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 
293     // Vector reductions
294     setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
295     setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
296     setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
297     setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
298     setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
299     setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
300     setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
301     setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
302     setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
303 
304     if (!HasMVEFP) {
305       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
306       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
307       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
308       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
309     }
310 
311     // Pre and Post inc are supported on loads and stores
312     for (unsigned im = (unsigned)ISD::PRE_INC;
313          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
314       setIndexedLoadAction(im, VT, Legal);
315       setIndexedStoreAction(im, VT, Legal);
316       setIndexedMaskedLoadAction(im, VT, Legal);
317       setIndexedMaskedStoreAction(im, VT, Legal);
318     }
319   }
320 
321   const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
322   for (auto VT : FloatTypes) {
323     addRegisterClass(VT, &ARM::MQPRRegClass);
324     if (!HasMVEFP)
325       setAllExpand(VT);
326 
327     // These are legal or custom whether we have MVE.fp or not
328     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
329     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
330     setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
331     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
332     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
333     setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
334     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
335     setOperationAction(ISD::SETCC, VT, Custom);
336     setOperationAction(ISD::MLOAD, VT, Custom);
337     setOperationAction(ISD::MSTORE, VT, Legal);
338 
339     // Pre and Post inc are supported on loads and stores
340     for (unsigned im = (unsigned)ISD::PRE_INC;
341          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
342       setIndexedLoadAction(im, VT, Legal);
343       setIndexedStoreAction(im, VT, Legal);
344       setIndexedMaskedLoadAction(im, VT, Legal);
345       setIndexedMaskedStoreAction(im, VT, Legal);
346     }
347 
348     if (HasMVEFP) {
349       setOperationAction(ISD::FMINNUM, VT, Legal);
350       setOperationAction(ISD::FMAXNUM, VT, Legal);
351       setOperationAction(ISD::FROUND, VT, Legal);
352       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
353       setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
354       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
355       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
356 
357       // No native support for these.
358       setOperationAction(ISD::FDIV, VT, Expand);
359       setOperationAction(ISD::FREM, VT, Expand);
360       setOperationAction(ISD::FSQRT, VT, Expand);
361       setOperationAction(ISD::FSIN, VT, Expand);
362       setOperationAction(ISD::FCOS, VT, Expand);
363       setOperationAction(ISD::FPOW, VT, Expand);
364       setOperationAction(ISD::FLOG, VT, Expand);
365       setOperationAction(ISD::FLOG2, VT, Expand);
366       setOperationAction(ISD::FLOG10, VT, Expand);
367       setOperationAction(ISD::FEXP, VT, Expand);
368       setOperationAction(ISD::FEXP2, VT, Expand);
369       setOperationAction(ISD::FNEARBYINT, VT, Expand);
370     }
371   }
372 
373   // Custom Expand smaller than legal vector reductions to prevent false zero
374   // items being added.
375   setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
376   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
377   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
378   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
379   setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
380   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
381   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
382   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
383 
384   // We 'support' these types up to bitcast/load/store level, regardless of
385   // MVE integer-only / float support. Only doing FP data processing on the FP
386   // vector types is inhibited at integer-only level.
387   const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
388   for (auto VT : LongTypes) {
389     addRegisterClass(VT, &ARM::MQPRRegClass);
390     setAllExpand(VT);
391     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
392     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
393     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
394   }
395   // We can do bitwise operations on v2i64 vectors
396   setOperationAction(ISD::AND, MVT::v2i64, Legal);
397   setOperationAction(ISD::OR, MVT::v2i64, Legal);
398   setOperationAction(ISD::XOR, MVT::v2i64, Legal);
399 
400   // It is legal to extload from v4i8 to v4i16 or v4i32.
401   addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
402   addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
403   addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
404 
405   // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
410   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
411 
412   // Some truncating stores are legal too.
413   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
414   setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
415   setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
416 
417   // Pre and Post inc on these are legal, given the correct extends
418   for (unsigned im = (unsigned)ISD::PRE_INC;
419        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
420     for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
421       setIndexedLoadAction(im, VT, Legal);
422       setIndexedStoreAction(im, VT, Legal);
423       setIndexedMaskedLoadAction(im, VT, Legal);
424       setIndexedMaskedStoreAction(im, VT, Legal);
425     }
426   }
427 
428   // Predicate types
429   const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
430   for (auto VT : pTypes) {
431     addRegisterClass(VT, &ARM::VCCRRegClass);
432     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
433     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
434     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
435     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
436     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
437     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
438     setOperationAction(ISD::SETCC, VT, Custom);
439     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
440     setOperationAction(ISD::LOAD, VT, Custom);
441     setOperationAction(ISD::STORE, VT, Custom);
442   }
443 }
444 
445 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
446                                      const ARMSubtarget &STI)
447     : TargetLowering(TM), Subtarget(&STI) {
448   RegInfo = Subtarget->getRegisterInfo();
449   Itins = Subtarget->getInstrItineraryData();
450 
451   setBooleanContents(ZeroOrOneBooleanContent);
452   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
453 
454   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
455       !Subtarget->isTargetWatchOS()) {
456     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
457     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
458       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
459                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
460                                        : CallingConv::ARM_AAPCS);
461   }
462 
463   if (Subtarget->isTargetMachO()) {
464     // Uses VFP for Thumb libfuncs if available.
465     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
466         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
467       static const struct {
468         const RTLIB::Libcall Op;
469         const char * const Name;
470         const ISD::CondCode Cond;
471       } LibraryCalls[] = {
472         // Single-precision floating-point arithmetic.
473         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
474         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
475         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
476         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
477 
478         // Double-precision floating-point arithmetic.
479         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
480         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
481         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
482         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
483 
484         // Single-precision comparisons.
485         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
486         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
487         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
488         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
489         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
490         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
491         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
492 
493         // Double-precision comparisons.
494         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
495         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
496         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
497         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
498         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
499         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
500         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
501 
502         // Floating-point to integer conversions.
503         // i64 conversions are done via library routines even when generating VFP
504         // instructions, so use the same ones.
505         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
506         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
507         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
508         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
509 
510         // Conversions between floating types.
511         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
512         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
513 
514         // Integer to floating-point conversions.
515         // i64 conversions are done via library routines even when generating VFP
516         // instructions, so use the same ones.
517         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
518         // e.g., __floatunsidf vs. __floatunssidfvfp.
519         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
520         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
521         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
522         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
523       };
524 
525       for (const auto &LC : LibraryCalls) {
526         setLibcallName(LC.Op, LC.Name);
527         if (LC.Cond != ISD::SETCC_INVALID)
528           setCmpLibcallCC(LC.Op, LC.Cond);
529       }
530     }
531   }
532 
533   // These libcalls are not available in 32-bit.
534   setLibcallName(RTLIB::SHL_I128, nullptr);
535   setLibcallName(RTLIB::SRL_I128, nullptr);
536   setLibcallName(RTLIB::SRA_I128, nullptr);
537 
538   // RTLIB
539   if (Subtarget->isAAPCS_ABI() &&
540       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
541        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
542     static const struct {
543       const RTLIB::Libcall Op;
544       const char * const Name;
545       const CallingConv::ID CC;
546       const ISD::CondCode Cond;
547     } LibraryCalls[] = {
548       // Double-precision floating-point arithmetic helper functions
549       // RTABI chapter 4.1.2, Table 2
550       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
554 
555       // Double-precision floating-point comparison helper functions
556       // RTABI chapter 4.1.2, Table 3
557       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
558       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
559       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
560       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
561       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
562       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
563       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
564 
565       // Single-precision floating-point arithmetic helper functions
566       // RTABI chapter 4.1.2, Table 4
567       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
570       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
571 
572       // Single-precision floating-point comparison helper functions
573       // RTABI chapter 4.1.2, Table 5
574       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
575       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
576       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
577       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
578       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
579       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
580       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
581 
582       // Floating-point to integer conversions.
583       // RTABI chapter 4.1.2, Table 6
584       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
587       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
588       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
589       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 
593       // Conversions between floating types.
594       // RTABI chapter 4.1.2, Table 7
595       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
596       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
597       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
598 
599       // Integer to floating-point conversions.
600       // RTABI chapter 4.1.2, Table 8
601       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
604       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
605       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
606       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
607       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
608       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 
610       // Long long helper functions
611       // RTABI chapter 4.2, Table 9
612       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
614       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
615       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
616 
617       // Integer division functions
618       // RTABI chapter 4.3.1
619       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
620       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
621       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
622       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
623       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
624       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627     };
628 
629     for (const auto &LC : LibraryCalls) {
630       setLibcallName(LC.Op, LC.Name);
631       setLibcallCallingConv(LC.Op, LC.CC);
632       if (LC.Cond != ISD::SETCC_INVALID)
633         setCmpLibcallCC(LC.Op, LC.Cond);
634     }
635 
636     // EABI dependent RTLIB
637     if (TM.Options.EABIVersion == EABI::EABI4 ||
638         TM.Options.EABIVersion == EABI::EABI5) {
639       static const struct {
640         const RTLIB::Libcall Op;
641         const char *const Name;
642         const CallingConv::ID CC;
643         const ISD::CondCode Cond;
644       } MemOpsLibraryCalls[] = {
645         // Memory operations
646         // RTABI chapter 4.3.4
647         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
648         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
649         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
650       };
651 
652       for (const auto &LC : MemOpsLibraryCalls) {
653         setLibcallName(LC.Op, LC.Name);
654         setLibcallCallingConv(LC.Op, LC.CC);
655         if (LC.Cond != ISD::SETCC_INVALID)
656           setCmpLibcallCC(LC.Op, LC.Cond);
657       }
658     }
659   }
660 
661   if (Subtarget->isTargetWindows()) {
662     static const struct {
663       const RTLIB::Libcall Op;
664       const char * const Name;
665       const CallingConv::ID CC;
666     } LibraryCalls[] = {
667       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
668       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
669       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
670       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
671       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
672       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
673       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
674       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
675     };
676 
677     for (const auto &LC : LibraryCalls) {
678       setLibcallName(LC.Op, LC.Name);
679       setLibcallCallingConv(LC.Op, LC.CC);
680     }
681   }
682 
683   // Use divmod compiler-rt calls for iOS 5.0 and later.
684   if (Subtarget->isTargetMachO() &&
685       !(Subtarget->isTargetIOS() &&
686         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
687     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
688     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
689   }
690 
691   // The half <-> float conversion functions are always soft-float on
692   // non-watchos platforms, but are needed for some targets which use a
693   // hard-float calling convention by default.
694   if (!Subtarget->isTargetWatchABI()) {
695     if (Subtarget->isAAPCS_ABI()) {
696       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
697       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
698       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
699     } else {
700       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
701       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
702       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
703     }
704   }
705 
706   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
707   // a __gnu_ prefix (which is the default).
708   if (Subtarget->isTargetAEABI()) {
709     static const struct {
710       const RTLIB::Libcall Op;
711       const char * const Name;
712       const CallingConv::ID CC;
713     } LibraryCalls[] = {
714       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
715       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
716       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
717     };
718 
719     for (const auto &LC : LibraryCalls) {
720       setLibcallName(LC.Op, LC.Name);
721       setLibcallCallingConv(LC.Op, LC.CC);
722     }
723   }
724 
725   if (Subtarget->isThumb1Only())
726     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
727   else
728     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
729 
730   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
731       Subtarget->hasFPRegs()) {
732     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
733     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
734     if (!Subtarget->hasVFP2Base())
735       setAllExpand(MVT::f32);
736     if (!Subtarget->hasFP64())
737       setAllExpand(MVT::f64);
738   }
739 
740   if (Subtarget->hasFullFP16()) {
741     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
742     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
743     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
744 
745     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
746     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
747   }
748 
749   if (Subtarget->hasBF16()) {
750     addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
751     setAllExpand(MVT::bf16);
752     if (!Subtarget->hasFullFP16())
753       setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
754   }
755 
756   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
757     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
758       setTruncStoreAction(VT, InnerVT, Expand);
759       addAllExtLoads(VT, InnerVT, Expand);
760     }
761 
762     setOperationAction(ISD::MULHS, VT, Expand);
763     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
764     setOperationAction(ISD::MULHU, VT, Expand);
765     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
766 
767     setOperationAction(ISD::BSWAP, VT, Expand);
768   }
769 
770   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
771   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
772 
773   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
774   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
775 
776   if (Subtarget->hasMVEIntegerOps())
777     addMVEVectorTypes(Subtarget->hasMVEFloatOps());
778 
779   // Combine low-overhead loop intrinsics so that we can lower i1 types.
780   if (Subtarget->hasLOB()) {
781     setTargetDAGCombine(ISD::BRCOND);
782     setTargetDAGCombine(ISD::BR_CC);
783   }
784 
785   if (Subtarget->hasNEON()) {
786     addDRTypeForNEON(MVT::v2f32);
787     addDRTypeForNEON(MVT::v8i8);
788     addDRTypeForNEON(MVT::v4i16);
789     addDRTypeForNEON(MVT::v2i32);
790     addDRTypeForNEON(MVT::v1i64);
791 
792     addQRTypeForNEON(MVT::v4f32);
793     addQRTypeForNEON(MVT::v2f64);
794     addQRTypeForNEON(MVT::v16i8);
795     addQRTypeForNEON(MVT::v8i16);
796     addQRTypeForNEON(MVT::v4i32);
797     addQRTypeForNEON(MVT::v2i64);
798 
799     if (Subtarget->hasFullFP16()) {
800       addQRTypeForNEON(MVT::v8f16);
801       addDRTypeForNEON(MVT::v4f16);
802     }
803 
804     if (Subtarget->hasBF16()) {
805       addQRTypeForNEON(MVT::v8bf16);
806       addDRTypeForNEON(MVT::v4bf16);
807     }
808   }
809 
810   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
811     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
812     // none of Neon, MVE or VFP supports any arithmetic operations on it.
813     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
814     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
815     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
816     // FIXME: Code duplication: FDIV and FREM are expanded always, see
817     // ARMTargetLowering::addTypeForNEON method for details.
818     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
819     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
820     // FIXME: Create unittest.
821     // In another words, find a way when "copysign" appears in DAG with vector
822     // operands.
823     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
824     // FIXME: Code duplication: SETCC has custom operation action, see
825     // ARMTargetLowering::addTypeForNEON method for details.
826     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
827     // FIXME: Create unittest for FNEG and for FABS.
828     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
829     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
830     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
831     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
832     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
833     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
834     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
835     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
836     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
837     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
838     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
839     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
840     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
841     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
842     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
843     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
844     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
845     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
846   }
847 
848   if (Subtarget->hasNEON()) {
849     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
850     // supported for v4f32.
851     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
852     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
853     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
854     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
855     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
856     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
857     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
858     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
859     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
860     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
861     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
862     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
863     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
864     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
865 
866     // Mark v2f32 intrinsics.
867     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
868     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
869     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
870     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
871     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
872     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
873     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
874     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
875     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
876     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
877     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
878     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
879     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
880     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
881 
882     // Neon does not support some operations on v1i64 and v2i64 types.
883     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
884     // Custom handling for some quad-vector types to detect VMULL.
885     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
886     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
887     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
888     // Custom handling for some vector types to avoid expensive expansions
889     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
890     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
891     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
892     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
893     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
894     // a destination type that is wider than the source, and nor does
895     // it have a FP_TO_[SU]INT instruction with a narrower destination than
896     // source.
897     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
898     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
899     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
900     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
901     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
902     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
903     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
904     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
905 
906     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
907     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
908 
909     // NEON does not have single instruction CTPOP for vectors with element
910     // types wider than 8-bits.  However, custom lowering can leverage the
911     // v8i8/v16i8 vcnt instruction.
912     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
913     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
914     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
915     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
916     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
917     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
918 
919     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
920     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
921 
922     // NEON does not have single instruction CTTZ for vectors.
923     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
924     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
925     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
926     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
927 
928     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
929     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
930     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
931     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
932 
933     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
934     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
935     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
936     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
937 
938     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
939     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
940     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
941     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
942 
943     // NEON only has FMA instructions as of VFP4.
944     if (!Subtarget->hasVFP4Base()) {
945       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
946       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
947     }
948 
949     setTargetDAGCombine(ISD::SHL);
950     setTargetDAGCombine(ISD::SRL);
951     setTargetDAGCombine(ISD::SRA);
952     setTargetDAGCombine(ISD::FP_TO_SINT);
953     setTargetDAGCombine(ISD::FP_TO_UINT);
954     setTargetDAGCombine(ISD::FDIV);
955     setTargetDAGCombine(ISD::LOAD);
956 
957     // It is legal to extload from v4i8 to v4i16 or v4i32.
958     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
959                    MVT::v2i32}) {
960       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
961         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
962         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
963         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
964       }
965     }
966   }
967 
968   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
969     setTargetDAGCombine(ISD::BUILD_VECTOR);
970     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
971     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
972     setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
973     setTargetDAGCombine(ISD::STORE);
974     setTargetDAGCombine(ISD::SIGN_EXTEND);
975     setTargetDAGCombine(ISD::ZERO_EXTEND);
976     setTargetDAGCombine(ISD::ANY_EXTEND);
977     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
978     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
979     setTargetDAGCombine(ISD::INTRINSIC_VOID);
980     setTargetDAGCombine(ISD::VECREDUCE_ADD);
981     setTargetDAGCombine(ISD::ADD);
982     setTargetDAGCombine(ISD::BITCAST);
983   }
984   if (Subtarget->hasMVEIntegerOps()) {
985     setTargetDAGCombine(ISD::SMIN);
986     setTargetDAGCombine(ISD::UMIN);
987     setTargetDAGCombine(ISD::SMAX);
988     setTargetDAGCombine(ISD::UMAX);
989     setTargetDAGCombine(ISD::FP_EXTEND);
990     setTargetDAGCombine(ISD::SELECT);
991     setTargetDAGCombine(ISD::SELECT_CC);
992   }
993 
994   if (!Subtarget->hasFP64()) {
995     // When targeting a floating-point unit with only single-precision
996     // operations, f64 is legal for the few double-precision instructions which
997     // are present However, no double-precision operations other than moves,
998     // loads and stores are provided by the hardware.
999     setOperationAction(ISD::FADD,       MVT::f64, Expand);
1000     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
1001     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
1002     setOperationAction(ISD::FMA,        MVT::f64, Expand);
1003     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
1004     setOperationAction(ISD::FREM,       MVT::f64, Expand);
1005     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
1006     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
1007     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
1008     setOperationAction(ISD::FABS,       MVT::f64, Expand);
1009     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
1010     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
1011     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
1012     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
1013     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
1014     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
1015     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
1016     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
1017     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
1018     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
1019     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
1020     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
1021     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1022     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
1023     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1024     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1025     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1026     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1027     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1028     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1029     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
1030     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1031     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1032     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1033     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1034     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
1035   }
1036 
1037   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1038     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
1039     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1040     if (Subtarget->hasFullFP16()) {
1041       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
1042       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1043     }
1044   }
1045 
1046   if (!Subtarget->hasFP16()) {
1047     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1048     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1049   }
1050 
1051   computeRegisterProperties(Subtarget->getRegisterInfo());
1052 
1053   // ARM does not have floating-point extending loads.
1054   for (MVT VT : MVT::fp_valuetypes()) {
1055     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1056     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1057   }
1058 
1059   // ... or truncating stores
1060   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1061   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1062   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1063 
1064   // ARM does not have i1 sign extending load.
1065   for (MVT VT : MVT::integer_valuetypes())
1066     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1067 
1068   // ARM supports all 4 flavors of integer indexed load / store.
1069   if (!Subtarget->isThumb1Only()) {
1070     for (unsigned im = (unsigned)ISD::PRE_INC;
1071          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1072       setIndexedLoadAction(im,  MVT::i1,  Legal);
1073       setIndexedLoadAction(im,  MVT::i8,  Legal);
1074       setIndexedLoadAction(im,  MVT::i16, Legal);
1075       setIndexedLoadAction(im,  MVT::i32, Legal);
1076       setIndexedStoreAction(im, MVT::i1,  Legal);
1077       setIndexedStoreAction(im, MVT::i8,  Legal);
1078       setIndexedStoreAction(im, MVT::i16, Legal);
1079       setIndexedStoreAction(im, MVT::i32, Legal);
1080     }
1081   } else {
1082     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1083     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1084     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1085   }
1086 
1087   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1088   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1089   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1090   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1091 
1092   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1093   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1094   if (Subtarget->hasDSP()) {
1095     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1096     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1097     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1098     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1099   }
1100   if (Subtarget->hasBaseDSP()) {
1101     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1102     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1103   }
1104 
1105   // i64 operation support.
1106   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1107   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1108   if (Subtarget->isThumb1Only()) {
1109     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1110     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1111   }
1112   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1113       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1114     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1115 
1116   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1117   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1118   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1119   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1120   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1121   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1122   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1123   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1124   setOperationAction(ISD::STORE, MVT::i64, Custom);
1125 
1126   // MVE lowers 64 bit shifts to lsll and lsrl
1127   // assuming that ISD::SRL and SRA of i64 are already marked custom
1128   if (Subtarget->hasMVEIntegerOps())
1129     setOperationAction(ISD::SHL, MVT::i64, Custom);
1130 
1131   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1132   if (Subtarget->isThumb1Only()) {
1133     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1134     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1135     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1136   }
1137 
1138   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1139     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1140 
1141   // ARM does not have ROTL.
1142   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1143   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1144     setOperationAction(ISD::ROTL, VT, Expand);
1145     setOperationAction(ISD::ROTR, VT, Expand);
1146   }
1147   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1148   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1149   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1150     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1151     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1152   }
1153 
1154   // @llvm.readcyclecounter requires the Performance Monitors extension.
1155   // Default to the 0 expansion on unsupported platforms.
1156   // FIXME: Technically there are older ARM CPUs that have
1157   // implementation-specific ways of obtaining this information.
1158   if (Subtarget->hasPerfMon())
1159     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1160 
1161   // Only ARMv6 has BSWAP.
1162   if (!Subtarget->hasV6Ops())
1163     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1164 
1165   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1166                                         : Subtarget->hasDivideInARMMode();
1167   if (!hasDivide) {
1168     // These are expanded into libcalls if the cpu doesn't have HW divider.
1169     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1170     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1171   }
1172 
1173   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1174     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1175     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1176 
1177     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1178     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1179   }
1180 
1181   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1182   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1183 
1184   // Register based DivRem for AEABI (RTABI 4.2)
1185   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1186       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1187       Subtarget->isTargetWindows()) {
1188     setOperationAction(ISD::SREM, MVT::i64, Custom);
1189     setOperationAction(ISD::UREM, MVT::i64, Custom);
1190     HasStandaloneRem = false;
1191 
1192     if (Subtarget->isTargetWindows()) {
1193       const struct {
1194         const RTLIB::Libcall Op;
1195         const char * const Name;
1196         const CallingConv::ID CC;
1197       } LibraryCalls[] = {
1198         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1199         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1200         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1201         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1202 
1203         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1204         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1205         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1206         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1207       };
1208 
1209       for (const auto &LC : LibraryCalls) {
1210         setLibcallName(LC.Op, LC.Name);
1211         setLibcallCallingConv(LC.Op, LC.CC);
1212       }
1213     } else {
1214       const struct {
1215         const RTLIB::Libcall Op;
1216         const char * const Name;
1217         const CallingConv::ID CC;
1218       } LibraryCalls[] = {
1219         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1220         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1221         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1222         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1223 
1224         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1225         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1226         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1227         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1228       };
1229 
1230       for (const auto &LC : LibraryCalls) {
1231         setLibcallName(LC.Op, LC.Name);
1232         setLibcallCallingConv(LC.Op, LC.CC);
1233       }
1234     }
1235 
1236     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1237     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1238     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1239     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1240   } else {
1241     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1242     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1243   }
1244 
1245   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1246     // MSVCRT doesn't have powi; fall back to pow
1247     setLibcallName(RTLIB::POWI_F32, nullptr);
1248     setLibcallName(RTLIB::POWI_F64, nullptr);
1249   }
1250 
1251   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1252   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1253   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1254   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1255 
1256   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1257   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1258 
1259   // Use the default implementation.
1260   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1261   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1262   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1263   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1264   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1265   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1266 
1267   if (Subtarget->isTargetWindows())
1268     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1269   else
1270     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1271 
1272   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1273   // the default expansion.
1274   InsertFencesForAtomic = false;
1275   if (Subtarget->hasAnyDataBarrier() &&
1276       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1277     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1278     // to ldrex/strex loops already.
1279     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1280     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1281       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1282 
1283     // On v8, we have particularly efficient implementations of atomic fences
1284     // if they can be combined with nearby atomic loads and stores.
1285     if (!Subtarget->hasAcquireRelease() ||
1286         getTargetMachine().getOptLevel() == 0) {
1287       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1288       InsertFencesForAtomic = true;
1289     }
1290   } else {
1291     // If there's anything we can use as a barrier, go through custom lowering
1292     // for ATOMIC_FENCE.
1293     // If target has DMB in thumb, Fences can be inserted.
1294     if (Subtarget->hasDataBarrier())
1295       InsertFencesForAtomic = true;
1296 
1297     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1298                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1299 
1300     // Set them all for expansion, which will force libcalls.
1301     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1302     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1303     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1304     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1305     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1306     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1307     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1308     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1309     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1310     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1311     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1312     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1313     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1314     // Unordered/Monotonic case.
1315     if (!InsertFencesForAtomic) {
1316       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1317       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1318     }
1319   }
1320 
1321   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1322 
1323   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1324   if (!Subtarget->hasV6Ops()) {
1325     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1326     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1327   }
1328   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1329 
1330   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1331       !Subtarget->isThumb1Only()) {
1332     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1333     // iff target supports vfp2.
1334     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1335     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1336   }
1337 
1338   // We want to custom lower some of our intrinsics.
1339   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1340   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1341   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1342   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1343   if (Subtarget->useSjLjEH())
1344     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1345 
1346   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1347   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1348   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1349   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1350   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1351   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1352   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1353   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1354   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1355   if (Subtarget->hasFullFP16()) {
1356     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1357     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1358     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1359   }
1360 
1361   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1362 
1363   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1364   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1365   if (Subtarget->hasFullFP16())
1366       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1367   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1368   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1369   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1370 
1371   // We don't support sin/cos/fmod/copysign/pow
1372   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1373   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1374   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1375   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1376   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1377   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1378   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1379   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1380   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1381       !Subtarget->isThumb1Only()) {
1382     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1383     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1384   }
1385   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1386   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1387 
1388   if (!Subtarget->hasVFP4Base()) {
1389     setOperationAction(ISD::FMA, MVT::f64, Expand);
1390     setOperationAction(ISD::FMA, MVT::f32, Expand);
1391   }
1392 
1393   // Various VFP goodness
1394   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1395     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1396     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1397       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1398       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1399     }
1400 
1401     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1402     if (!Subtarget->hasFP16()) {
1403       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1404       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1405     }
1406 
1407     // Strict floating-point comparisons need custom lowering.
1408     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1409     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1410     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1411     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1412     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1413     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1414   }
1415 
1416   // Use __sincos_stret if available.
1417   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1418       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1419     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1420     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1421   }
1422 
1423   // FP-ARMv8 implements a lot of rounding-like FP operations.
1424   if (Subtarget->hasFPARMv8Base()) {
1425     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1426     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1427     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1428     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1429     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1430     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1431     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1432     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1433     if (Subtarget->hasNEON()) {
1434       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1435       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1436       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1437       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1438     }
1439 
1440     if (Subtarget->hasFP64()) {
1441       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1442       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1443       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1444       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1445       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1446       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1447       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1448       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1449     }
1450   }
1451 
1452   // FP16 often need to be promoted to call lib functions
1453   if (Subtarget->hasFullFP16()) {
1454     setOperationAction(ISD::FREM, MVT::f16, Promote);
1455     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1456     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1457     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1458     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1459     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1460     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1461     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1462     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1463     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1464     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1465     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1466 
1467     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1468   }
1469 
1470   if (Subtarget->hasNEON()) {
1471     // vmin and vmax aren't available in a scalar form, so we can use
1472     // a NEON instruction with an undef lane instead.  This has a performance
1473     // penalty on some cores, so we don't do this unless we have been
1474     // asked to by the core tuning model.
1475     if (Subtarget->useNEONForSinglePrecisionFP()) {
1476       setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1477       setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1478       setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1479       setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1480     }
1481     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1482     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1483     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1484     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1485 
1486     if (Subtarget->hasFullFP16()) {
1487       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1488       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1489       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1490       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1491 
1492       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1493       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1494       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1495       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1496     }
1497   }
1498 
1499   // We have target-specific dag combine patterns for the following nodes:
1500   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1501   setTargetDAGCombine(ISD::ADD);
1502   setTargetDAGCombine(ISD::SUB);
1503   setTargetDAGCombine(ISD::MUL);
1504   setTargetDAGCombine(ISD::AND);
1505   setTargetDAGCombine(ISD::OR);
1506   setTargetDAGCombine(ISD::XOR);
1507 
1508   if (Subtarget->hasMVEIntegerOps())
1509     setTargetDAGCombine(ISD::VSELECT);
1510 
1511   if (Subtarget->hasV6Ops())
1512     setTargetDAGCombine(ISD::SRL);
1513   if (Subtarget->isThumb1Only())
1514     setTargetDAGCombine(ISD::SHL);
1515 
1516   setStackPointerRegisterToSaveRestore(ARM::SP);
1517 
1518   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1519       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1520     setSchedulingPreference(Sched::RegPressure);
1521   else
1522     setSchedulingPreference(Sched::Hybrid);
1523 
1524   //// temporary - rewrite interface to use type
1525   MaxStoresPerMemset = 8;
1526   MaxStoresPerMemsetOptSize = 4;
1527   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1528   MaxStoresPerMemcpyOptSize = 2;
1529   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1530   MaxStoresPerMemmoveOptSize = 2;
1531 
1532   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1533   // are at least 4 bytes aligned.
1534   setMinStackArgumentAlignment(Align(4));
1535 
1536   // Prefer likely predicted branches to selects on out-of-order cores.
1537   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1538 
1539   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1540 
1541   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1542 
1543   if (Subtarget->isThumb() || Subtarget->isThumb2())
1544     setTargetDAGCombine(ISD::ABS);
1545 }
1546 
1547 bool ARMTargetLowering::useSoftFloat() const {
1548   return Subtarget->useSoftFloat();
1549 }
1550 
1551 // FIXME: It might make sense to define the representative register class as the
1552 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1553 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1554 // SPR's representative would be DPR_VFP2. This should work well if register
1555 // pressure tracking were modified such that a register use would increment the
1556 // pressure of the register class's representative and all of it's super
1557 // classes' representatives transitively. We have not implemented this because
1558 // of the difficulty prior to coalescing of modeling operand register classes
1559 // due to the common occurrence of cross class copies and subregister insertions
1560 // and extractions.
1561 std::pair<const TargetRegisterClass *, uint8_t>
1562 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1563                                            MVT VT) const {
1564   const TargetRegisterClass *RRC = nullptr;
1565   uint8_t Cost = 1;
1566   switch (VT.SimpleTy) {
1567   default:
1568     return TargetLowering::findRepresentativeClass(TRI, VT);
1569   // Use DPR as representative register class for all floating point
1570   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1571   // the cost is 1 for both f32 and f64.
1572   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1573   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1574     RRC = &ARM::DPRRegClass;
1575     // When NEON is used for SP, only half of the register file is available
1576     // because operations that define both SP and DP results will be constrained
1577     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1578     // coalescing by double-counting the SP regs. See the FIXME above.
1579     if (Subtarget->useNEONForSinglePrecisionFP())
1580       Cost = 2;
1581     break;
1582   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1583   case MVT::v4f32: case MVT::v2f64:
1584     RRC = &ARM::DPRRegClass;
1585     Cost = 2;
1586     break;
1587   case MVT::v4i64:
1588     RRC = &ARM::DPRRegClass;
1589     Cost = 4;
1590     break;
1591   case MVT::v8i64:
1592     RRC = &ARM::DPRRegClass;
1593     Cost = 8;
1594     break;
1595   }
1596   return std::make_pair(RRC, Cost);
1597 }
1598 
1599 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1600   switch ((ARMISD::NodeType)Opcode) {
1601   case ARMISD::FIRST_NUMBER:  break;
1602   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1603   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1604   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1605   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1606   case ARMISD::CALL:          return "ARMISD::CALL";
1607   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1608   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1609   case ARMISD::tSECALL:       return "ARMISD::tSECALL";
1610   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1611   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1612   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1613   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1614   case ARMISD::SERET_FLAG:    return "ARMISD::SERET_FLAG";
1615   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1616   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1617   case ARMISD::CMP:           return "ARMISD::CMP";
1618   case ARMISD::CMN:           return "ARMISD::CMN";
1619   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1620   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1621   case ARMISD::CMPFPE:        return "ARMISD::CMPFPE";
1622   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1623   case ARMISD::CMPFPEw0:      return "ARMISD::CMPFPEw0";
1624   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1625   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1626 
1627   case ARMISD::CMOV:          return "ARMISD::CMOV";
1628   case ARMISD::SUBS:          return "ARMISD::SUBS";
1629 
1630   case ARMISD::SSAT:          return "ARMISD::SSAT";
1631   case ARMISD::USAT:          return "ARMISD::USAT";
1632 
1633   case ARMISD::ASRL:          return "ARMISD::ASRL";
1634   case ARMISD::LSRL:          return "ARMISD::LSRL";
1635   case ARMISD::LSLL:          return "ARMISD::LSLL";
1636 
1637   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1638   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1639   case ARMISD::RRX:           return "ARMISD::RRX";
1640 
1641   case ARMISD::ADDC:          return "ARMISD::ADDC";
1642   case ARMISD::ADDE:          return "ARMISD::ADDE";
1643   case ARMISD::SUBC:          return "ARMISD::SUBC";
1644   case ARMISD::SUBE:          return "ARMISD::SUBE";
1645   case ARMISD::LSLS:          return "ARMISD::LSLS";
1646 
1647   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1648   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1649   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1650   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1651   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1652 
1653   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1654   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1655   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1656 
1657   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1658 
1659   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1660 
1661   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1662 
1663   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1664 
1665   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1666 
1667   case ARMISD::LDRD:          return "ARMISD::LDRD";
1668   case ARMISD::STRD:          return "ARMISD::STRD";
1669 
1670   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1671   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1672 
1673   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1674   case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1675   case ARMISD::VCMP:          return "ARMISD::VCMP";
1676   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1677   case ARMISD::VTST:          return "ARMISD::VTST";
1678 
1679   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1680   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1681   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1682   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1683   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1684   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1685   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1686   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1687   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1688   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1689   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1690   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1691   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1692   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1693   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1694   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1695   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1696   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1697   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1698   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1699   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1700   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1701   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1702   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1703   case ARMISD::VDUP:          return "ARMISD::VDUP";
1704   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1705   case ARMISD::VEXT:          return "ARMISD::VEXT";
1706   case ARMISD::VREV64:        return "ARMISD::VREV64";
1707   case ARMISD::VREV32:        return "ARMISD::VREV32";
1708   case ARMISD::VREV16:        return "ARMISD::VREV16";
1709   case ARMISD::VZIP:          return "ARMISD::VZIP";
1710   case ARMISD::VUZP:          return "ARMISD::VUZP";
1711   case ARMISD::VTRN:          return "ARMISD::VTRN";
1712   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1713   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1714   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1715   case ARMISD::VQMOVNs:       return "ARMISD::VQMOVNs";
1716   case ARMISD::VQMOVNu:       return "ARMISD::VQMOVNu";
1717   case ARMISD::VCVTN:         return "ARMISD::VCVTN";
1718   case ARMISD::VCVTL:         return "ARMISD::VCVTL";
1719   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1720   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1721   case ARMISD::VQDMULH:       return "ARMISD::VQDMULH";
1722   case ARMISD::VADDVs:        return "ARMISD::VADDVs";
1723   case ARMISD::VADDVu:        return "ARMISD::VADDVu";
1724   case ARMISD::VADDVps:       return "ARMISD::VADDVps";
1725   case ARMISD::VADDVpu:       return "ARMISD::VADDVpu";
1726   case ARMISD::VADDLVs:       return "ARMISD::VADDLVs";
1727   case ARMISD::VADDLVu:       return "ARMISD::VADDLVu";
1728   case ARMISD::VADDLVAs:      return "ARMISD::VADDLVAs";
1729   case ARMISD::VADDLVAu:      return "ARMISD::VADDLVAu";
1730   case ARMISD::VADDLVps:      return "ARMISD::VADDLVps";
1731   case ARMISD::VADDLVpu:      return "ARMISD::VADDLVpu";
1732   case ARMISD::VADDLVAps:     return "ARMISD::VADDLVAps";
1733   case ARMISD::VADDLVApu:     return "ARMISD::VADDLVApu";
1734   case ARMISD::VMLAVs:        return "ARMISD::VMLAVs";
1735   case ARMISD::VMLAVu:        return "ARMISD::VMLAVu";
1736   case ARMISD::VMLAVps:       return "ARMISD::VMLAVps";
1737   case ARMISD::VMLAVpu:       return "ARMISD::VMLAVpu";
1738   case ARMISD::VMLALVs:       return "ARMISD::VMLALVs";
1739   case ARMISD::VMLALVu:       return "ARMISD::VMLALVu";
1740   case ARMISD::VMLALVps:      return "ARMISD::VMLALVps";
1741   case ARMISD::VMLALVpu:      return "ARMISD::VMLALVpu";
1742   case ARMISD::VMLALVAs:      return "ARMISD::VMLALVAs";
1743   case ARMISD::VMLALVAu:      return "ARMISD::VMLALVAu";
1744   case ARMISD::VMLALVAps:     return "ARMISD::VMLALVAps";
1745   case ARMISD::VMLALVApu:     return "ARMISD::VMLALVApu";
1746   case ARMISD::VMINVu:        return "ARMISD::VMINVu";
1747   case ARMISD::VMINVs:        return "ARMISD::VMINVs";
1748   case ARMISD::VMAXVu:        return "ARMISD::VMAXVu";
1749   case ARMISD::VMAXVs:        return "ARMISD::VMAXVs";
1750   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1751   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1752   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1753   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1754   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1755   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1756   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1757   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1758   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1759   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1760   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1761   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1762   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1763   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1764   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1765   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1766   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1767   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1768   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1769   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1770   case ARMISD::BFI:           return "ARMISD::BFI";
1771   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1772   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1773   case ARMISD::VBSP:          return "ARMISD::VBSP";
1774   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1775   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1776   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1777   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1778   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1779   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1780   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1781   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1782   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1783   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1784   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1785   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1786   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1787   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1788   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1789   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1790   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1791   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1792   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1793   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1794   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1795   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1796   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1797   case ARMISD::WLS:           return "ARMISD::WLS";
1798   case ARMISD::LE:            return "ARMISD::LE";
1799   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1800   case ARMISD::CSINV:         return "ARMISD::CSINV";
1801   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1802   case ARMISD::CSINC:         return "ARMISD::CSINC";
1803   }
1804   return nullptr;
1805 }
1806 
1807 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1808                                           EVT VT) const {
1809   if (!VT.isVector())
1810     return getPointerTy(DL);
1811 
1812   // MVE has a predicate register.
1813   if (Subtarget->hasMVEIntegerOps() &&
1814       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1815     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1816   return VT.changeVectorElementTypeToInteger();
1817 }
1818 
1819 /// getRegClassFor - Return the register class that should be used for the
1820 /// specified value type.
1821 const TargetRegisterClass *
1822 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1823   (void)isDivergent;
1824   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1825   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1826   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1827   // MVE Q registers.
1828   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1829     if (VT == MVT::v4i64)
1830       return &ARM::QQPRRegClass;
1831     if (VT == MVT::v8i64)
1832       return &ARM::QQQQPRRegClass;
1833   }
1834   return TargetLowering::getRegClassFor(VT);
1835 }
1836 
1837 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1838 // source/dest is aligned and the copy size is large enough. We therefore want
1839 // to align such objects passed to memory intrinsics.
1840 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1841                                                unsigned &PrefAlign) const {
1842   if (!isa<MemIntrinsic>(CI))
1843     return false;
1844   MinSize = 8;
1845   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1846   // cycle faster than 4-byte aligned LDM.
1847   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1848   return true;
1849 }
1850 
1851 // Create a fast isel object.
1852 FastISel *
1853 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1854                                   const TargetLibraryInfo *libInfo) const {
1855   return ARM::createFastISel(funcInfo, libInfo);
1856 }
1857 
1858 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1859   unsigned NumVals = N->getNumValues();
1860   if (!NumVals)
1861     return Sched::RegPressure;
1862 
1863   for (unsigned i = 0; i != NumVals; ++i) {
1864     EVT VT = N->getValueType(i);
1865     if (VT == MVT::Glue || VT == MVT::Other)
1866       continue;
1867     if (VT.isFloatingPoint() || VT.isVector())
1868       return Sched::ILP;
1869   }
1870 
1871   if (!N->isMachineOpcode())
1872     return Sched::RegPressure;
1873 
1874   // Load are scheduled for latency even if there instruction itinerary
1875   // is not available.
1876   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1877   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1878 
1879   if (MCID.getNumDefs() == 0)
1880     return Sched::RegPressure;
1881   if (!Itins->isEmpty() &&
1882       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1883     return Sched::ILP;
1884 
1885   return Sched::RegPressure;
1886 }
1887 
1888 //===----------------------------------------------------------------------===//
1889 // Lowering Code
1890 //===----------------------------------------------------------------------===//
1891 
1892 static bool isSRL16(const SDValue &Op) {
1893   if (Op.getOpcode() != ISD::SRL)
1894     return false;
1895   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1896     return Const->getZExtValue() == 16;
1897   return false;
1898 }
1899 
1900 static bool isSRA16(const SDValue &Op) {
1901   if (Op.getOpcode() != ISD::SRA)
1902     return false;
1903   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1904     return Const->getZExtValue() == 16;
1905   return false;
1906 }
1907 
1908 static bool isSHL16(const SDValue &Op) {
1909   if (Op.getOpcode() != ISD::SHL)
1910     return false;
1911   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1912     return Const->getZExtValue() == 16;
1913   return false;
1914 }
1915 
1916 // Check for a signed 16-bit value. We special case SRA because it makes it
1917 // more simple when also looking for SRAs that aren't sign extending a
1918 // smaller value. Without the check, we'd need to take extra care with
1919 // checking order for some operations.
1920 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1921   if (isSRA16(Op))
1922     return isSHL16(Op.getOperand(0));
1923   return DAG.ComputeNumSignBits(Op) == 17;
1924 }
1925 
1926 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1927 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1928   switch (CC) {
1929   default: llvm_unreachable("Unknown condition code!");
1930   case ISD::SETNE:  return ARMCC::NE;
1931   case ISD::SETEQ:  return ARMCC::EQ;
1932   case ISD::SETGT:  return ARMCC::GT;
1933   case ISD::SETGE:  return ARMCC::GE;
1934   case ISD::SETLT:  return ARMCC::LT;
1935   case ISD::SETLE:  return ARMCC::LE;
1936   case ISD::SETUGT: return ARMCC::HI;
1937   case ISD::SETUGE: return ARMCC::HS;
1938   case ISD::SETULT: return ARMCC::LO;
1939   case ISD::SETULE: return ARMCC::LS;
1940   }
1941 }
1942 
1943 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1944 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1945                         ARMCC::CondCodes &CondCode2) {
1946   CondCode2 = ARMCC::AL;
1947   switch (CC) {
1948   default: llvm_unreachable("Unknown FP condition!");
1949   case ISD::SETEQ:
1950   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1951   case ISD::SETGT:
1952   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1953   case ISD::SETGE:
1954   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1955   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1956   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1957   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1958   case ISD::SETO:   CondCode = ARMCC::VC; break;
1959   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1960   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1961   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1962   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1963   case ISD::SETLT:
1964   case ISD::SETULT: CondCode = ARMCC::LT; break;
1965   case ISD::SETLE:
1966   case ISD::SETULE: CondCode = ARMCC::LE; break;
1967   case ISD::SETNE:
1968   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1969   }
1970 }
1971 
1972 //===----------------------------------------------------------------------===//
1973 //                      Calling Convention Implementation
1974 //===----------------------------------------------------------------------===//
1975 
1976 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1977 /// account presence of floating point hardware and calling convention
1978 /// limitations, such as support for variadic functions.
1979 CallingConv::ID
1980 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1981                                            bool isVarArg) const {
1982   switch (CC) {
1983   default:
1984     report_fatal_error("Unsupported calling convention");
1985   case CallingConv::ARM_AAPCS:
1986   case CallingConv::ARM_APCS:
1987   case CallingConv::GHC:
1988   case CallingConv::CFGuard_Check:
1989     return CC;
1990   case CallingConv::PreserveMost:
1991     return CallingConv::PreserveMost;
1992   case CallingConv::ARM_AAPCS_VFP:
1993   case CallingConv::Swift:
1994     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1995   case CallingConv::C:
1996     if (!Subtarget->isAAPCS_ABI())
1997       return CallingConv::ARM_APCS;
1998     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1999              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
2000              !isVarArg)
2001       return CallingConv::ARM_AAPCS_VFP;
2002     else
2003       return CallingConv::ARM_AAPCS;
2004   case CallingConv::Fast:
2005   case CallingConv::CXX_FAST_TLS:
2006     if (!Subtarget->isAAPCS_ABI()) {
2007       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2008         return CallingConv::Fast;
2009       return CallingConv::ARM_APCS;
2010     } else if (Subtarget->hasVFP2Base() &&
2011                !Subtarget->isThumb1Only() && !isVarArg)
2012       return CallingConv::ARM_AAPCS_VFP;
2013     else
2014       return CallingConv::ARM_AAPCS;
2015   }
2016 }
2017 
2018 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2019                                                  bool isVarArg) const {
2020   return CCAssignFnForNode(CC, false, isVarArg);
2021 }
2022 
2023 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2024                                                    bool isVarArg) const {
2025   return CCAssignFnForNode(CC, true, isVarArg);
2026 }
2027 
2028 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2029 /// CallingConvention.
2030 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2031                                                  bool Return,
2032                                                  bool isVarArg) const {
2033   switch (getEffectiveCallingConv(CC, isVarArg)) {
2034   default:
2035     report_fatal_error("Unsupported calling convention");
2036   case CallingConv::ARM_APCS:
2037     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2038   case CallingConv::ARM_AAPCS:
2039     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2040   case CallingConv::ARM_AAPCS_VFP:
2041     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2042   case CallingConv::Fast:
2043     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2044   case CallingConv::GHC:
2045     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2046   case CallingConv::PreserveMost:
2047     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2048   case CallingConv::CFGuard_Check:
2049     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2050   }
2051 }
2052 
2053 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2054                                      MVT LocVT, MVT ValVT, SDValue Val) const {
2055   Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2056                     Val);
2057   if (Subtarget->hasFullFP16()) {
2058     Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2059   } else {
2060     Val = DAG.getNode(ISD::TRUNCATE, dl,
2061                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2062     Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2063   }
2064   return Val;
2065 }
2066 
2067 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2068                                        MVT LocVT, MVT ValVT,
2069                                        SDValue Val) const {
2070   if (Subtarget->hasFullFP16()) {
2071     Val = DAG.getNode(ARMISD::VMOVrh, dl,
2072                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2073   } else {
2074     Val = DAG.getNode(ISD::BITCAST, dl,
2075                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2076     Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2077                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2078   }
2079   return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2080 }
2081 
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2084 SDValue ARMTargetLowering::LowerCallResult(
2085     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2086     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2087     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2088     SDValue ThisVal) const {
2089   // Assign locations to each value returned by this call.
2090   SmallVector<CCValAssign, 16> RVLocs;
2091   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2092                  *DAG.getContext());
2093   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2094 
2095   // Copy all of the result registers out of their specified physreg.
2096   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2097     CCValAssign VA = RVLocs[i];
2098 
2099     // Pass 'this' value directly from the argument to return value, to avoid
2100     // reg unit interference
2101     if (i == 0 && isThisReturn) {
2102       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2103              "unexpected return calling convention register assignment");
2104       InVals.push_back(ThisVal);
2105       continue;
2106     }
2107 
2108     SDValue Val;
2109     if (VA.needsCustom() &&
2110         (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2111       // Handle f64 or half of a v2f64.
2112       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2113                                       InFlag);
2114       Chain = Lo.getValue(1);
2115       InFlag = Lo.getValue(2);
2116       VA = RVLocs[++i]; // skip ahead to next loc
2117       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2118                                       InFlag);
2119       Chain = Hi.getValue(1);
2120       InFlag = Hi.getValue(2);
2121       if (!Subtarget->isLittle())
2122         std::swap (Lo, Hi);
2123       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2124 
2125       if (VA.getLocVT() == MVT::v2f64) {
2126         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2127         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2128                           DAG.getConstant(0, dl, MVT::i32));
2129 
2130         VA = RVLocs[++i]; // skip ahead to next loc
2131         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2132         Chain = Lo.getValue(1);
2133         InFlag = Lo.getValue(2);
2134         VA = RVLocs[++i]; // skip ahead to next loc
2135         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2136         Chain = Hi.getValue(1);
2137         InFlag = Hi.getValue(2);
2138         if (!Subtarget->isLittle())
2139           std::swap (Lo, Hi);
2140         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2141         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2142                           DAG.getConstant(1, dl, MVT::i32));
2143       }
2144     } else {
2145       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2146                                InFlag);
2147       Chain = Val.getValue(1);
2148       InFlag = Val.getValue(2);
2149     }
2150 
2151     switch (VA.getLocInfo()) {
2152     default: llvm_unreachable("Unknown loc info!");
2153     case CCValAssign::Full: break;
2154     case CCValAssign::BCvt:
2155       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2156       break;
2157     }
2158 
2159     // f16 arguments have their size extended to 4 bytes and passed as if they
2160     // had been copied to the LSBs of a 32-bit register.
2161     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2162     if (VA.needsCustom() &&
2163         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2164       Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2165 
2166     InVals.push_back(Val);
2167   }
2168 
2169   return Chain;
2170 }
2171 
2172 /// LowerMemOpCallTo - Store the argument to the stack.
2173 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2174                                             SDValue Arg, const SDLoc &dl,
2175                                             SelectionDAG &DAG,
2176                                             const CCValAssign &VA,
2177                                             ISD::ArgFlagsTy Flags) const {
2178   unsigned LocMemOffset = VA.getLocMemOffset();
2179   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2180   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2181                        StackPtr, PtrOff);
2182   return DAG.getStore(
2183       Chain, dl, Arg, PtrOff,
2184       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2185 }
2186 
2187 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2188                                          SDValue Chain, SDValue &Arg,
2189                                          RegsToPassVector &RegsToPass,
2190                                          CCValAssign &VA, CCValAssign &NextVA,
2191                                          SDValue &StackPtr,
2192                                          SmallVectorImpl<SDValue> &MemOpChains,
2193                                          ISD::ArgFlagsTy Flags) const {
2194   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2195                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2196   unsigned id = Subtarget->isLittle() ? 0 : 1;
2197   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2198 
2199   if (NextVA.isRegLoc())
2200     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2201   else {
2202     assert(NextVA.isMemLoc());
2203     if (!StackPtr.getNode())
2204       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2205                                     getPointerTy(DAG.getDataLayout()));
2206 
2207     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2208                                            dl, DAG, NextVA,
2209                                            Flags));
2210   }
2211 }
2212 
2213 /// LowerCall - Lowering a call into a callseq_start <-
2214 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2215 /// nodes.
2216 SDValue
2217 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2218                              SmallVectorImpl<SDValue> &InVals) const {
2219   SelectionDAG &DAG                     = CLI.DAG;
2220   SDLoc &dl                             = CLI.DL;
2221   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2222   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2223   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2224   SDValue Chain                         = CLI.Chain;
2225   SDValue Callee                        = CLI.Callee;
2226   bool &isTailCall                      = CLI.IsTailCall;
2227   CallingConv::ID CallConv              = CLI.CallConv;
2228   bool doesNotRet                       = CLI.DoesNotReturn;
2229   bool isVarArg                         = CLI.IsVarArg;
2230 
2231   MachineFunction &MF = DAG.getMachineFunction();
2232   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2233   MachineFunction::CallSiteInfo CSInfo;
2234   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2235   bool isThisReturn = false;
2236   bool isCmseNSCall   = false;
2237   bool PreferIndirect = false;
2238 
2239   // Determine whether this is a non-secure function call.
2240   if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call"))
2241     isCmseNSCall = true;
2242 
2243   // Disable tail calls if they're not supported.
2244   if (!Subtarget->supportsTailCall())
2245     isTailCall = false;
2246 
2247   // For both the non-secure calls and the returns from a CMSE entry function,
2248   // the function needs to do some extra work afte r the call, or before the
2249   // return, respectively, thus it cannot end with atail call
2250   if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2251     isTailCall = false;
2252 
2253   if (isa<GlobalAddressSDNode>(Callee)) {
2254     // If we're optimizing for minimum size and the function is called three or
2255     // more times in this block, we can improve codesize by calling indirectly
2256     // as BLXr has a 16-bit encoding.
2257     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2258     if (CLI.CB) {
2259       auto *BB = CLI.CB->getParent();
2260       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2261                        count_if(GV->users(), [&BB](const User *U) {
2262                          return isa<Instruction>(U) &&
2263                                 cast<Instruction>(U)->getParent() == BB;
2264                        }) > 2;
2265     }
2266   }
2267   if (isTailCall) {
2268     // Check if it's really possible to do a tail call.
2269     isTailCall = IsEligibleForTailCallOptimization(
2270         Callee, CallConv, isVarArg, isStructRet,
2271         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2272         PreferIndirect);
2273     if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2274       report_fatal_error("failed to perform tail call elimination on a call "
2275                          "site marked musttail");
2276     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2277     // detected sibcalls.
2278     if (isTailCall)
2279       ++NumTailCalls;
2280   }
2281 
2282   // Analyze operands of the call, assigning locations to each operand.
2283   SmallVector<CCValAssign, 16> ArgLocs;
2284   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2285                  *DAG.getContext());
2286   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2287 
2288   // Get a count of how many bytes are to be pushed on the stack.
2289   unsigned NumBytes = CCInfo.getNextStackOffset();
2290 
2291   if (isTailCall) {
2292     // For tail calls, memory operands are available in our caller's stack.
2293     NumBytes = 0;
2294   } else {
2295     // Adjust the stack pointer for the new arguments...
2296     // These operations are automatically eliminated by the prolog/epilog pass
2297     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2298   }
2299 
2300   SDValue StackPtr =
2301       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2302 
2303   RegsToPassVector RegsToPass;
2304   SmallVector<SDValue, 8> MemOpChains;
2305 
2306   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2307   // of tail call optimization, arguments are handled later.
2308   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2309        i != e;
2310        ++i, ++realArgIdx) {
2311     CCValAssign &VA = ArgLocs[i];
2312     SDValue Arg = OutVals[realArgIdx];
2313     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2314     bool isByVal = Flags.isByVal();
2315 
2316     // Promote the value if needed.
2317     switch (VA.getLocInfo()) {
2318     default: llvm_unreachable("Unknown loc info!");
2319     case CCValAssign::Full: break;
2320     case CCValAssign::SExt:
2321       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2322       break;
2323     case CCValAssign::ZExt:
2324       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2325       break;
2326     case CCValAssign::AExt:
2327       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2328       break;
2329     case CCValAssign::BCvt:
2330       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2331       break;
2332     }
2333 
2334     // f16 arguments have their size extended to 4 bytes and passed as if they
2335     // had been copied to the LSBs of a 32-bit register.
2336     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2337     if (VA.needsCustom() &&
2338         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2339       Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2340     } else {
2341       // f16 arguments could have been extended prior to argument lowering.
2342       // Mask them arguments if this is a CMSE nonsecure call.
2343       auto ArgVT = Outs[realArgIdx].ArgVT;
2344       if (isCmseNSCall && (ArgVT == MVT::f16)) {
2345         auto LocBits = VA.getLocVT().getSizeInBits();
2346         auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2347         SDValue Mask =
2348             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2349         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2350         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2351         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2352       }
2353     }
2354 
2355     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2356     if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2357       SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2358                                 DAG.getConstant(0, dl, MVT::i32));
2359       SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2360                                 DAG.getConstant(1, dl, MVT::i32));
2361 
2362       PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2363                        StackPtr, MemOpChains, Flags);
2364 
2365       VA = ArgLocs[++i]; // skip ahead to next loc
2366       if (VA.isRegLoc()) {
2367         PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2368                          StackPtr, MemOpChains, Flags);
2369       } else {
2370         assert(VA.isMemLoc());
2371 
2372         MemOpChains.push_back(
2373             LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags));
2374       }
2375     } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2376       PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2377                        StackPtr, MemOpChains, Flags);
2378     } else if (VA.isRegLoc()) {
2379       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2380           Outs[0].VT == MVT::i32) {
2381         assert(VA.getLocVT() == MVT::i32 &&
2382                "unexpected calling convention register assignment");
2383         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2384                "unexpected use of 'returned'");
2385         isThisReturn = true;
2386       }
2387       const TargetOptions &Options = DAG.getTarget().Options;
2388       if (Options.EmitCallSiteInfo)
2389         CSInfo.emplace_back(VA.getLocReg(), i);
2390       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2391     } else if (isByVal) {
2392       assert(VA.isMemLoc());
2393       unsigned offset = 0;
2394 
2395       // True if this byval aggregate will be split between registers
2396       // and memory.
2397       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2398       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2399 
2400       if (CurByValIdx < ByValArgsCount) {
2401 
2402         unsigned RegBegin, RegEnd;
2403         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2404 
2405         EVT PtrVT =
2406             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2407         unsigned int i, j;
2408         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2409           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2410           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2411           SDValue Load =
2412               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2413                           DAG.InferPtrAlign(AddArg));
2414           MemOpChains.push_back(Load.getValue(1));
2415           RegsToPass.push_back(std::make_pair(j, Load));
2416         }
2417 
2418         // If parameter size outsides register area, "offset" value
2419         // helps us to calculate stack slot for remained part properly.
2420         offset = RegEnd - RegBegin;
2421 
2422         CCInfo.nextInRegsParam();
2423       }
2424 
2425       if (Flags.getByValSize() > 4*offset) {
2426         auto PtrVT = getPointerTy(DAG.getDataLayout());
2427         unsigned LocMemOffset = VA.getLocMemOffset();
2428         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2429         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2430         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2431         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2432         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2433                                            MVT::i32);
2434         SDValue AlignNode =
2435             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2436 
2437         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2438         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2439         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2440                                           Ops));
2441       }
2442     } else if (!isTailCall) {
2443       assert(VA.isMemLoc());
2444 
2445       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2446                                              dl, DAG, VA, Flags));
2447     }
2448   }
2449 
2450   if (!MemOpChains.empty())
2451     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2452 
2453   // Build a sequence of copy-to-reg nodes chained together with token chain
2454   // and flag operands which copy the outgoing args into the appropriate regs.
2455   SDValue InFlag;
2456   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2457     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2458                              RegsToPass[i].second, InFlag);
2459     InFlag = Chain.getValue(1);
2460   }
2461 
2462   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2463   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2464   // node so that legalize doesn't hack it.
2465   bool isDirect = false;
2466 
2467   const TargetMachine &TM = getTargetMachine();
2468   const Module *Mod = MF.getFunction().getParent();
2469   const GlobalValue *GV = nullptr;
2470   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2471     GV = G->getGlobal();
2472   bool isStub =
2473       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2474 
2475   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2476   bool isLocalARMFunc = false;
2477   auto PtrVt = getPointerTy(DAG.getDataLayout());
2478 
2479   if (Subtarget->genLongCalls()) {
2480     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2481            "long-calls codegen is not position independent!");
2482     // Handle a global address or an external symbol. If it's not one of
2483     // those, the target's already in a register, so we don't need to do
2484     // anything extra.
2485     if (isa<GlobalAddressSDNode>(Callee)) {
2486       // Create a constant pool entry for the callee address
2487       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2488       ARMConstantPoolValue *CPV =
2489         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2490 
2491       // Get the address of the callee into a register
2492       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2493       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2494       Callee = DAG.getLoad(
2495           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2496           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2497     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2498       const char *Sym = S->getSymbol();
2499 
2500       // Create a constant pool entry for the callee address
2501       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2502       ARMConstantPoolValue *CPV =
2503         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2504                                       ARMPCLabelIndex, 0);
2505       // Get the address of the callee into a register
2506       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2507       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2508       Callee = DAG.getLoad(
2509           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2510           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2511     }
2512   } else if (isa<GlobalAddressSDNode>(Callee)) {
2513     if (!PreferIndirect) {
2514       isDirect = true;
2515       bool isDef = GV->isStrongDefinitionForLinker();
2516 
2517       // ARM call to a local ARM function is predicable.
2518       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2519       // tBX takes a register source operand.
2520       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2521         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2522         Callee = DAG.getNode(
2523             ARMISD::WrapperPIC, dl, PtrVt,
2524             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2525         Callee = DAG.getLoad(
2526             PtrVt, dl, DAG.getEntryNode(), Callee,
2527             MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2528             MachineMemOperand::MODereferenceable |
2529                 MachineMemOperand::MOInvariant);
2530       } else if (Subtarget->isTargetCOFF()) {
2531         assert(Subtarget->isTargetWindows() &&
2532                "Windows is the only supported COFF target");
2533         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2534         if (GV->hasDLLImportStorageClass())
2535           TargetFlags = ARMII::MO_DLLIMPORT;
2536         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2537           TargetFlags = ARMII::MO_COFFSTUB;
2538         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2539                                             TargetFlags);
2540         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2541           Callee =
2542               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2543                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2544                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2545       } else {
2546         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2547       }
2548     }
2549   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2550     isDirect = true;
2551     // tBX takes a register source operand.
2552     const char *Sym = S->getSymbol();
2553     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2554       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2555       ARMConstantPoolValue *CPV =
2556         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2557                                       ARMPCLabelIndex, 4);
2558       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2559       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2560       Callee = DAG.getLoad(
2561           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2562           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2563       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2564       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2565     } else {
2566       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2567     }
2568   }
2569 
2570   if (isCmseNSCall) {
2571     assert(!isARMFunc && !isDirect &&
2572            "Cannot handle call to ARM function or direct call");
2573     if (NumBytes > 0) {
2574       DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2575                                      "call to non-secure function would "
2576                                      "require passing arguments on stack",
2577                                      dl.getDebugLoc());
2578       DAG.getContext()->diagnose(Diag);
2579     }
2580     if (isStructRet) {
2581       DiagnosticInfoUnsupported Diag(
2582           DAG.getMachineFunction().getFunction(),
2583           "call to non-secure function would return value through pointer",
2584           dl.getDebugLoc());
2585       DAG.getContext()->diagnose(Diag);
2586     }
2587   }
2588 
2589   // FIXME: handle tail calls differently.
2590   unsigned CallOpc;
2591   if (Subtarget->isThumb()) {
2592     if (isCmseNSCall)
2593       CallOpc = ARMISD::tSECALL;
2594     else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2595       CallOpc = ARMISD::CALL_NOLINK;
2596     else
2597       CallOpc = ARMISD::CALL;
2598   } else {
2599     if (!isDirect && !Subtarget->hasV5TOps())
2600       CallOpc = ARMISD::CALL_NOLINK;
2601     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2602              // Emit regular call when code size is the priority
2603              !Subtarget->hasMinSize())
2604       // "mov lr, pc; b _foo" to avoid confusing the RSP
2605       CallOpc = ARMISD::CALL_NOLINK;
2606     else
2607       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2608   }
2609 
2610   std::vector<SDValue> Ops;
2611   Ops.push_back(Chain);
2612   Ops.push_back(Callee);
2613 
2614   // Add argument registers to the end of the list so that they are known live
2615   // into the call.
2616   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2617     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2618                                   RegsToPass[i].second.getValueType()));
2619 
2620   // Add a register mask operand representing the call-preserved registers.
2621   if (!isTailCall) {
2622     const uint32_t *Mask;
2623     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2624     if (isThisReturn) {
2625       // For 'this' returns, use the R0-preserving mask if applicable
2626       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2627       if (!Mask) {
2628         // Set isThisReturn to false if the calling convention is not one that
2629         // allows 'returned' to be modeled in this way, so LowerCallResult does
2630         // not try to pass 'this' straight through
2631         isThisReturn = false;
2632         Mask = ARI->getCallPreservedMask(MF, CallConv);
2633       }
2634     } else
2635       Mask = ARI->getCallPreservedMask(MF, CallConv);
2636 
2637     assert(Mask && "Missing call preserved mask for calling convention");
2638     Ops.push_back(DAG.getRegisterMask(Mask));
2639   }
2640 
2641   if (InFlag.getNode())
2642     Ops.push_back(InFlag);
2643 
2644   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2645   if (isTailCall) {
2646     MF.getFrameInfo().setHasTailCall();
2647     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2648     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2649     return Ret;
2650   }
2651 
2652   // Returns a chain and a flag for retval copy to use.
2653   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2654   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2655   InFlag = Chain.getValue(1);
2656   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2657 
2658   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2659                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2660   if (!Ins.empty())
2661     InFlag = Chain.getValue(1);
2662 
2663   // Handle result values, copying them out of physregs into vregs that we
2664   // return.
2665   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2666                          InVals, isThisReturn,
2667                          isThisReturn ? OutVals[0] : SDValue());
2668 }
2669 
2670 /// HandleByVal - Every parameter *after* a byval parameter is passed
2671 /// on the stack.  Remember the next parameter register to allocate,
2672 /// and then confiscate the rest of the parameter registers to insure
2673 /// this.
2674 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2675                                     Align Alignment) const {
2676   // Byval (as with any stack) slots are always at least 4 byte aligned.
2677   Alignment = std::max(Alignment, Align(4));
2678 
2679   unsigned Reg = State->AllocateReg(GPRArgRegs);
2680   if (!Reg)
2681     return;
2682 
2683   unsigned AlignInRegs = Alignment.value() / 4;
2684   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2685   for (unsigned i = 0; i < Waste; ++i)
2686     Reg = State->AllocateReg(GPRArgRegs);
2687 
2688   if (!Reg)
2689     return;
2690 
2691   unsigned Excess = 4 * (ARM::R4 - Reg);
2692 
2693   // Special case when NSAA != SP and parameter size greater than size of
2694   // all remained GPR regs. In that case we can't split parameter, we must
2695   // send it to stack. We also must set NCRN to R4, so waste all
2696   // remained registers.
2697   const unsigned NSAAOffset = State->getNextStackOffset();
2698   if (NSAAOffset != 0 && Size > Excess) {
2699     while (State->AllocateReg(GPRArgRegs))
2700       ;
2701     return;
2702   }
2703 
2704   // First register for byval parameter is the first register that wasn't
2705   // allocated before this method call, so it would be "reg".
2706   // If parameter is small enough to be saved in range [reg, r4), then
2707   // the end (first after last) register would be reg + param-size-in-regs,
2708   // else parameter would be splitted between registers and stack,
2709   // end register would be r4 in this case.
2710   unsigned ByValRegBegin = Reg;
2711   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2712   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2713   // Note, first register is allocated in the beginning of function already,
2714   // allocate remained amount of registers we need.
2715   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2716     State->AllocateReg(GPRArgRegs);
2717   // A byval parameter that is split between registers and memory needs its
2718   // size truncated here.
2719   // In the case where the entire structure fits in registers, we set the
2720   // size in memory to zero.
2721   Size = std::max<int>(Size - Excess, 0);
2722 }
2723 
2724 /// MatchingStackOffset - Return true if the given stack call argument is
2725 /// already available in the same position (relatively) of the caller's
2726 /// incoming argument stack.
2727 static
2728 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2729                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2730                          const TargetInstrInfo *TII) {
2731   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2732   int FI = std::numeric_limits<int>::max();
2733   if (Arg.getOpcode() == ISD::CopyFromReg) {
2734     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2735     if (!Register::isVirtualRegister(VR))
2736       return false;
2737     MachineInstr *Def = MRI->getVRegDef(VR);
2738     if (!Def)
2739       return false;
2740     if (!Flags.isByVal()) {
2741       if (!TII->isLoadFromStackSlot(*Def, FI))
2742         return false;
2743     } else {
2744       return false;
2745     }
2746   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2747     if (Flags.isByVal())
2748       // ByVal argument is passed in as a pointer but it's now being
2749       // dereferenced. e.g.
2750       // define @foo(%struct.X* %A) {
2751       //   tail call @bar(%struct.X* byval %A)
2752       // }
2753       return false;
2754     SDValue Ptr = Ld->getBasePtr();
2755     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2756     if (!FINode)
2757       return false;
2758     FI = FINode->getIndex();
2759   } else
2760     return false;
2761 
2762   assert(FI != std::numeric_limits<int>::max());
2763   if (!MFI.isFixedObjectIndex(FI))
2764     return false;
2765   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2766 }
2767 
2768 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2769 /// for tail call optimization. Targets which want to do tail call
2770 /// optimization should implement this function.
2771 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2772     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2773     bool isCalleeStructRet, bool isCallerStructRet,
2774     const SmallVectorImpl<ISD::OutputArg> &Outs,
2775     const SmallVectorImpl<SDValue> &OutVals,
2776     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2777     const bool isIndirect) const {
2778   MachineFunction &MF = DAG.getMachineFunction();
2779   const Function &CallerF = MF.getFunction();
2780   CallingConv::ID CallerCC = CallerF.getCallingConv();
2781 
2782   assert(Subtarget->supportsTailCall());
2783 
2784   // Indirect tail calls cannot be optimized for Thumb1 if the args
2785   // to the call take up r0-r3. The reason is that there are no legal registers
2786   // left to hold the pointer to the function to be called.
2787   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2788       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2789     return false;
2790 
2791   // Look for obvious safe cases to perform tail call optimization that do not
2792   // require ABI changes. This is what gcc calls sibcall.
2793 
2794   // Exception-handling functions need a special set of instructions to indicate
2795   // a return to the hardware. Tail-calling another function would probably
2796   // break this.
2797   if (CallerF.hasFnAttribute("interrupt"))
2798     return false;
2799 
2800   // Also avoid sibcall optimization if either caller or callee uses struct
2801   // return semantics.
2802   if (isCalleeStructRet || isCallerStructRet)
2803     return false;
2804 
2805   // Externally-defined functions with weak linkage should not be
2806   // tail-called on ARM when the OS does not support dynamic
2807   // pre-emption of symbols, as the AAELF spec requires normal calls
2808   // to undefined weak functions to be replaced with a NOP or jump to the
2809   // next instruction. The behaviour of branch instructions in this
2810   // situation (as used for tail calls) is implementation-defined, so we
2811   // cannot rely on the linker replacing the tail call with a return.
2812   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2813     const GlobalValue *GV = G->getGlobal();
2814     const Triple &TT = getTargetMachine().getTargetTriple();
2815     if (GV->hasExternalWeakLinkage() &&
2816         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2817       return false;
2818   }
2819 
2820   // Check that the call results are passed in the same way.
2821   LLVMContext &C = *DAG.getContext();
2822   if (!CCState::resultsCompatible(
2823           getEffectiveCallingConv(CalleeCC, isVarArg),
2824           getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2825           CCAssignFnForReturn(CalleeCC, isVarArg),
2826           CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2827     return false;
2828   // The callee has to preserve all registers the caller needs to preserve.
2829   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2830   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2831   if (CalleeCC != CallerCC) {
2832     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2833     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2834       return false;
2835   }
2836 
2837   // If Caller's vararg or byval argument has been split between registers and
2838   // stack, do not perform tail call, since part of the argument is in caller's
2839   // local frame.
2840   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2841   if (AFI_Caller->getArgRegsSaveSize())
2842     return false;
2843 
2844   // If the callee takes no arguments then go on to check the results of the
2845   // call.
2846   if (!Outs.empty()) {
2847     // Check if stack adjustment is needed. For now, do not do this if any
2848     // argument is passed on the stack.
2849     SmallVector<CCValAssign, 16> ArgLocs;
2850     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2851     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2852     if (CCInfo.getNextStackOffset()) {
2853       // Check if the arguments are already laid out in the right way as
2854       // the caller's fixed stack objects.
2855       MachineFrameInfo &MFI = MF.getFrameInfo();
2856       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2857       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2858       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2859            i != e;
2860            ++i, ++realArgIdx) {
2861         CCValAssign &VA = ArgLocs[i];
2862         EVT RegVT = VA.getLocVT();
2863         SDValue Arg = OutVals[realArgIdx];
2864         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2865         if (VA.getLocInfo() == CCValAssign::Indirect)
2866           return false;
2867         if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
2868           // f64 and vector types are split into multiple registers or
2869           // register/stack-slot combinations.  The types will not match
2870           // the registers; give up on memory f64 refs until we figure
2871           // out what to do about this.
2872           if (!VA.isRegLoc())
2873             return false;
2874           if (!ArgLocs[++i].isRegLoc())
2875             return false;
2876           if (RegVT == MVT::v2f64) {
2877             if (!ArgLocs[++i].isRegLoc())
2878               return false;
2879             if (!ArgLocs[++i].isRegLoc())
2880               return false;
2881           }
2882         } else if (!VA.isRegLoc()) {
2883           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2884                                    MFI, MRI, TII))
2885             return false;
2886         }
2887       }
2888     }
2889 
2890     const MachineRegisterInfo &MRI = MF.getRegInfo();
2891     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2892       return false;
2893   }
2894 
2895   return true;
2896 }
2897 
2898 bool
2899 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2900                                   MachineFunction &MF, bool isVarArg,
2901                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2902                                   LLVMContext &Context) const {
2903   SmallVector<CCValAssign, 16> RVLocs;
2904   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2905   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2906 }
2907 
2908 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2909                                     const SDLoc &DL, SelectionDAG &DAG) {
2910   const MachineFunction &MF = DAG.getMachineFunction();
2911   const Function &F = MF.getFunction();
2912 
2913   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2914 
2915   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2916   // version of the "preferred return address". These offsets affect the return
2917   // instruction if this is a return from PL1 without hypervisor extensions.
2918   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2919   //    SWI:     0      "subs pc, lr, #0"
2920   //    ABORT:   +4     "subs pc, lr, #4"
2921   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2922   // UNDEF varies depending on where the exception came from ARM or Thumb
2923   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2924 
2925   int64_t LROffset;
2926   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2927       IntKind == "ABORT")
2928     LROffset = 4;
2929   else if (IntKind == "SWI" || IntKind == "UNDEF")
2930     LROffset = 0;
2931   else
2932     report_fatal_error("Unsupported interrupt attribute. If present, value "
2933                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2934 
2935   RetOps.insert(RetOps.begin() + 1,
2936                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2937 
2938   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2939 }
2940 
2941 SDValue
2942 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2943                                bool isVarArg,
2944                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2945                                const SmallVectorImpl<SDValue> &OutVals,
2946                                const SDLoc &dl, SelectionDAG &DAG) const {
2947   // CCValAssign - represent the assignment of the return value to a location.
2948   SmallVector<CCValAssign, 16> RVLocs;
2949 
2950   // CCState - Info about the registers and stack slots.
2951   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2952                  *DAG.getContext());
2953 
2954   // Analyze outgoing return values.
2955   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2956 
2957   SDValue Flag;
2958   SmallVector<SDValue, 4> RetOps;
2959   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2960   bool isLittleEndian = Subtarget->isLittle();
2961 
2962   MachineFunction &MF = DAG.getMachineFunction();
2963   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2964   AFI->setReturnRegsCount(RVLocs.size());
2965 
2966  // Report error if cmse entry function returns structure through first ptr arg.
2967   if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2968     // Note: using an empty SDLoc(), as the first line of the function is a
2969     // better place to report than the last line.
2970     DiagnosticInfoUnsupported Diag(
2971         DAG.getMachineFunction().getFunction(),
2972         "secure entry function would return value through pointer",
2973         SDLoc().getDebugLoc());
2974     DAG.getContext()->diagnose(Diag);
2975   }
2976 
2977   // Copy the result values into the output registers.
2978   for (unsigned i = 0, realRVLocIdx = 0;
2979        i != RVLocs.size();
2980        ++i, ++realRVLocIdx) {
2981     CCValAssign &VA = RVLocs[i];
2982     assert(VA.isRegLoc() && "Can only return in registers!");
2983 
2984     SDValue Arg = OutVals[realRVLocIdx];
2985     bool ReturnF16 = false;
2986 
2987     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2988       // Half-precision return values can be returned like this:
2989       //
2990       // t11 f16 = fadd ...
2991       // t12: i16 = bitcast t11
2992       //   t13: i32 = zero_extend t12
2993       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2994       //
2995       // to avoid code generation for bitcasts, we simply set Arg to the node
2996       // that produces the f16 value, t11 in this case.
2997       //
2998       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2999         SDValue ZE = Arg.getOperand(0);
3000         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
3001           SDValue BC = ZE.getOperand(0);
3002           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
3003             Arg = BC.getOperand(0);
3004             ReturnF16 = true;
3005           }
3006         }
3007       }
3008     }
3009 
3010     switch (VA.getLocInfo()) {
3011     default: llvm_unreachable("Unknown loc info!");
3012     case CCValAssign::Full: break;
3013     case CCValAssign::BCvt:
3014       if (!ReturnF16)
3015         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3016       break;
3017     }
3018 
3019     // Mask f16 arguments if this is a CMSE nonsecure entry.
3020     auto RetVT = Outs[realRVLocIdx].ArgVT;
3021     if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3022       if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3023         Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3024       } else {
3025         auto LocBits = VA.getLocVT().getSizeInBits();
3026         auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3027         SDValue Mask =
3028             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3029         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3030         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3031         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3032       }
3033     }
3034 
3035     if (VA.needsCustom() &&
3036         (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3037       if (VA.getLocVT() == MVT::v2f64) {
3038         // Extract the first half and return it in two registers.
3039         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3040                                    DAG.getConstant(0, dl, MVT::i32));
3041         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3042                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
3043 
3044         Chain =
3045             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3046                              HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3047         Flag = Chain.getValue(1);
3048         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3049         VA = RVLocs[++i]; // skip ahead to next loc
3050         Chain =
3051             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3052                              HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3053         Flag = Chain.getValue(1);
3054         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3055         VA = RVLocs[++i]; // skip ahead to next loc
3056 
3057         // Extract the 2nd half and fall through to handle it as an f64 value.
3058         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3059                           DAG.getConstant(1, dl, MVT::i32));
3060       }
3061       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
3062       // available.
3063       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3064                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
3065       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3066                                fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3067       Flag = Chain.getValue(1);
3068       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3069       VA = RVLocs[++i]; // skip ahead to next loc
3070       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3071                                fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3072     } else
3073       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3074 
3075     // Guarantee that all emitted copies are
3076     // stuck together, avoiding something bad.
3077     Flag = Chain.getValue(1);
3078     RetOps.push_back(DAG.getRegister(
3079         VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3080   }
3081   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3082   const MCPhysReg *I =
3083       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3084   if (I) {
3085     for (; *I; ++I) {
3086       if (ARM::GPRRegClass.contains(*I))
3087         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3088       else if (ARM::DPRRegClass.contains(*I))
3089         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3090       else
3091         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3092     }
3093   }
3094 
3095   // Update chain and glue.
3096   RetOps[0] = Chain;
3097   if (Flag.getNode())
3098     RetOps.push_back(Flag);
3099 
3100   // CPUs which aren't M-class use a special sequence to return from
3101   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3102   // though we use "subs pc, lr, #N").
3103   //
3104   // M-class CPUs actually use a normal return sequence with a special
3105   // (hardware-provided) value in LR, so the normal code path works.
3106   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3107       !Subtarget->isMClass()) {
3108     if (Subtarget->isThumb1Only())
3109       report_fatal_error("interrupt attribute is not supported in Thumb1");
3110     return LowerInterruptReturn(RetOps, dl, DAG);
3111   }
3112 
3113   ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3114                                                             ARMISD::RET_FLAG;
3115   return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3116 }
3117 
3118 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3119   if (N->getNumValues() != 1)
3120     return false;
3121   if (!N->hasNUsesOfValue(1, 0))
3122     return false;
3123 
3124   SDValue TCChain = Chain;
3125   SDNode *Copy = *N->use_begin();
3126   if (Copy->getOpcode() == ISD::CopyToReg) {
3127     // If the copy has a glue operand, we conservatively assume it isn't safe to
3128     // perform a tail call.
3129     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3130       return false;
3131     TCChain = Copy->getOperand(0);
3132   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3133     SDNode *VMov = Copy;
3134     // f64 returned in a pair of GPRs.
3135     SmallPtrSet<SDNode*, 2> Copies;
3136     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3137          UI != UE; ++UI) {
3138       if (UI->getOpcode() != ISD::CopyToReg)
3139         return false;
3140       Copies.insert(*UI);
3141     }
3142     if (Copies.size() > 2)
3143       return false;
3144 
3145     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3146          UI != UE; ++UI) {
3147       SDValue UseChain = UI->getOperand(0);
3148       if (Copies.count(UseChain.getNode()))
3149         // Second CopyToReg
3150         Copy = *UI;
3151       else {
3152         // We are at the top of this chain.
3153         // If the copy has a glue operand, we conservatively assume it
3154         // isn't safe to perform a tail call.
3155         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3156           return false;
3157         // First CopyToReg
3158         TCChain = UseChain;
3159       }
3160     }
3161   } else if (Copy->getOpcode() == ISD::BITCAST) {
3162     // f32 returned in a single GPR.
3163     if (!Copy->hasOneUse())
3164       return false;
3165     Copy = *Copy->use_begin();
3166     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3167       return false;
3168     // If the copy has a glue operand, we conservatively assume it isn't safe to
3169     // perform a tail call.
3170     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3171       return false;
3172     TCChain = Copy->getOperand(0);
3173   } else {
3174     return false;
3175   }
3176 
3177   bool HasRet = false;
3178   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3179        UI != UE; ++UI) {
3180     if (UI->getOpcode() != ARMISD::RET_FLAG &&
3181         UI->getOpcode() != ARMISD::INTRET_FLAG)
3182       return false;
3183     HasRet = true;
3184   }
3185 
3186   if (!HasRet)
3187     return false;
3188 
3189   Chain = TCChain;
3190   return true;
3191 }
3192 
3193 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3194   if (!Subtarget->supportsTailCall())
3195     return false;
3196 
3197   if (!CI->isTailCall())
3198     return false;
3199 
3200   return true;
3201 }
3202 
3203 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3204 // and pass the lower and high parts through.
3205 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3206   SDLoc DL(Op);
3207   SDValue WriteValue = Op->getOperand(2);
3208 
3209   // This function is only supposed to be called for i64 type argument.
3210   assert(WriteValue.getValueType() == MVT::i64
3211           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3212 
3213   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3214                            DAG.getConstant(0, DL, MVT::i32));
3215   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3216                            DAG.getConstant(1, DL, MVT::i32));
3217   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3218   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3219 }
3220 
3221 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3222 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3223 // one of the above mentioned nodes. It has to be wrapped because otherwise
3224 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3225 // be used to form addressing mode. These wrapped nodes will be selected
3226 // into MOVi.
3227 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3228                                              SelectionDAG &DAG) const {
3229   EVT PtrVT = Op.getValueType();
3230   // FIXME there is no actual debug info here
3231   SDLoc dl(Op);
3232   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3233   SDValue Res;
3234 
3235   // When generating execute-only code Constant Pools must be promoted to the
3236   // global data section. It's a bit ugly that we can't share them across basic
3237   // blocks, but this way we guarantee that execute-only behaves correct with
3238   // position-independent addressing modes.
3239   if (Subtarget->genExecuteOnly()) {
3240     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3241     auto T = const_cast<Type*>(CP->getType());
3242     auto C = const_cast<Constant*>(CP->getConstVal());
3243     auto M = const_cast<Module*>(DAG.getMachineFunction().
3244                                  getFunction().getParent());
3245     auto GV = new GlobalVariable(
3246                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3247                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3248                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3249                     Twine(AFI->createPICLabelUId())
3250                   );
3251     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3252                                             dl, PtrVT);
3253     return LowerGlobalAddress(GA, DAG);
3254   }
3255 
3256   if (CP->isMachineConstantPoolEntry())
3257     Res =
3258         DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3259   else
3260     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3261   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3262 }
3263 
3264 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3265   return MachineJumpTableInfo::EK_Inline;
3266 }
3267 
3268 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3269                                              SelectionDAG &DAG) const {
3270   MachineFunction &MF = DAG.getMachineFunction();
3271   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3272   unsigned ARMPCLabelIndex = 0;
3273   SDLoc DL(Op);
3274   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3275   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3276   SDValue CPAddr;
3277   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3278   if (!IsPositionIndependent) {
3279     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3280   } else {
3281     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3282     ARMPCLabelIndex = AFI->createPICLabelUId();
3283     ARMConstantPoolValue *CPV =
3284       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3285                                       ARMCP::CPBlockAddress, PCAdj);
3286     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3287   }
3288   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3289   SDValue Result = DAG.getLoad(
3290       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3291       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3292   if (!IsPositionIndependent)
3293     return Result;
3294   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3295   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3296 }
3297 
3298 /// Convert a TLS address reference into the correct sequence of loads
3299 /// and calls to compute the variable's address for Darwin, and return an
3300 /// SDValue containing the final node.
3301 
3302 /// Darwin only has one TLS scheme which must be capable of dealing with the
3303 /// fully general situation, in the worst case. This means:
3304 ///     + "extern __thread" declaration.
3305 ///     + Defined in a possibly unknown dynamic library.
3306 ///
3307 /// The general system is that each __thread variable has a [3 x i32] descriptor
3308 /// which contains information used by the runtime to calculate the address. The
3309 /// only part of this the compiler needs to know about is the first word, which
3310 /// contains a function pointer that must be called with the address of the
3311 /// entire descriptor in "r0".
3312 ///
3313 /// Since this descriptor may be in a different unit, in general access must
3314 /// proceed along the usual ARM rules. A common sequence to produce is:
3315 ///
3316 ///     movw rT1, :lower16:_var$non_lazy_ptr
3317 ///     movt rT1, :upper16:_var$non_lazy_ptr
3318 ///     ldr r0, [rT1]
3319 ///     ldr rT2, [r0]
3320 ///     blx rT2
3321 ///     [...address now in r0...]
3322 SDValue
3323 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3324                                                SelectionDAG &DAG) const {
3325   assert(Subtarget->isTargetDarwin() &&
3326          "This function expects a Darwin target");
3327   SDLoc DL(Op);
3328 
3329   // First step is to get the address of the actua global symbol. This is where
3330   // the TLS descriptor lives.
3331   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3332 
3333   // The first entry in the descriptor is a function pointer that we must call
3334   // to obtain the address of the variable.
3335   SDValue Chain = DAG.getEntryNode();
3336   SDValue FuncTLVGet = DAG.getLoad(
3337       MVT::i32, DL, Chain, DescAddr,
3338       MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3339       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3340           MachineMemOperand::MOInvariant);
3341   Chain = FuncTLVGet.getValue(1);
3342 
3343   MachineFunction &F = DAG.getMachineFunction();
3344   MachineFrameInfo &MFI = F.getFrameInfo();
3345   MFI.setAdjustsStack(true);
3346 
3347   // TLS calls preserve all registers except those that absolutely must be
3348   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3349   // silly).
3350   auto TRI =
3351       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3352   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3353   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3354 
3355   // Finally, we can make the call. This is just a degenerate version of a
3356   // normal AArch64 call node: r0 takes the address of the descriptor, and
3357   // returns the address of the variable in this thread.
3358   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3359   Chain =
3360       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3361                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3362                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3363   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3364 }
3365 
3366 SDValue
3367 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3368                                                 SelectionDAG &DAG) const {
3369   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3370 
3371   SDValue Chain = DAG.getEntryNode();
3372   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3373   SDLoc DL(Op);
3374 
3375   // Load the current TEB (thread environment block)
3376   SDValue Ops[] = {Chain,
3377                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3378                    DAG.getTargetConstant(15, DL, MVT::i32),
3379                    DAG.getTargetConstant(0, DL, MVT::i32),
3380                    DAG.getTargetConstant(13, DL, MVT::i32),
3381                    DAG.getTargetConstant(0, DL, MVT::i32),
3382                    DAG.getTargetConstant(2, DL, MVT::i32)};
3383   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3384                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3385 
3386   SDValue TEB = CurrentTEB.getValue(0);
3387   Chain = CurrentTEB.getValue(1);
3388 
3389   // Load the ThreadLocalStoragePointer from the TEB
3390   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3391   SDValue TLSArray =
3392       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3393   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3394 
3395   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3396   // offset into the TLSArray.
3397 
3398   // Load the TLS index from the C runtime
3399   SDValue TLSIndex =
3400       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3401   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3402   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3403 
3404   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3405                               DAG.getConstant(2, DL, MVT::i32));
3406   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3407                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3408                             MachinePointerInfo());
3409 
3410   // Get the offset of the start of the .tls section (section base)
3411   const auto *GA = cast<GlobalAddressSDNode>(Op);
3412   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3413   SDValue Offset = DAG.getLoad(
3414       PtrVT, DL, Chain,
3415       DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3416                   DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3417       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3418 
3419   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3420 }
3421 
3422 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3423 SDValue
3424 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3425                                                  SelectionDAG &DAG) const {
3426   SDLoc dl(GA);
3427   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3428   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3429   MachineFunction &MF = DAG.getMachineFunction();
3430   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3431   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3432   ARMConstantPoolValue *CPV =
3433     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3434                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3435   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3436   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3437   Argument = DAG.getLoad(
3438       PtrVT, dl, DAG.getEntryNode(), Argument,
3439       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3440   SDValue Chain = Argument.getValue(1);
3441 
3442   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3443   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3444 
3445   // call __tls_get_addr.
3446   ArgListTy Args;
3447   ArgListEntry Entry;
3448   Entry.Node = Argument;
3449   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3450   Args.push_back(Entry);
3451 
3452   // FIXME: is there useful debug info available here?
3453   TargetLowering::CallLoweringInfo CLI(DAG);
3454   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3455       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3456       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3457 
3458   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3459   return CallResult.first;
3460 }
3461 
3462 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3463 // "local exec" model.
3464 SDValue
3465 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3466                                         SelectionDAG &DAG,
3467                                         TLSModel::Model model) const {
3468   const GlobalValue *GV = GA->getGlobal();
3469   SDLoc dl(GA);
3470   SDValue Offset;
3471   SDValue Chain = DAG.getEntryNode();
3472   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3473   // Get the Thread Pointer
3474   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3475 
3476   if (model == TLSModel::InitialExec) {
3477     MachineFunction &MF = DAG.getMachineFunction();
3478     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3479     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3480     // Initial exec model.
3481     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3482     ARMConstantPoolValue *CPV =
3483       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3484                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3485                                       true);
3486     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3487     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3488     Offset = DAG.getLoad(
3489         PtrVT, dl, Chain, Offset,
3490         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3491     Chain = Offset.getValue(1);
3492 
3493     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3494     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3495 
3496     Offset = DAG.getLoad(
3497         PtrVT, dl, Chain, Offset,
3498         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3499   } else {
3500     // local exec model
3501     assert(model == TLSModel::LocalExec);
3502     ARMConstantPoolValue *CPV =
3503       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3504     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3505     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3506     Offset = DAG.getLoad(
3507         PtrVT, dl, Chain, Offset,
3508         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3509   }
3510 
3511   // The address of the thread local variable is the add of the thread
3512   // pointer with the offset of the variable.
3513   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3514 }
3515 
3516 SDValue
3517 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3518   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3519   if (DAG.getTarget().useEmulatedTLS())
3520     return LowerToTLSEmulatedModel(GA, DAG);
3521 
3522   if (Subtarget->isTargetDarwin())
3523     return LowerGlobalTLSAddressDarwin(Op, DAG);
3524 
3525   if (Subtarget->isTargetWindows())
3526     return LowerGlobalTLSAddressWindows(Op, DAG);
3527 
3528   // TODO: implement the "local dynamic" model
3529   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3530   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3531 
3532   switch (model) {
3533     case TLSModel::GeneralDynamic:
3534     case TLSModel::LocalDynamic:
3535       return LowerToTLSGeneralDynamicModel(GA, DAG);
3536     case TLSModel::InitialExec:
3537     case TLSModel::LocalExec:
3538       return LowerToTLSExecModels(GA, DAG, model);
3539   }
3540   llvm_unreachable("bogus TLS model");
3541 }
3542 
3543 /// Return true if all users of V are within function F, looking through
3544 /// ConstantExprs.
3545 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3546   SmallVector<const User*,4> Worklist;
3547   for (auto *U : V->users())
3548     Worklist.push_back(U);
3549   while (!Worklist.empty()) {
3550     auto *U = Worklist.pop_back_val();
3551     if (isa<ConstantExpr>(U)) {
3552       for (auto *UU : U->users())
3553         Worklist.push_back(UU);
3554       continue;
3555     }
3556 
3557     auto *I = dyn_cast<Instruction>(U);
3558     if (!I || I->getParent()->getParent() != F)
3559       return false;
3560   }
3561   return true;
3562 }
3563 
3564 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3565                                      const GlobalValue *GV, SelectionDAG &DAG,
3566                                      EVT PtrVT, const SDLoc &dl) {
3567   // If we're creating a pool entry for a constant global with unnamed address,
3568   // and the global is small enough, we can emit it inline into the constant pool
3569   // to save ourselves an indirection.
3570   //
3571   // This is a win if the constant is only used in one function (so it doesn't
3572   // need to be duplicated) or duplicating the constant wouldn't increase code
3573   // size (implying the constant is no larger than 4 bytes).
3574   const Function &F = DAG.getMachineFunction().getFunction();
3575 
3576   // We rely on this decision to inline being idemopotent and unrelated to the
3577   // use-site. We know that if we inline a variable at one use site, we'll
3578   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3579   // doesn't know about this optimization, so bail out if it's enabled else
3580   // we could decide to inline here (and thus never emit the GV) but require
3581   // the GV from fast-isel generated code.
3582   if (!EnableConstpoolPromotion ||
3583       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3584       return SDValue();
3585 
3586   auto *GVar = dyn_cast<GlobalVariable>(GV);
3587   if (!GVar || !GVar->hasInitializer() ||
3588       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3589       !GVar->hasLocalLinkage())
3590     return SDValue();
3591 
3592   // If we inline a value that contains relocations, we move the relocations
3593   // from .data to .text. This is not allowed in position-independent code.
3594   auto *Init = GVar->getInitializer();
3595   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3596       Init->needsRelocation())
3597     return SDValue();
3598 
3599   // The constant islands pass can only really deal with alignment requests
3600   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3601   // any type wanting greater alignment requirements than 4 bytes. We also
3602   // can only promote constants that are multiples of 4 bytes in size or
3603   // are paddable to a multiple of 4. Currently we only try and pad constants
3604   // that are strings for simplicity.
3605   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3606   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3607   Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3608   unsigned RequiredPadding = 4 - (Size % 4);
3609   bool PaddingPossible =
3610     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3611   if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3612       Size == 0)
3613     return SDValue();
3614 
3615   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3616   MachineFunction &MF = DAG.getMachineFunction();
3617   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3618 
3619   // We can't bloat the constant pool too much, else the ConstantIslands pass
3620   // may fail to converge. If we haven't promoted this global yet (it may have
3621   // multiple uses), and promoting it would increase the constant pool size (Sz
3622   // > 4), ensure we have space to do so up to MaxTotal.
3623   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3624     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3625         ConstpoolPromotionMaxTotal)
3626       return SDValue();
3627 
3628   // This is only valid if all users are in a single function; we can't clone
3629   // the constant in general. The LLVM IR unnamed_addr allows merging
3630   // constants, but not cloning them.
3631   //
3632   // We could potentially allow cloning if we could prove all uses of the
3633   // constant in the current function don't care about the address, like
3634   // printf format strings. But that isn't implemented for now.
3635   if (!allUsersAreInFunction(GVar, &F))
3636     return SDValue();
3637 
3638   // We're going to inline this global. Pad it out if needed.
3639   if (RequiredPadding != 4) {
3640     StringRef S = CDAInit->getAsString();
3641 
3642     SmallVector<uint8_t,16> V(S.size());
3643     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3644     while (RequiredPadding--)
3645       V.push_back(0);
3646     Init = ConstantDataArray::get(*DAG.getContext(), V);
3647   }
3648 
3649   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3650   SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3651   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3652     AFI->markGlobalAsPromotedToConstantPool(GVar);
3653     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3654                                       PaddedSize - 4);
3655   }
3656   ++NumConstpoolPromoted;
3657   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3658 }
3659 
3660 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3661   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3662     if (!(GV = GA->getBaseObject()))
3663       return false;
3664   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3665     return V->isConstant();
3666   return isa<Function>(GV);
3667 }
3668 
3669 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3670                                               SelectionDAG &DAG) const {
3671   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3672   default: llvm_unreachable("unknown object format");
3673   case Triple::COFF:
3674     return LowerGlobalAddressWindows(Op, DAG);
3675   case Triple::ELF:
3676     return LowerGlobalAddressELF(Op, DAG);
3677   case Triple::MachO:
3678     return LowerGlobalAddressDarwin(Op, DAG);
3679   }
3680 }
3681 
3682 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3683                                                  SelectionDAG &DAG) const {
3684   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3685   SDLoc dl(Op);
3686   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3687   const TargetMachine &TM = getTargetMachine();
3688   bool IsRO = isReadOnly(GV);
3689 
3690   // promoteToConstantPool only if not generating XO text section
3691   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3692     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3693       return V;
3694 
3695   if (isPositionIndependent()) {
3696     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3697     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3698                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3699     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3700     if (UseGOT_PREL)
3701       Result =
3702           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3703                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3704     return Result;
3705   } else if (Subtarget->isROPI() && IsRO) {
3706     // PC-relative.
3707     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3708     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3709     return Result;
3710   } else if (Subtarget->isRWPI() && !IsRO) {
3711     // SB-relative.
3712     SDValue RelAddr;
3713     if (Subtarget->useMovt()) {
3714       ++NumMovwMovt;
3715       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3716       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3717     } else { // use literal pool for address constant
3718       ARMConstantPoolValue *CPV =
3719         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3720       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3721       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3722       RelAddr = DAG.getLoad(
3723           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3724           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3725     }
3726     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3727     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3728     return Result;
3729   }
3730 
3731   // If we have T2 ops, we can materialize the address directly via movt/movw
3732   // pair. This is always cheaper.
3733   if (Subtarget->useMovt()) {
3734     ++NumMovwMovt;
3735     // FIXME: Once remat is capable of dealing with instructions with register
3736     // operands, expand this into two nodes.
3737     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3738                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3739   } else {
3740     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3741     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3742     return DAG.getLoad(
3743         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3744         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3745   }
3746 }
3747 
3748 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3749                                                     SelectionDAG &DAG) const {
3750   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3751          "ROPI/RWPI not currently supported for Darwin");
3752   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3753   SDLoc dl(Op);
3754   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3755 
3756   if (Subtarget->useMovt())
3757     ++NumMovwMovt;
3758 
3759   // FIXME: Once remat is capable of dealing with instructions with register
3760   // operands, expand this into multiple nodes
3761   unsigned Wrapper =
3762       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3763 
3764   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3765   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3766 
3767   if (Subtarget->isGVIndirectSymbol(GV))
3768     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3769                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3770   return Result;
3771 }
3772 
3773 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3774                                                      SelectionDAG &DAG) const {
3775   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3776   assert(Subtarget->useMovt() &&
3777          "Windows on ARM expects to use movw/movt");
3778   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3779          "ROPI/RWPI not currently supported for Windows");
3780 
3781   const TargetMachine &TM = getTargetMachine();
3782   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3783   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3784   if (GV->hasDLLImportStorageClass())
3785     TargetFlags = ARMII::MO_DLLIMPORT;
3786   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3787     TargetFlags = ARMII::MO_COFFSTUB;
3788   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3789   SDValue Result;
3790   SDLoc DL(Op);
3791 
3792   ++NumMovwMovt;
3793 
3794   // FIXME: Once remat is capable of dealing with instructions with register
3795   // operands, expand this into two nodes.
3796   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3797                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3798                                                   TargetFlags));
3799   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3800     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3801                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3802   return Result;
3803 }
3804 
3805 SDValue
3806 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3807   SDLoc dl(Op);
3808   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3809   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3810                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3811                      Op.getOperand(1), Val);
3812 }
3813 
3814 SDValue
3815 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3816   SDLoc dl(Op);
3817   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3818                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3819 }
3820 
3821 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3822                                                       SelectionDAG &DAG) const {
3823   SDLoc dl(Op);
3824   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3825                      Op.getOperand(0));
3826 }
3827 
3828 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3829     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3830   unsigned IntNo =
3831       cast<ConstantSDNode>(
3832           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3833           ->getZExtValue();
3834   switch (IntNo) {
3835     default:
3836       return SDValue();  // Don't custom lower most intrinsics.
3837     case Intrinsic::arm_gnu_eabi_mcount: {
3838       MachineFunction &MF = DAG.getMachineFunction();
3839       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3840       SDLoc dl(Op);
3841       SDValue Chain = Op.getOperand(0);
3842       // call "\01__gnu_mcount_nc"
3843       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3844       const uint32_t *Mask =
3845           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3846       assert(Mask && "Missing call preserved mask for calling convention");
3847       // Mark LR an implicit live-in.
3848       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3849       SDValue ReturnAddress =
3850           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3851       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3852       SDValue Callee =
3853           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3854       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3855       if (Subtarget->isThumb())
3856         return SDValue(
3857             DAG.getMachineNode(
3858                 ARM::tBL_PUSHLR, dl, ResultTys,
3859                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3860                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3861             0);
3862       return SDValue(
3863           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3864                              {ReturnAddress, Callee, RegisterMask, Chain}),
3865           0);
3866     }
3867   }
3868 }
3869 
3870 SDValue
3871 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3872                                           const ARMSubtarget *Subtarget) const {
3873   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3874   SDLoc dl(Op);
3875   switch (IntNo) {
3876   default: return SDValue();    // Don't custom lower most intrinsics.
3877   case Intrinsic::thread_pointer: {
3878     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3879     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3880   }
3881   case Intrinsic::arm_cls: {
3882     const SDValue &Operand = Op.getOperand(1);
3883     const EVT VTy = Op.getValueType();
3884     SDValue SRA =
3885         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3886     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3887     SDValue SHL =
3888         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3889     SDValue OR =
3890         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3891     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3892     return Result;
3893   }
3894   case Intrinsic::arm_cls64: {
3895     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3896     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3897     const SDValue &Operand = Op.getOperand(1);
3898     const EVT VTy = Op.getValueType();
3899 
3900     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3901                              DAG.getConstant(1, dl, VTy));
3902     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3903                              DAG.getConstant(0, dl, VTy));
3904     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3905     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3906     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3907     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3908     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3909     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3910     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3911     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3912     SDValue CheckLo =
3913         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3914     SDValue HiIsZero =
3915         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3916     SDValue AdjustedLo =
3917         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3918     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3919     SDValue Result =
3920         DAG.getSelect(dl, VTy, CheckLo,
3921                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3922     return Result;
3923   }
3924   case Intrinsic::eh_sjlj_lsda: {
3925     MachineFunction &MF = DAG.getMachineFunction();
3926     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3927     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3928     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3929     SDValue CPAddr;
3930     bool IsPositionIndependent = isPositionIndependent();
3931     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3932     ARMConstantPoolValue *CPV =
3933       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3934                                       ARMCP::CPLSDA, PCAdj);
3935     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3936     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3937     SDValue Result = DAG.getLoad(
3938         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3939         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3940 
3941     if (IsPositionIndependent) {
3942       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3943       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3944     }
3945     return Result;
3946   }
3947   case Intrinsic::arm_neon_vabs:
3948     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3949                         Op.getOperand(1));
3950   case Intrinsic::arm_neon_vmulls:
3951   case Intrinsic::arm_neon_vmullu: {
3952     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3953       ? ARMISD::VMULLs : ARMISD::VMULLu;
3954     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3955                        Op.getOperand(1), Op.getOperand(2));
3956   }
3957   case Intrinsic::arm_neon_vminnm:
3958   case Intrinsic::arm_neon_vmaxnm: {
3959     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3960       ? ISD::FMINNUM : ISD::FMAXNUM;
3961     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3962                        Op.getOperand(1), Op.getOperand(2));
3963   }
3964   case Intrinsic::arm_neon_vminu:
3965   case Intrinsic::arm_neon_vmaxu: {
3966     if (Op.getValueType().isFloatingPoint())
3967       return SDValue();
3968     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3969       ? ISD::UMIN : ISD::UMAX;
3970     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3971                          Op.getOperand(1), Op.getOperand(2));
3972   }
3973   case Intrinsic::arm_neon_vmins:
3974   case Intrinsic::arm_neon_vmaxs: {
3975     // v{min,max}s is overloaded between signed integers and floats.
3976     if (!Op.getValueType().isFloatingPoint()) {
3977       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3978         ? ISD::SMIN : ISD::SMAX;
3979       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3980                          Op.getOperand(1), Op.getOperand(2));
3981     }
3982     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3983       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3984     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3985                        Op.getOperand(1), Op.getOperand(2));
3986   }
3987   case Intrinsic::arm_neon_vtbl1:
3988     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3989                        Op.getOperand(1), Op.getOperand(2));
3990   case Intrinsic::arm_neon_vtbl2:
3991     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3992                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3993   case Intrinsic::arm_mve_pred_i2v:
3994   case Intrinsic::arm_mve_pred_v2i:
3995     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3996                        Op.getOperand(1));
3997   case Intrinsic::arm_mve_vreinterpretq:
3998     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
3999                        Op.getOperand(1));
4000   case Intrinsic::arm_mve_lsll:
4001     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
4002                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4003   case Intrinsic::arm_mve_asrl:
4004     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
4005                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4006   }
4007 }
4008 
4009 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4010                                  const ARMSubtarget *Subtarget) {
4011   SDLoc dl(Op);
4012   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4013   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4014   if (SSID == SyncScope::SingleThread)
4015     return Op;
4016 
4017   if (!Subtarget->hasDataBarrier()) {
4018     // Some ARMv6 cpus can support data barriers with an mcr instruction.
4019     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4020     // here.
4021     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4022            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4023     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4024                        DAG.getConstant(0, dl, MVT::i32));
4025   }
4026 
4027   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4028   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4029   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4030   if (Subtarget->isMClass()) {
4031     // Only a full system barrier exists in the M-class architectures.
4032     Domain = ARM_MB::SY;
4033   } else if (Subtarget->preferISHSTBarriers() &&
4034              Ord == AtomicOrdering::Release) {
4035     // Swift happens to implement ISHST barriers in a way that's compatible with
4036     // Release semantics but weaker than ISH so we'd be fools not to use
4037     // it. Beware: other processors probably don't!
4038     Domain = ARM_MB::ISHST;
4039   }
4040 
4041   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4042                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4043                      DAG.getConstant(Domain, dl, MVT::i32));
4044 }
4045 
4046 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4047                              const ARMSubtarget *Subtarget) {
4048   // ARM pre v5TE and Thumb1 does not have preload instructions.
4049   if (!(Subtarget->isThumb2() ||
4050         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4051     // Just preserve the chain.
4052     return Op.getOperand(0);
4053 
4054   SDLoc dl(Op);
4055   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4056   if (!isRead &&
4057       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4058     // ARMv7 with MP extension has PLDW.
4059     return Op.getOperand(0);
4060 
4061   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4062   if (Subtarget->isThumb()) {
4063     // Invert the bits.
4064     isRead = ~isRead & 1;
4065     isData = ~isData & 1;
4066   }
4067 
4068   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4069                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4070                      DAG.getConstant(isData, dl, MVT::i32));
4071 }
4072 
4073 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4074   MachineFunction &MF = DAG.getMachineFunction();
4075   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4076 
4077   // vastart just stores the address of the VarArgsFrameIndex slot into the
4078   // memory location argument.
4079   SDLoc dl(Op);
4080   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4081   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4082   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4083   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4084                       MachinePointerInfo(SV));
4085 }
4086 
4087 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4088                                                 CCValAssign &NextVA,
4089                                                 SDValue &Root,
4090                                                 SelectionDAG &DAG,
4091                                                 const SDLoc &dl) const {
4092   MachineFunction &MF = DAG.getMachineFunction();
4093   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4094 
4095   const TargetRegisterClass *RC;
4096   if (AFI->isThumb1OnlyFunction())
4097     RC = &ARM::tGPRRegClass;
4098   else
4099     RC = &ARM::GPRRegClass;
4100 
4101   // Transform the arguments stored in physical registers into virtual ones.
4102   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4103   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4104 
4105   SDValue ArgValue2;
4106   if (NextVA.isMemLoc()) {
4107     MachineFrameInfo &MFI = MF.getFrameInfo();
4108     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4109 
4110     // Create load node to retrieve arguments from the stack.
4111     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4112     ArgValue2 = DAG.getLoad(
4113         MVT::i32, dl, Root, FIN,
4114         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4115   } else {
4116     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4117     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4118   }
4119   if (!Subtarget->isLittle())
4120     std::swap (ArgValue, ArgValue2);
4121   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4122 }
4123 
4124 // The remaining GPRs hold either the beginning of variable-argument
4125 // data, or the beginning of an aggregate passed by value (usually
4126 // byval).  Either way, we allocate stack slots adjacent to the data
4127 // provided by our caller, and store the unallocated registers there.
4128 // If this is a variadic function, the va_list pointer will begin with
4129 // these values; otherwise, this reassembles a (byval) structure that
4130 // was split between registers and memory.
4131 // Return: The frame index registers were stored into.
4132 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4133                                       const SDLoc &dl, SDValue &Chain,
4134                                       const Value *OrigArg,
4135                                       unsigned InRegsParamRecordIdx,
4136                                       int ArgOffset, unsigned ArgSize) const {
4137   // Currently, two use-cases possible:
4138   // Case #1. Non-var-args function, and we meet first byval parameter.
4139   //          Setup first unallocated register as first byval register;
4140   //          eat all remained registers
4141   //          (these two actions are performed by HandleByVal method).
4142   //          Then, here, we initialize stack frame with
4143   //          "store-reg" instructions.
4144   // Case #2. Var-args function, that doesn't contain byval parameters.
4145   //          The same: eat all remained unallocated registers,
4146   //          initialize stack frame.
4147 
4148   MachineFunction &MF = DAG.getMachineFunction();
4149   MachineFrameInfo &MFI = MF.getFrameInfo();
4150   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4151   unsigned RBegin, REnd;
4152   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4153     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4154   } else {
4155     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4156     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4157     REnd = ARM::R4;
4158   }
4159 
4160   if (REnd != RBegin)
4161     ArgOffset = -4 * (ARM::R4 - RBegin);
4162 
4163   auto PtrVT = getPointerTy(DAG.getDataLayout());
4164   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4165   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4166 
4167   SmallVector<SDValue, 4> MemOps;
4168   const TargetRegisterClass *RC =
4169       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4170 
4171   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4172     unsigned VReg = MF.addLiveIn(Reg, RC);
4173     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4174     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4175                                  MachinePointerInfo(OrigArg, 4 * i));
4176     MemOps.push_back(Store);
4177     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4178   }
4179 
4180   if (!MemOps.empty())
4181     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4182   return FrameIndex;
4183 }
4184 
4185 // Setup stack frame, the va_list pointer will start from.
4186 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4187                                              const SDLoc &dl, SDValue &Chain,
4188                                              unsigned ArgOffset,
4189                                              unsigned TotalArgRegsSaveSize,
4190                                              bool ForceMutable) const {
4191   MachineFunction &MF = DAG.getMachineFunction();
4192   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4193 
4194   // Try to store any remaining integer argument regs
4195   // to their spots on the stack so that they may be loaded by dereferencing
4196   // the result of va_next.
4197   // If there is no regs to be stored, just point address after last
4198   // argument passed via stack.
4199   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4200                                   CCInfo.getInRegsParamsCount(),
4201                                   CCInfo.getNextStackOffset(),
4202                                   std::max(4U, TotalArgRegsSaveSize));
4203   AFI->setVarArgsFrameIndex(FrameIndex);
4204 }
4205 
4206 bool ARMTargetLowering::splitValueIntoRegisterParts(
4207     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4208     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4209   bool IsABIRegCopy = CC.hasValue();
4210   EVT ValueVT = Val.getValueType();
4211   if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4212       PartVT == MVT::f32) {
4213     unsigned ValueBits = ValueVT.getSizeInBits();
4214     unsigned PartBits = PartVT.getSizeInBits();
4215     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4216     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4217     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4218     Parts[0] = Val;
4219     return true;
4220   }
4221   return false;
4222 }
4223 
4224 SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4225     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4226     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4227   bool IsABIRegCopy = CC.hasValue();
4228   if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4229       PartVT == MVT::f32) {
4230     unsigned ValueBits = ValueVT.getSizeInBits();
4231     unsigned PartBits = PartVT.getSizeInBits();
4232     SDValue Val = Parts[0];
4233 
4234     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4235     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4236     Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4237     return Val;
4238   }
4239   return SDValue();
4240 }
4241 
4242 SDValue ARMTargetLowering::LowerFormalArguments(
4243     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4244     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4245     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4246   MachineFunction &MF = DAG.getMachineFunction();
4247   MachineFrameInfo &MFI = MF.getFrameInfo();
4248 
4249   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4250 
4251   // Assign locations to all of the incoming arguments.
4252   SmallVector<CCValAssign, 16> ArgLocs;
4253   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4254                  *DAG.getContext());
4255   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4256 
4257   SmallVector<SDValue, 16> ArgValues;
4258   SDValue ArgValue;
4259   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4260   unsigned CurArgIdx = 0;
4261 
4262   // Initially ArgRegsSaveSize is zero.
4263   // Then we increase this value each time we meet byval parameter.
4264   // We also increase this value in case of varargs function.
4265   AFI->setArgRegsSaveSize(0);
4266 
4267   // Calculate the amount of stack space that we need to allocate to store
4268   // byval and variadic arguments that are passed in registers.
4269   // We need to know this before we allocate the first byval or variadic
4270   // argument, as they will be allocated a stack slot below the CFA (Canonical
4271   // Frame Address, the stack pointer at entry to the function).
4272   unsigned ArgRegBegin = ARM::R4;
4273   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4274     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4275       break;
4276 
4277     CCValAssign &VA = ArgLocs[i];
4278     unsigned Index = VA.getValNo();
4279     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4280     if (!Flags.isByVal())
4281       continue;
4282 
4283     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4284     unsigned RBegin, REnd;
4285     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4286     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4287 
4288     CCInfo.nextInRegsParam();
4289   }
4290   CCInfo.rewindByValRegsInfo();
4291 
4292   int lastInsIndex = -1;
4293   if (isVarArg && MFI.hasVAStart()) {
4294     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4295     if (RegIdx != array_lengthof(GPRArgRegs))
4296       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4297   }
4298 
4299   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4300   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4301   auto PtrVT = getPointerTy(DAG.getDataLayout());
4302 
4303   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4304     CCValAssign &VA = ArgLocs[i];
4305     if (Ins[VA.getValNo()].isOrigArg()) {
4306       std::advance(CurOrigArg,
4307                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4308       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4309     }
4310     // Arguments stored in registers.
4311     if (VA.isRegLoc()) {
4312       EVT RegVT = VA.getLocVT();
4313 
4314       if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4315         // f64 and vector types are split up into multiple registers or
4316         // combinations of registers and stack slots.
4317         SDValue ArgValue1 =
4318             GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4319         VA = ArgLocs[++i]; // skip ahead to next loc
4320         SDValue ArgValue2;
4321         if (VA.isMemLoc()) {
4322           int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4323           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4324           ArgValue2 = DAG.getLoad(
4325               MVT::f64, dl, Chain, FIN,
4326               MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4327         } else {
4328           ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4329         }
4330         ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4331         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4332                                ArgValue1, DAG.getIntPtrConstant(0, dl));
4333         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4334                                ArgValue2, DAG.getIntPtrConstant(1, dl));
4335       } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4336         ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4337       } else {
4338         const TargetRegisterClass *RC;
4339 
4340         if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4341           RC = &ARM::HPRRegClass;
4342         else if (RegVT == MVT::f32)
4343           RC = &ARM::SPRRegClass;
4344         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4345                  RegVT == MVT::v4bf16)
4346           RC = &ARM::DPRRegClass;
4347         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4348                  RegVT == MVT::v8bf16)
4349           RC = &ARM::QPRRegClass;
4350         else if (RegVT == MVT::i32)
4351           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4352                                            : &ARM::GPRRegClass;
4353         else
4354           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4355 
4356         // Transform the arguments in physical registers into virtual ones.
4357         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4358         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4359 
4360         // If this value is passed in r0 and has the returned attribute (e.g.
4361         // C++ 'structors), record this fact for later use.
4362         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4363           AFI->setPreservesR0();
4364         }
4365       }
4366 
4367       // If this is an 8 or 16-bit value, it is really passed promoted
4368       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4369       // truncate to the right size.
4370       switch (VA.getLocInfo()) {
4371       default: llvm_unreachable("Unknown loc info!");
4372       case CCValAssign::Full: break;
4373       case CCValAssign::BCvt:
4374         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4375         break;
4376       case CCValAssign::SExt:
4377         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4378                                DAG.getValueType(VA.getValVT()));
4379         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4380         break;
4381       case CCValAssign::ZExt:
4382         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4383                                DAG.getValueType(VA.getValVT()));
4384         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4385         break;
4386       }
4387 
4388       // f16 arguments have their size extended to 4 bytes and passed as if they
4389       // had been copied to the LSBs of a 32-bit register.
4390       // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4391       if (VA.needsCustom() &&
4392           (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4393         ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4394 
4395       InVals.push_back(ArgValue);
4396     } else { // VA.isRegLoc()
4397       // sanity check
4398       assert(VA.isMemLoc());
4399       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4400 
4401       int index = VA.getValNo();
4402 
4403       // Some Ins[] entries become multiple ArgLoc[] entries.
4404       // Process them only once.
4405       if (index != lastInsIndex)
4406         {
4407           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4408           // FIXME: For now, all byval parameter objects are marked mutable.
4409           // This can be changed with more analysis.
4410           // In case of tail call optimization mark all arguments mutable.
4411           // Since they could be overwritten by lowering of arguments in case of
4412           // a tail call.
4413           if (Flags.isByVal()) {
4414             assert(Ins[index].isOrigArg() &&
4415                    "Byval arguments cannot be implicit");
4416             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4417 
4418             int FrameIndex = StoreByValRegs(
4419                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4420                 VA.getLocMemOffset(), Flags.getByValSize());
4421             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4422             CCInfo.nextInRegsParam();
4423           } else {
4424             unsigned FIOffset = VA.getLocMemOffset();
4425             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4426                                            FIOffset, true);
4427 
4428             // Create load nodes to retrieve arguments from the stack.
4429             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4430             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4431                                          MachinePointerInfo::getFixedStack(
4432                                              DAG.getMachineFunction(), FI)));
4433           }
4434           lastInsIndex = index;
4435         }
4436     }
4437   }
4438 
4439   // varargs
4440   if (isVarArg && MFI.hasVAStart()) {
4441     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4442                          TotalArgRegsSaveSize);
4443     if (AFI->isCmseNSEntryFunction()) {
4444       DiagnosticInfoUnsupported Diag(
4445           DAG.getMachineFunction().getFunction(),
4446           "secure entry function must not be variadic", dl.getDebugLoc());
4447       DAG.getContext()->diagnose(Diag);
4448     }
4449   }
4450 
4451   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4452 
4453   if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4454     DiagnosticInfoUnsupported Diag(
4455         DAG.getMachineFunction().getFunction(),
4456         "secure entry function requires arguments on stack", dl.getDebugLoc());
4457     DAG.getContext()->diagnose(Diag);
4458   }
4459 
4460   return Chain;
4461 }
4462 
4463 /// isFloatingPointZero - Return true if this is +0.0.
4464 static bool isFloatingPointZero(SDValue Op) {
4465   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4466     return CFP->getValueAPF().isPosZero();
4467   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4468     // Maybe this has already been legalized into the constant pool?
4469     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4470       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4471       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4472         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4473           return CFP->getValueAPF().isPosZero();
4474     }
4475   } else if (Op->getOpcode() == ISD::BITCAST &&
4476              Op->getValueType(0) == MVT::f64) {
4477     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4478     // created by LowerConstantFP().
4479     SDValue BitcastOp = Op->getOperand(0);
4480     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4481         isNullConstant(BitcastOp->getOperand(0)))
4482       return true;
4483   }
4484   return false;
4485 }
4486 
4487 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4488 /// the given operands.
4489 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4490                                      SDValue &ARMcc, SelectionDAG &DAG,
4491                                      const SDLoc &dl) const {
4492   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4493     unsigned C = RHSC->getZExtValue();
4494     if (!isLegalICmpImmediate((int32_t)C)) {
4495       // Constant does not fit, try adjusting it by one.
4496       switch (CC) {
4497       default: break;
4498       case ISD::SETLT:
4499       case ISD::SETGE:
4500         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4501           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4502           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4503         }
4504         break;
4505       case ISD::SETULT:
4506       case ISD::SETUGE:
4507         if (C != 0 && isLegalICmpImmediate(C-1)) {
4508           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4509           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4510         }
4511         break;
4512       case ISD::SETLE:
4513       case ISD::SETGT:
4514         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4515           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4516           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4517         }
4518         break;
4519       case ISD::SETULE:
4520       case ISD::SETUGT:
4521         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4522           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4523           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4524         }
4525         break;
4526       }
4527     }
4528   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4529              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4530     // In ARM and Thumb-2, the compare instructions can shift their second
4531     // operand.
4532     CC = ISD::getSetCCSwappedOperands(CC);
4533     std::swap(LHS, RHS);
4534   }
4535 
4536   // Thumb1 has very limited immediate modes, so turning an "and" into a
4537   // shift can save multiple instructions.
4538   //
4539   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4540   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4541   // own. If it's the operand to an unsigned comparison with an immediate,
4542   // we can eliminate one of the shifts: we transform
4543   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4544   //
4545   // We avoid transforming cases which aren't profitable due to encoding
4546   // details:
4547   //
4548   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4549   // would not; in that case, we're essentially trading one immediate load for
4550   // another.
4551   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4552   // 3. C2 is zero; we have other code for this special case.
4553   //
4554   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4555   // instruction, since the AND is always one instruction anyway, but we could
4556   // use narrow instructions in some cases.
4557   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4558       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4559       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4560       !isSignedIntSetCC(CC)) {
4561     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4562     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4563     uint64_t RHSV = RHSC->getZExtValue();
4564     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4565       unsigned ShiftBits = countLeadingZeros(Mask);
4566       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4567         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4568         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4569         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4570       }
4571     }
4572   }
4573 
4574   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4575   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4576   // way a cmp would.
4577   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4578   // some tweaks to the heuristics for the previous and->shift transform.
4579   // FIXME: Optimize cases where the LHS isn't a shift.
4580   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4581       isa<ConstantSDNode>(RHS) &&
4582       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4583       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4584       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4585     unsigned ShiftAmt =
4586       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4587     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4588                                 DAG.getVTList(MVT::i32, MVT::i32),
4589                                 LHS.getOperand(0),
4590                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4591     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4592                                      Shift.getValue(1), SDValue());
4593     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4594     return Chain.getValue(1);
4595   }
4596 
4597   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4598 
4599   // If the RHS is a constant zero then the V (overflow) flag will never be
4600   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4601   // simpler for other passes (like the peephole optimiser) to deal with.
4602   if (isNullConstant(RHS)) {
4603     switch (CondCode) {
4604       default: break;
4605       case ARMCC::GE:
4606         CondCode = ARMCC::PL;
4607         break;
4608       case ARMCC::LT:
4609         CondCode = ARMCC::MI;
4610         break;
4611     }
4612   }
4613 
4614   ARMISD::NodeType CompareType;
4615   switch (CondCode) {
4616   default:
4617     CompareType = ARMISD::CMP;
4618     break;
4619   case ARMCC::EQ:
4620   case ARMCC::NE:
4621     // Uses only Z Flag
4622     CompareType = ARMISD::CMPZ;
4623     break;
4624   }
4625   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4626   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4627 }
4628 
4629 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4630 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4631                                      SelectionDAG &DAG, const SDLoc &dl,
4632                                      bool Signaling) const {
4633   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4634   SDValue Cmp;
4635   if (!isFloatingPointZero(RHS))
4636     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4637                       dl, MVT::Glue, LHS, RHS);
4638   else
4639     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4640                       dl, MVT::Glue, LHS);
4641   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4642 }
4643 
4644 /// duplicateCmp - Glue values can have only one use, so this function
4645 /// duplicates a comparison node.
4646 SDValue
4647 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4648   unsigned Opc = Cmp.getOpcode();
4649   SDLoc DL(Cmp);
4650   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4651     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4652 
4653   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4654   Cmp = Cmp.getOperand(0);
4655   Opc = Cmp.getOpcode();
4656   if (Opc == ARMISD::CMPFP)
4657     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4658   else {
4659     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4660     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4661   }
4662   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4663 }
4664 
4665 // This function returns three things: the arithmetic computation itself
4666 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4667 // comparison and the condition code define the case in which the arithmetic
4668 // computation *does not* overflow.
4669 std::pair<SDValue, SDValue>
4670 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4671                                  SDValue &ARMcc) const {
4672   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4673 
4674   SDValue Value, OverflowCmp;
4675   SDValue LHS = Op.getOperand(0);
4676   SDValue RHS = Op.getOperand(1);
4677   SDLoc dl(Op);
4678 
4679   // FIXME: We are currently always generating CMPs because we don't support
4680   // generating CMN through the backend. This is not as good as the natural
4681   // CMP case because it causes a register dependency and cannot be folded
4682   // later.
4683 
4684   switch (Op.getOpcode()) {
4685   default:
4686     llvm_unreachable("Unknown overflow instruction!");
4687   case ISD::SADDO:
4688     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4689     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4690     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4691     break;
4692   case ISD::UADDO:
4693     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4694     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4695     // We do not use it in the USUBO case as Value may not be used.
4696     Value = DAG.getNode(ARMISD::ADDC, dl,
4697                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4698                 .getValue(0);
4699     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4700     break;
4701   case ISD::SSUBO:
4702     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4703     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4704     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4705     break;
4706   case ISD::USUBO:
4707     ARMcc = DAG.getConstant(ARMCC::HS, 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::UMULO:
4712     // We generate a UMUL_LOHI and then check if the high word is 0.
4713     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4714     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4715                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4716                         LHS, RHS);
4717     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4718                               DAG.getConstant(0, dl, MVT::i32));
4719     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4720     break;
4721   case ISD::SMULO:
4722     // We generate a SMUL_LOHI and then check if all the bits of the high word
4723     // are the same as the sign bit of the low word.
4724     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4725     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4726                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4727                         LHS, RHS);
4728     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4729                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4730                                           Value.getValue(0),
4731                                           DAG.getConstant(31, dl, MVT::i32)));
4732     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4733     break;
4734   } // switch (...)
4735 
4736   return std::make_pair(Value, OverflowCmp);
4737 }
4738 
4739 SDValue
4740 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4741   // Let legalize expand this if it isn't a legal type yet.
4742   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4743     return SDValue();
4744 
4745   SDValue Value, OverflowCmp;
4746   SDValue ARMcc;
4747   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4748   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4749   SDLoc dl(Op);
4750   // We use 0 and 1 as false and true values.
4751   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4752   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4753   EVT VT = Op.getValueType();
4754 
4755   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4756                                  ARMcc, CCR, OverflowCmp);
4757 
4758   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4759   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4760 }
4761 
4762 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4763                                               SelectionDAG &DAG) {
4764   SDLoc DL(BoolCarry);
4765   EVT CarryVT = BoolCarry.getValueType();
4766 
4767   // This converts the boolean value carry into the carry flag by doing
4768   // ARMISD::SUBC Carry, 1
4769   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4770                               DAG.getVTList(CarryVT, MVT::i32),
4771                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4772   return Carry.getValue(1);
4773 }
4774 
4775 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4776                                               SelectionDAG &DAG) {
4777   SDLoc DL(Flags);
4778 
4779   // Now convert the carry flag into a boolean carry. We do this
4780   // using ARMISD:ADDE 0, 0, Carry
4781   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4782                      DAG.getConstant(0, DL, MVT::i32),
4783                      DAG.getConstant(0, DL, MVT::i32), Flags);
4784 }
4785 
4786 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4787                                              SelectionDAG &DAG) const {
4788   // Let legalize expand this if it isn't a legal type yet.
4789   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4790     return SDValue();
4791 
4792   SDValue LHS = Op.getOperand(0);
4793   SDValue RHS = Op.getOperand(1);
4794   SDLoc dl(Op);
4795 
4796   EVT VT = Op.getValueType();
4797   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4798   SDValue Value;
4799   SDValue Overflow;
4800   switch (Op.getOpcode()) {
4801   default:
4802     llvm_unreachable("Unknown overflow instruction!");
4803   case ISD::UADDO:
4804     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4805     // Convert the carry flag into a boolean value.
4806     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4807     break;
4808   case ISD::USUBO: {
4809     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4810     // Convert the carry flag into a boolean value.
4811     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4812     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4813     // value. So compute 1 - C.
4814     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4815                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4816     break;
4817   }
4818   }
4819 
4820   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4821 }
4822 
4823 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4824                                const ARMSubtarget *Subtarget) {
4825   EVT VT = Op.getValueType();
4826   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4827     return SDValue();
4828   if (!VT.isSimple())
4829     return SDValue();
4830 
4831   unsigned NewOpcode;
4832   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4833   switch (VT.getSimpleVT().SimpleTy) {
4834   default:
4835     return SDValue();
4836   case MVT::i8:
4837     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4838     break;
4839   case MVT::i16:
4840     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4841     break;
4842   }
4843 
4844   SDLoc dl(Op);
4845   SDValue Add =
4846       DAG.getNode(NewOpcode, dl, MVT::i32,
4847                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4848                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4849   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4850 }
4851 
4852 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4853   SDValue Cond = Op.getOperand(0);
4854   SDValue SelectTrue = Op.getOperand(1);
4855   SDValue SelectFalse = Op.getOperand(2);
4856   SDLoc dl(Op);
4857   unsigned Opc = Cond.getOpcode();
4858 
4859   if (Cond.getResNo() == 1 &&
4860       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4861        Opc == ISD::USUBO)) {
4862     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4863       return SDValue();
4864 
4865     SDValue Value, OverflowCmp;
4866     SDValue ARMcc;
4867     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4868     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4869     EVT VT = Op.getValueType();
4870 
4871     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4872                    OverflowCmp, DAG);
4873   }
4874 
4875   // Convert:
4876   //
4877   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4878   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4879   //
4880   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4881     const ConstantSDNode *CMOVTrue =
4882       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4883     const ConstantSDNode *CMOVFalse =
4884       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4885 
4886     if (CMOVTrue && CMOVFalse) {
4887       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4888       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4889 
4890       SDValue True;
4891       SDValue False;
4892       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4893         True = SelectTrue;
4894         False = SelectFalse;
4895       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4896         True = SelectFalse;
4897         False = SelectTrue;
4898       }
4899 
4900       if (True.getNode() && False.getNode()) {
4901         EVT VT = Op.getValueType();
4902         SDValue ARMcc = Cond.getOperand(2);
4903         SDValue CCR = Cond.getOperand(3);
4904         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4905         assert(True.getValueType() == VT);
4906         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4907       }
4908     }
4909   }
4910 
4911   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4912   // undefined bits before doing a full-word comparison with zero.
4913   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4914                      DAG.getConstant(1, dl, Cond.getValueType()));
4915 
4916   return DAG.getSelectCC(dl, Cond,
4917                          DAG.getConstant(0, dl, Cond.getValueType()),
4918                          SelectTrue, SelectFalse, ISD::SETNE);
4919 }
4920 
4921 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4922                                  bool &swpCmpOps, bool &swpVselOps) {
4923   // Start by selecting the GE condition code for opcodes that return true for
4924   // 'equality'
4925   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4926       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4927     CondCode = ARMCC::GE;
4928 
4929   // and GT for opcodes that return false for 'equality'.
4930   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4931            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4932     CondCode = ARMCC::GT;
4933 
4934   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4935   // to swap the compare operands.
4936   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4937       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4938     swpCmpOps = true;
4939 
4940   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4941   // If we have an unordered opcode, we need to swap the operands to the VSEL
4942   // instruction (effectively negating the condition).
4943   //
4944   // This also has the effect of swapping which one of 'less' or 'greater'
4945   // returns true, so we also swap the compare operands. It also switches
4946   // whether we return true for 'equality', so we compensate by picking the
4947   // opposite condition code to our original choice.
4948   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4949       CC == ISD::SETUGT) {
4950     swpCmpOps = !swpCmpOps;
4951     swpVselOps = !swpVselOps;
4952     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4953   }
4954 
4955   // 'ordered' is 'anything but unordered', so use the VS condition code and
4956   // swap the VSEL operands.
4957   if (CC == ISD::SETO) {
4958     CondCode = ARMCC::VS;
4959     swpVselOps = true;
4960   }
4961 
4962   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4963   // code and swap the VSEL operands. Also do this if we don't care about the
4964   // unordered case.
4965   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4966     CondCode = ARMCC::EQ;
4967     swpVselOps = true;
4968   }
4969 }
4970 
4971 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4972                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4973                                    SDValue Cmp, SelectionDAG &DAG) const {
4974   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4975     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4976                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4977     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4978                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4979 
4980     SDValue TrueLow = TrueVal.getValue(0);
4981     SDValue TrueHigh = TrueVal.getValue(1);
4982     SDValue FalseLow = FalseVal.getValue(0);
4983     SDValue FalseHigh = FalseVal.getValue(1);
4984 
4985     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4986                               ARMcc, CCR, Cmp);
4987     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4988                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4989 
4990     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4991   } else {
4992     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4993                        Cmp);
4994   }
4995 }
4996 
4997 static bool isGTorGE(ISD::CondCode CC) {
4998   return CC == ISD::SETGT || CC == ISD::SETGE;
4999 }
5000 
5001 static bool isLTorLE(ISD::CondCode CC) {
5002   return CC == ISD::SETLT || CC == ISD::SETLE;
5003 }
5004 
5005 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
5006 // All of these conditions (and their <= and >= counterparts) will do:
5007 //          x < k ? k : x
5008 //          x > k ? x : k
5009 //          k < x ? x : k
5010 //          k > x ? k : x
5011 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5012                             const SDValue TrueVal, const SDValue FalseVal,
5013                             const ISD::CondCode CC, const SDValue K) {
5014   return (isGTorGE(CC) &&
5015           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5016          (isLTorLE(CC) &&
5017           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5018 }
5019 
5020 // Check if two chained conditionals could be converted into SSAT or USAT.
5021 //
5022 // SSAT can replace a set of two conditional selectors that bound a number to an
5023 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5024 //
5025 //     x < -k ? -k : (x > k ? k : x)
5026 //     x < -k ? -k : (x < k ? x : k)
5027 //     x > -k ? (x > k ? k : x) : -k
5028 //     x < k ? (x < -k ? -k : x) : k
5029 //     etc.
5030 //
5031 // LLVM canonicalizes these to either a min(max()) or a max(min())
5032 // pattern. This function tries to match one of these and will return true
5033 // if successful.
5034 //
5035 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
5036 // a power of 2.
5037 //
5038 // It returns true if the conversion can be done, false otherwise.
5039 // Additionally, the variable is returned in parameter V, the constant in K and
5040 // usat is set to true if the conditional represents an unsigned saturation
5041 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
5042                                     uint64_t &K, bool &Usat) {
5043   SDValue V1 = Op.getOperand(0);
5044   SDValue K1 = Op.getOperand(1);
5045   SDValue TrueVal1 = Op.getOperand(2);
5046   SDValue FalseVal1 = Op.getOperand(3);
5047   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5048 
5049   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5050   if (Op2.getOpcode() != ISD::SELECT_CC)
5051     return false;
5052 
5053   SDValue V2 = Op2.getOperand(0);
5054   SDValue K2 = Op2.getOperand(1);
5055   SDValue TrueVal2 = Op2.getOperand(2);
5056   SDValue FalseVal2 = Op2.getOperand(3);
5057   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5058 
5059   SDValue V1Tmp = V1;
5060   SDValue V2Tmp = V2;
5061 
5062   if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5063       V2.getOpcode() == ISD::SIGN_EXTEND_INREG) {
5064     V1Tmp = V1.getOperand(0);
5065     V2Tmp = V2.getOperand(0);
5066   }
5067 
5068   // Check that the registers and the constants match a max(min()) or min(max())
5069   // pattern
5070   if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 &&
5071       K2 == FalseVal2 &&
5072       ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) {
5073 
5074     // Check that the constant in the lower-bound check is
5075     // the opposite of the constant in the upper-bound check
5076     // in 1's complement.
5077     if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5078       return false;
5079 
5080     int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5081     int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5082     int64_t PosVal = std::max(Val1, Val2);
5083     int64_t NegVal = std::min(Val1, Val2);
5084 
5085     if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5086         !isPowerOf2_64(PosVal + 1))
5087       return false;
5088 
5089     // Handle the difference between USAT (unsigned) and SSAT (signed)
5090     // saturation
5091     if (Val1 == ~Val2)
5092       Usat = false;
5093     else if (NegVal == 0)
5094       Usat = true;
5095     else
5096       return false;
5097 
5098     V = V2Tmp;
5099     // At this point, PosVal is guaranteed to be positive
5100     K = (uint64_t) PosVal;
5101 
5102     return true;
5103   }
5104   return false;
5105 }
5106 
5107 // Check if a condition of the type x < k ? k : x can be converted into a
5108 // bit operation instead of conditional moves.
5109 // Currently this is allowed given:
5110 // - The conditions and values match up
5111 // - k is 0 or -1 (all ones)
5112 // This function will not check the last condition, thats up to the caller
5113 // It returns true if the transformation can be made, and in such case
5114 // returns x in V, and k in SatK.
5115 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5116                                          SDValue &SatK)
5117 {
5118   SDValue LHS = Op.getOperand(0);
5119   SDValue RHS = Op.getOperand(1);
5120   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5121   SDValue TrueVal = Op.getOperand(2);
5122   SDValue FalseVal = Op.getOperand(3);
5123 
5124   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5125                                                ? &RHS
5126                                                : nullptr;
5127 
5128   // No constant operation in comparison, early out
5129   if (!K)
5130     return false;
5131 
5132   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5133   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5134   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5135 
5136   // If the constant on left and right side, or variable on left and right,
5137   // does not match, early out
5138   if (*K != KTmp || V != VTmp)
5139     return false;
5140 
5141   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5142     SatK = *K;
5143     return true;
5144   }
5145 
5146   return false;
5147 }
5148 
5149 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5150   if (VT == MVT::f32)
5151     return !Subtarget->hasVFP2Base();
5152   if (VT == MVT::f64)
5153     return !Subtarget->hasFP64();
5154   if (VT == MVT::f16)
5155     return !Subtarget->hasFullFP16();
5156   return false;
5157 }
5158 
5159 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5160   EVT VT = Op.getValueType();
5161   SDLoc dl(Op);
5162 
5163   // Try to convert two saturating conditional selects into a single SSAT
5164   SDValue SatValue;
5165   uint64_t SatConstant;
5166   bool SatUSat;
5167   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
5168       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
5169     if (SatUSat)
5170       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
5171                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5172     else
5173       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
5174                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5175   }
5176 
5177   // Try to convert expressions of the form x < k ? k : x (and similar forms)
5178   // into more efficient bit operations, which is possible when k is 0 or -1
5179   // On ARM and Thumb-2 which have flexible operand 2 this will result in
5180   // single instructions. On Thumb the shift and the bit operation will be two
5181   // instructions.
5182   // Only allow this transformation on full-width (32-bit) operations
5183   SDValue LowerSatConstant;
5184   if (VT == MVT::i32 &&
5185       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5186     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5187                                  DAG.getConstant(31, dl, VT));
5188     if (isNullConstant(LowerSatConstant)) {
5189       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5190                                       DAG.getAllOnesConstant(dl, VT));
5191       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5192     } else if (isAllOnesConstant(LowerSatConstant))
5193       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5194   }
5195 
5196   SDValue LHS = Op.getOperand(0);
5197   SDValue RHS = Op.getOperand(1);
5198   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5199   SDValue TrueVal = Op.getOperand(2);
5200   SDValue FalseVal = Op.getOperand(3);
5201   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5202   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5203 
5204   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5205       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5206     unsigned TVal = CTVal->getZExtValue();
5207     unsigned FVal = CFVal->getZExtValue();
5208     unsigned Opcode = 0;
5209 
5210     if (TVal == ~FVal) {
5211       Opcode = ARMISD::CSINV;
5212     } else if (TVal == ~FVal + 1) {
5213       Opcode = ARMISD::CSNEG;
5214     } else if (TVal + 1 == FVal) {
5215       Opcode = ARMISD::CSINC;
5216     } else if (TVal == FVal + 1) {
5217       Opcode = ARMISD::CSINC;
5218       std::swap(TrueVal, FalseVal);
5219       std::swap(TVal, FVal);
5220       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5221     }
5222 
5223     if (Opcode) {
5224       // If one of the constants is cheaper than another, materialise the
5225       // cheaper one and let the csel generate the other.
5226       if (Opcode != ARMISD::CSINC &&
5227           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5228         std::swap(TrueVal, FalseVal);
5229         std::swap(TVal, FVal);
5230         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5231       }
5232 
5233       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5234       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5235       // -(-a) == a, but (a+1)+1 != a).
5236       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5237         std::swap(TrueVal, FalseVal);
5238         std::swap(TVal, FVal);
5239         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5240       }
5241       if (TVal == 0)
5242         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5243 
5244       // Drops F's value because we can get it by inverting/negating TVal.
5245       FalseVal = TrueVal;
5246 
5247       SDValue ARMcc;
5248       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5249       EVT VT = TrueVal.getValueType();
5250       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5251     }
5252   }
5253 
5254   if (isUnsupportedFloatingType(LHS.getValueType())) {
5255     DAG.getTargetLoweringInfo().softenSetCCOperands(
5256         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5257 
5258     // If softenSetCCOperands only returned one value, we should compare it to
5259     // zero.
5260     if (!RHS.getNode()) {
5261       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5262       CC = ISD::SETNE;
5263     }
5264   }
5265 
5266   if (LHS.getValueType() == MVT::i32) {
5267     // Try to generate VSEL on ARMv8.
5268     // The VSEL instruction can't use all the usual ARM condition
5269     // codes: it only has two bits to select the condition code, so it's
5270     // constrained to use only GE, GT, VS and EQ.
5271     //
5272     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5273     // swap the operands of the previous compare instruction (effectively
5274     // inverting the compare condition, swapping 'less' and 'greater') and
5275     // sometimes need to swap the operands to the VSEL (which inverts the
5276     // condition in the sense of firing whenever the previous condition didn't)
5277     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5278                                         TrueVal.getValueType() == MVT::f32 ||
5279                                         TrueVal.getValueType() == MVT::f64)) {
5280       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5281       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5282           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5283         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5284         std::swap(TrueVal, FalseVal);
5285       }
5286     }
5287 
5288     SDValue ARMcc;
5289     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5290     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5291     // Choose GE over PL, which vsel does now support
5292     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5293       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5294     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5295   }
5296 
5297   ARMCC::CondCodes CondCode, CondCode2;
5298   FPCCToARMCC(CC, CondCode, CondCode2);
5299 
5300   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5301   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5302   // must use VSEL (limited condition codes), due to not having conditional f16
5303   // moves.
5304   if (Subtarget->hasFPARMv8Base() &&
5305       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5306       (TrueVal.getValueType() == MVT::f16 ||
5307        TrueVal.getValueType() == MVT::f32 ||
5308        TrueVal.getValueType() == MVT::f64)) {
5309     bool swpCmpOps = false;
5310     bool swpVselOps = false;
5311     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5312 
5313     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5314         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5315       if (swpCmpOps)
5316         std::swap(LHS, RHS);
5317       if (swpVselOps)
5318         std::swap(TrueVal, FalseVal);
5319     }
5320   }
5321 
5322   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5323   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5324   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5325   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5326   if (CondCode2 != ARMCC::AL) {
5327     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5328     // FIXME: Needs another CMP because flag can have but one use.
5329     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5330     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5331   }
5332   return Result;
5333 }
5334 
5335 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5336 /// to morph to an integer compare sequence.
5337 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5338                            const ARMSubtarget *Subtarget) {
5339   SDNode *N = Op.getNode();
5340   if (!N->hasOneUse())
5341     // Otherwise it requires moving the value from fp to integer registers.
5342     return false;
5343   if (!N->getNumValues())
5344     return false;
5345   EVT VT = Op.getValueType();
5346   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5347     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5348     // vmrs are very slow, e.g. cortex-a8.
5349     return false;
5350 
5351   if (isFloatingPointZero(Op)) {
5352     SeenZero = true;
5353     return true;
5354   }
5355   return ISD::isNormalLoad(N);
5356 }
5357 
5358 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5359   if (isFloatingPointZero(Op))
5360     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5361 
5362   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5363     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5364                        Ld->getPointerInfo(), Ld->getAlignment(),
5365                        Ld->getMemOperand()->getFlags());
5366 
5367   llvm_unreachable("Unknown VFP cmp argument!");
5368 }
5369 
5370 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5371                            SDValue &RetVal1, SDValue &RetVal2) {
5372   SDLoc dl(Op);
5373 
5374   if (isFloatingPointZero(Op)) {
5375     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5376     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5377     return;
5378   }
5379 
5380   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5381     SDValue Ptr = Ld->getBasePtr();
5382     RetVal1 =
5383         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5384                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5385 
5386     EVT PtrType = Ptr.getValueType();
5387     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5388     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5389                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5390     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5391                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5392                           Ld->getMemOperand()->getFlags());
5393     return;
5394   }
5395 
5396   llvm_unreachable("Unknown VFP cmp argument!");
5397 }
5398 
5399 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5400 /// f32 and even f64 comparisons to integer ones.
5401 SDValue
5402 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5403   SDValue Chain = Op.getOperand(0);
5404   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5405   SDValue LHS = Op.getOperand(2);
5406   SDValue RHS = Op.getOperand(3);
5407   SDValue Dest = Op.getOperand(4);
5408   SDLoc dl(Op);
5409 
5410   bool LHSSeenZero = false;
5411   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5412   bool RHSSeenZero = false;
5413   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5414   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5415     // If unsafe fp math optimization is enabled and there are no other uses of
5416     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5417     // to an integer comparison.
5418     if (CC == ISD::SETOEQ)
5419       CC = ISD::SETEQ;
5420     else if (CC == ISD::SETUNE)
5421       CC = ISD::SETNE;
5422 
5423     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5424     SDValue ARMcc;
5425     if (LHS.getValueType() == MVT::f32) {
5426       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5427                         bitcastf32Toi32(LHS, DAG), Mask);
5428       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5429                         bitcastf32Toi32(RHS, DAG), Mask);
5430       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5431       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5432       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5433                          Chain, Dest, ARMcc, CCR, Cmp);
5434     }
5435 
5436     SDValue LHS1, LHS2;
5437     SDValue RHS1, RHS2;
5438     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5439     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5440     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5441     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5442     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5443     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5444     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5445     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5446     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5447   }
5448 
5449   return SDValue();
5450 }
5451 
5452 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5453   SDValue Chain = Op.getOperand(0);
5454   SDValue Cond = Op.getOperand(1);
5455   SDValue Dest = Op.getOperand(2);
5456   SDLoc dl(Op);
5457 
5458   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5459   // instruction.
5460   unsigned Opc = Cond.getOpcode();
5461   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5462                       !Subtarget->isThumb1Only();
5463   if (Cond.getResNo() == 1 &&
5464       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5465        Opc == ISD::USUBO || OptimizeMul)) {
5466     // Only lower legal XALUO ops.
5467     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5468       return SDValue();
5469 
5470     // The actual operation with overflow check.
5471     SDValue Value, OverflowCmp;
5472     SDValue ARMcc;
5473     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5474 
5475     // Reverse the condition code.
5476     ARMCC::CondCodes CondCode =
5477         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5478     CondCode = ARMCC::getOppositeCondition(CondCode);
5479     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5480     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5481 
5482     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5483                        OverflowCmp);
5484   }
5485 
5486   return SDValue();
5487 }
5488 
5489 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5490   SDValue Chain = Op.getOperand(0);
5491   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5492   SDValue LHS = Op.getOperand(2);
5493   SDValue RHS = Op.getOperand(3);
5494   SDValue Dest = Op.getOperand(4);
5495   SDLoc dl(Op);
5496 
5497   if (isUnsupportedFloatingType(LHS.getValueType())) {
5498     DAG.getTargetLoweringInfo().softenSetCCOperands(
5499         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5500 
5501     // If softenSetCCOperands only returned one value, we should compare it to
5502     // zero.
5503     if (!RHS.getNode()) {
5504       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5505       CC = ISD::SETNE;
5506     }
5507   }
5508 
5509   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5510   // instruction.
5511   unsigned Opc = LHS.getOpcode();
5512   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5513                       !Subtarget->isThumb1Only();
5514   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5515       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5516        Opc == ISD::USUBO || OptimizeMul) &&
5517       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5518     // Only lower legal XALUO ops.
5519     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5520       return SDValue();
5521 
5522     // The actual operation with overflow check.
5523     SDValue Value, OverflowCmp;
5524     SDValue ARMcc;
5525     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5526 
5527     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5528       // Reverse the condition code.
5529       ARMCC::CondCodes CondCode =
5530           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5531       CondCode = ARMCC::getOppositeCondition(CondCode);
5532       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5533     }
5534     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5535 
5536     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5537                        OverflowCmp);
5538   }
5539 
5540   if (LHS.getValueType() == MVT::i32) {
5541     SDValue ARMcc;
5542     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5543     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5544     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5545                        Chain, Dest, ARMcc, CCR, Cmp);
5546   }
5547 
5548   if (getTargetMachine().Options.UnsafeFPMath &&
5549       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5550        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5551     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5552       return Result;
5553   }
5554 
5555   ARMCC::CondCodes CondCode, CondCode2;
5556   FPCCToARMCC(CC, CondCode, CondCode2);
5557 
5558   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5559   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5560   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5561   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5562   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5563   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5564   if (CondCode2 != ARMCC::AL) {
5565     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5566     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5567     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5568   }
5569   return Res;
5570 }
5571 
5572 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5573   SDValue Chain = Op.getOperand(0);
5574   SDValue Table = Op.getOperand(1);
5575   SDValue Index = Op.getOperand(2);
5576   SDLoc dl(Op);
5577 
5578   EVT PTy = getPointerTy(DAG.getDataLayout());
5579   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5580   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5581   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5582   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5583   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5584   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5585     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5586     // which does another jump to the destination. This also makes it easier
5587     // to translate it to TBB / TBH later (Thumb2 only).
5588     // FIXME: This might not work if the function is extremely large.
5589     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5590                        Addr, Op.getOperand(2), JTI);
5591   }
5592   if (isPositionIndependent() || Subtarget->isROPI()) {
5593     Addr =
5594         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5595                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5596     Chain = Addr.getValue(1);
5597     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5598     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5599   } else {
5600     Addr =
5601         DAG.getLoad(PTy, dl, Chain, Addr,
5602                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5603     Chain = Addr.getValue(1);
5604     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5605   }
5606 }
5607 
5608 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5609   EVT VT = Op.getValueType();
5610   SDLoc dl(Op);
5611 
5612   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5613     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5614       return Op;
5615     return DAG.UnrollVectorOp(Op.getNode());
5616   }
5617 
5618   const bool HasFullFP16 =
5619     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5620 
5621   EVT NewTy;
5622   const EVT OpTy = Op.getOperand(0).getValueType();
5623   if (OpTy == MVT::v4f32)
5624     NewTy = MVT::v4i32;
5625   else if (OpTy == MVT::v4f16 && HasFullFP16)
5626     NewTy = MVT::v4i16;
5627   else if (OpTy == MVT::v8f16 && HasFullFP16)
5628     NewTy = MVT::v8i16;
5629   else
5630     llvm_unreachable("Invalid type for custom lowering!");
5631 
5632   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5633     return DAG.UnrollVectorOp(Op.getNode());
5634 
5635   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5636   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5637 }
5638 
5639 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5640   EVT VT = Op.getValueType();
5641   if (VT.isVector())
5642     return LowerVectorFP_TO_INT(Op, DAG);
5643 
5644   bool IsStrict = Op->isStrictFPOpcode();
5645   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5646 
5647   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5648     RTLIB::Libcall LC;
5649     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5650         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5651       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5652                               Op.getValueType());
5653     else
5654       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5655                               Op.getValueType());
5656     SDLoc Loc(Op);
5657     MakeLibCallOptions CallOptions;
5658     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5659     SDValue Result;
5660     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5661                                           CallOptions, Loc, Chain);
5662     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5663   }
5664 
5665   // FIXME: Remove this when we have strict fp instruction selection patterns
5666   if (IsStrict) {
5667     SDLoc Loc(Op);
5668     SDValue Result =
5669         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5670                                                              : ISD::FP_TO_UINT,
5671                     Loc, Op.getValueType(), SrcVal);
5672     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5673   }
5674 
5675   return Op;
5676 }
5677 
5678 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5679   EVT VT = Op.getValueType();
5680   SDLoc dl(Op);
5681 
5682   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5683     if (VT.getVectorElementType() == MVT::f32)
5684       return Op;
5685     return DAG.UnrollVectorOp(Op.getNode());
5686   }
5687 
5688   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5689           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5690          "Invalid type for custom lowering!");
5691 
5692   const bool HasFullFP16 =
5693     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5694 
5695   EVT DestVecType;
5696   if (VT == MVT::v4f32)
5697     DestVecType = MVT::v4i32;
5698   else if (VT == MVT::v4f16 && HasFullFP16)
5699     DestVecType = MVT::v4i16;
5700   else if (VT == MVT::v8f16 && HasFullFP16)
5701     DestVecType = MVT::v8i16;
5702   else
5703     return DAG.UnrollVectorOp(Op.getNode());
5704 
5705   unsigned CastOpc;
5706   unsigned Opc;
5707   switch (Op.getOpcode()) {
5708   default: llvm_unreachable("Invalid opcode!");
5709   case ISD::SINT_TO_FP:
5710     CastOpc = ISD::SIGN_EXTEND;
5711     Opc = ISD::SINT_TO_FP;
5712     break;
5713   case ISD::UINT_TO_FP:
5714     CastOpc = ISD::ZERO_EXTEND;
5715     Opc = ISD::UINT_TO_FP;
5716     break;
5717   }
5718 
5719   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5720   return DAG.getNode(Opc, dl, VT, Op);
5721 }
5722 
5723 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5724   EVT VT = Op.getValueType();
5725   if (VT.isVector())
5726     return LowerVectorINT_TO_FP(Op, DAG);
5727   if (isUnsupportedFloatingType(VT)) {
5728     RTLIB::Libcall LC;
5729     if (Op.getOpcode() == ISD::SINT_TO_FP)
5730       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5731                               Op.getValueType());
5732     else
5733       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5734                               Op.getValueType());
5735     MakeLibCallOptions CallOptions;
5736     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5737                        CallOptions, SDLoc(Op)).first;
5738   }
5739 
5740   return Op;
5741 }
5742 
5743 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5744   // Implement fcopysign with a fabs and a conditional fneg.
5745   SDValue Tmp0 = Op.getOperand(0);
5746   SDValue Tmp1 = Op.getOperand(1);
5747   SDLoc dl(Op);
5748   EVT VT = Op.getValueType();
5749   EVT SrcVT = Tmp1.getValueType();
5750   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5751     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5752   bool UseNEON = !InGPR && Subtarget->hasNEON();
5753 
5754   if (UseNEON) {
5755     // Use VBSL to copy the sign bit.
5756     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5757     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5758                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5759     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5760     if (VT == MVT::f64)
5761       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5762                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5763                          DAG.getConstant(32, dl, MVT::i32));
5764     else /*if (VT == MVT::f32)*/
5765       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5766     if (SrcVT == MVT::f32) {
5767       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5768       if (VT == MVT::f64)
5769         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5770                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5771                            DAG.getConstant(32, dl, MVT::i32));
5772     } else if (VT == MVT::f32)
5773       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5774                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5775                          DAG.getConstant(32, dl, MVT::i32));
5776     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5777     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5778 
5779     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5780                                             dl, MVT::i32);
5781     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5782     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5783                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5784 
5785     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5786                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5787                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5788     if (VT == MVT::f32) {
5789       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5790       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5791                         DAG.getConstant(0, dl, MVT::i32));
5792     } else {
5793       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5794     }
5795 
5796     return Res;
5797   }
5798 
5799   // Bitcast operand 1 to i32.
5800   if (SrcVT == MVT::f64)
5801     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5802                        Tmp1).getValue(1);
5803   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5804 
5805   // Or in the signbit with integer operations.
5806   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5807   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5808   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5809   if (VT == MVT::f32) {
5810     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5811                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5812     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5813                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5814   }
5815 
5816   // f64: Or the high part with signbit and then combine two parts.
5817   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5818                      Tmp0);
5819   SDValue Lo = Tmp0.getValue(0);
5820   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5821   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5822   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5823 }
5824 
5825 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5826   MachineFunction &MF = DAG.getMachineFunction();
5827   MachineFrameInfo &MFI = MF.getFrameInfo();
5828   MFI.setReturnAddressIsTaken(true);
5829 
5830   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5831     return SDValue();
5832 
5833   EVT VT = Op.getValueType();
5834   SDLoc dl(Op);
5835   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5836   if (Depth) {
5837     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5838     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5839     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5840                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5841                        MachinePointerInfo());
5842   }
5843 
5844   // Return LR, which contains the return address. Mark it an implicit live-in.
5845   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5846   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5847 }
5848 
5849 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5850   const ARMBaseRegisterInfo &ARI =
5851     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5852   MachineFunction &MF = DAG.getMachineFunction();
5853   MachineFrameInfo &MFI = MF.getFrameInfo();
5854   MFI.setFrameAddressIsTaken(true);
5855 
5856   EVT VT = Op.getValueType();
5857   SDLoc dl(Op);  // FIXME probably not meaningful
5858   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5859   Register FrameReg = ARI.getFrameRegister(MF);
5860   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5861   while (Depth--)
5862     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5863                             MachinePointerInfo());
5864   return FrameAddr;
5865 }
5866 
5867 // FIXME? Maybe this could be a TableGen attribute on some registers and
5868 // this table could be generated automatically from RegInfo.
5869 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5870                                               const MachineFunction &MF) const {
5871   Register Reg = StringSwitch<unsigned>(RegName)
5872                        .Case("sp", ARM::SP)
5873                        .Default(0);
5874   if (Reg)
5875     return Reg;
5876   report_fatal_error(Twine("Invalid register name \""
5877                               + StringRef(RegName)  + "\"."));
5878 }
5879 
5880 // Result is 64 bit value so split into two 32 bit values and return as a
5881 // pair of values.
5882 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5883                                 SelectionDAG &DAG) {
5884   SDLoc DL(N);
5885 
5886   // This function is only supposed to be called for i64 type destination.
5887   assert(N->getValueType(0) == MVT::i64
5888           && "ExpandREAD_REGISTER called for non-i64 type result.");
5889 
5890   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5891                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5892                              N->getOperand(0),
5893                              N->getOperand(1));
5894 
5895   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5896                     Read.getValue(1)));
5897   Results.push_back(Read.getOperand(0));
5898 }
5899 
5900 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5901 /// When \p DstVT, the destination type of \p BC, is on the vector
5902 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5903 /// it might be possible to combine them, such that everything stays on the
5904 /// vector register bank.
5905 /// \p return The node that would replace \p BT, if the combine
5906 /// is possible.
5907 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5908                                                 SelectionDAG &DAG) {
5909   SDValue Op = BC->getOperand(0);
5910   EVT DstVT = BC->getValueType(0);
5911 
5912   // The only vector instruction that can produce a scalar (remember,
5913   // since the bitcast was about to be turned into VMOVDRR, the source
5914   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5915   // Moreover, we can do this combine only if there is one use.
5916   // Finally, if the destination type is not a vector, there is not
5917   // much point on forcing everything on the vector bank.
5918   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5919       !Op.hasOneUse())
5920     return SDValue();
5921 
5922   // If the index is not constant, we will introduce an additional
5923   // multiply that will stick.
5924   // Give up in that case.
5925   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5926   if (!Index)
5927     return SDValue();
5928   unsigned DstNumElt = DstVT.getVectorNumElements();
5929 
5930   // Compute the new index.
5931   const APInt &APIntIndex = Index->getAPIntValue();
5932   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5933   NewIndex *= APIntIndex;
5934   // Check if the new constant index fits into i32.
5935   if (NewIndex.getBitWidth() > 32)
5936     return SDValue();
5937 
5938   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5939   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5940   SDLoc dl(Op);
5941   SDValue ExtractSrc = Op.getOperand(0);
5942   EVT VecVT = EVT::getVectorVT(
5943       *DAG.getContext(), DstVT.getScalarType(),
5944       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5945   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5946   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5947                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5948 }
5949 
5950 /// ExpandBITCAST - If the target supports VFP, this function is called to
5951 /// expand a bit convert where either the source or destination type is i64 to
5952 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5953 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5954 /// vectors), since the legalizer won't know what to do with that.
5955 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5956                                          const ARMSubtarget *Subtarget) const {
5957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5958   SDLoc dl(N);
5959   SDValue Op = N->getOperand(0);
5960 
5961   // This function is only supposed to be called for i16 and i64 types, either
5962   // as the source or destination of the bit convert.
5963   EVT SrcVT = Op.getValueType();
5964   EVT DstVT = N->getValueType(0);
5965 
5966   if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
5967       (DstVT == MVT::f16 || DstVT == MVT::bf16))
5968     return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
5969                      DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5970 
5971   if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
5972       (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
5973     return DAG.getNode(
5974         ISD::TRUNCATE, SDLoc(N), DstVT,
5975         MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
5976 
5977   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5978     return SDValue();
5979 
5980   // Turn i64->f64 into VMOVDRR.
5981   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5982     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5983     // if we can combine the bitcast with its source.
5984     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5985       return Val;
5986 
5987     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5988                              DAG.getConstant(0, dl, MVT::i32));
5989     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5990                              DAG.getConstant(1, dl, MVT::i32));
5991     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5992                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5993   }
5994 
5995   // Turn f64->i64 into VMOVRRD.
5996   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5997     SDValue Cvt;
5998     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5999         SrcVT.getVectorNumElements() > 1)
6000       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6001                         DAG.getVTList(MVT::i32, MVT::i32),
6002                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
6003     else
6004       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
6005                         DAG.getVTList(MVT::i32, MVT::i32), Op);
6006     // Merge the pieces into a single i64 value.
6007     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6008   }
6009 
6010   return SDValue();
6011 }
6012 
6013 /// getZeroVector - Returns a vector of specified type with all zero elements.
6014 /// Zero vectors are used to represent vector negation and in those cases
6015 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
6016 /// not support i64 elements, so sometimes the zero vectors will need to be
6017 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
6018 /// zero vector.
6019 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6020   assert(VT.isVector() && "Expected a vector type");
6021   // The canonical modified immediate encoding of a zero vector is....0!
6022   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6023   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6024   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6025   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6026 }
6027 
6028 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6029 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
6030 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6031                                                 SelectionDAG &DAG) const {
6032   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6033   EVT VT = Op.getValueType();
6034   unsigned VTBits = VT.getSizeInBits();
6035   SDLoc dl(Op);
6036   SDValue ShOpLo = Op.getOperand(0);
6037   SDValue ShOpHi = Op.getOperand(1);
6038   SDValue ShAmt  = Op.getOperand(2);
6039   SDValue ARMcc;
6040   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6041   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6042 
6043   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6044 
6045   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6046                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6047   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6048   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6049                                    DAG.getConstant(VTBits, dl, MVT::i32));
6050   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6051   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6052   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6053   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6054                             ISD::SETGE, ARMcc, DAG, dl);
6055   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6056                            ARMcc, CCR, CmpLo);
6057 
6058   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6059   SDValue HiBigShift = Opc == ISD::SRA
6060                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
6061                                          DAG.getConstant(VTBits - 1, dl, VT))
6062                            : DAG.getConstant(0, dl, VT);
6063   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6064                             ISD::SETGE, ARMcc, DAG, dl);
6065   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6066                            ARMcc, CCR, CmpHi);
6067 
6068   SDValue Ops[2] = { Lo, Hi };
6069   return DAG.getMergeValues(Ops, dl);
6070 }
6071 
6072 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6073 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
6074 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6075                                                SelectionDAG &DAG) const {
6076   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6077   EVT VT = Op.getValueType();
6078   unsigned VTBits = VT.getSizeInBits();
6079   SDLoc dl(Op);
6080   SDValue ShOpLo = Op.getOperand(0);
6081   SDValue ShOpHi = Op.getOperand(1);
6082   SDValue ShAmt  = Op.getOperand(2);
6083   SDValue ARMcc;
6084   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6085 
6086   assert(Op.getOpcode() == ISD::SHL_PARTS);
6087   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6088                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6089   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6090   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6091   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6092 
6093   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6094                                    DAG.getConstant(VTBits, dl, MVT::i32));
6095   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6096   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6097                             ISD::SETGE, ARMcc, DAG, dl);
6098   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6099                            ARMcc, CCR, CmpHi);
6100 
6101   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6102                           ISD::SETGE, ARMcc, DAG, dl);
6103   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6104   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6105                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6106 
6107   SDValue Ops[2] = { Lo, Hi };
6108   return DAG.getMergeValues(Ops, dl);
6109 }
6110 
6111 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6112                                             SelectionDAG &DAG) const {
6113   // The rounding mode is in bits 23:22 of the FPSCR.
6114   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6115   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6116   // so that the shift + and get folded into a bitfield extract.
6117   SDLoc dl(Op);
6118   SDValue Chain = Op.getOperand(0);
6119   SDValue Ops[] = {Chain,
6120                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6121 
6122   SDValue FPSCR =
6123       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6124   Chain = FPSCR.getValue(1);
6125   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6126                                   DAG.getConstant(1U << 22, dl, MVT::i32));
6127   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6128                               DAG.getConstant(22, dl, MVT::i32));
6129   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6130                             DAG.getConstant(3, dl, MVT::i32));
6131   return DAG.getMergeValues({And, Chain}, dl);
6132 }
6133 
6134 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6135                          const ARMSubtarget *ST) {
6136   SDLoc dl(N);
6137   EVT VT = N->getValueType(0);
6138   if (VT.isVector() && ST->hasNEON()) {
6139 
6140     // Compute the least significant set bit: LSB = X & -X
6141     SDValue X = N->getOperand(0);
6142     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6143     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6144 
6145     EVT ElemTy = VT.getVectorElementType();
6146 
6147     if (ElemTy == MVT::i8) {
6148       // Compute with: cttz(x) = ctpop(lsb - 1)
6149       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6150                                 DAG.getTargetConstant(1, dl, ElemTy));
6151       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6152       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6153     }
6154 
6155     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6156         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6157       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6158       unsigned NumBits = ElemTy.getSizeInBits();
6159       SDValue WidthMinus1 =
6160           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6161                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6162       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6163       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6164     }
6165 
6166     // Compute with: cttz(x) = ctpop(lsb - 1)
6167 
6168     // Compute LSB - 1.
6169     SDValue Bits;
6170     if (ElemTy == MVT::i64) {
6171       // Load constant 0xffff'ffff'ffff'ffff to register.
6172       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6173                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6174       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6175     } else {
6176       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6177                                 DAG.getTargetConstant(1, dl, ElemTy));
6178       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6179     }
6180     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6181   }
6182 
6183   if (!ST->hasV6T2Ops())
6184     return SDValue();
6185 
6186   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6187   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6188 }
6189 
6190 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6191                           const ARMSubtarget *ST) {
6192   EVT VT = N->getValueType(0);
6193   SDLoc DL(N);
6194 
6195   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6196   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6197           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6198          "Unexpected type for custom ctpop lowering");
6199 
6200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6201   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6202   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6203   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6204 
6205   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6206   unsigned EltSize = 8;
6207   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6208   while (EltSize != VT.getScalarSizeInBits()) {
6209     SmallVector<SDValue, 8> Ops;
6210     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6211                                   TLI.getPointerTy(DAG.getDataLayout())));
6212     Ops.push_back(Res);
6213 
6214     EltSize *= 2;
6215     NumElts /= 2;
6216     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6217     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6218   }
6219 
6220   return Res;
6221 }
6222 
6223 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6224 /// operand of a vector shift operation, where all the elements of the
6225 /// build_vector must have the same constant integer value.
6226 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6227   // Ignore bit_converts.
6228   while (Op.getOpcode() == ISD::BITCAST)
6229     Op = Op.getOperand(0);
6230   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6231   APInt SplatBits, SplatUndef;
6232   unsigned SplatBitSize;
6233   bool HasAnyUndefs;
6234   if (!BVN ||
6235       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6236                             ElementBits) ||
6237       SplatBitSize > ElementBits)
6238     return false;
6239   Cnt = SplatBits.getSExtValue();
6240   return true;
6241 }
6242 
6243 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6244 /// operand of a vector shift left operation.  That value must be in the range:
6245 ///   0 <= Value < ElementBits for a left shift; or
6246 ///   0 <= Value <= ElementBits for a long left shift.
6247 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6248   assert(VT.isVector() && "vector shift count is not a vector type");
6249   int64_t ElementBits = VT.getScalarSizeInBits();
6250   if (!getVShiftImm(Op, ElementBits, Cnt))
6251     return false;
6252   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6253 }
6254 
6255 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6256 /// operand of a vector shift right operation.  For a shift opcode, the value
6257 /// is positive, but for an intrinsic the value count must be negative. The
6258 /// absolute value must be in the range:
6259 ///   1 <= |Value| <= ElementBits for a right shift; or
6260 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6261 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6262                          int64_t &Cnt) {
6263   assert(VT.isVector() && "vector shift count is not a vector type");
6264   int64_t ElementBits = VT.getScalarSizeInBits();
6265   if (!getVShiftImm(Op, ElementBits, Cnt))
6266     return false;
6267   if (!isIntrinsic)
6268     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6269   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6270     Cnt = -Cnt;
6271     return true;
6272   }
6273   return false;
6274 }
6275 
6276 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6277                           const ARMSubtarget *ST) {
6278   EVT VT = N->getValueType(0);
6279   SDLoc dl(N);
6280   int64_t Cnt;
6281 
6282   if (!VT.isVector())
6283     return SDValue();
6284 
6285   // We essentially have two forms here. Shift by an immediate and shift by a
6286   // vector register (there are also shift by a gpr, but that is just handled
6287   // with a tablegen pattern). We cannot easily match shift by an immediate in
6288   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6289   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6290   // signed or unsigned, and a negative shift indicates a shift right).
6291   if (N->getOpcode() == ISD::SHL) {
6292     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6293       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6294                          DAG.getConstant(Cnt, dl, MVT::i32));
6295     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6296                        N->getOperand(1));
6297   }
6298 
6299   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6300          "unexpected vector shift opcode");
6301 
6302   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6303     unsigned VShiftOpc =
6304         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6305     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6306                        DAG.getConstant(Cnt, dl, MVT::i32));
6307   }
6308 
6309   // Other right shifts we don't have operations for (we use a shift left by a
6310   // negative number).
6311   EVT ShiftVT = N->getOperand(1).getValueType();
6312   SDValue NegatedCount = DAG.getNode(
6313       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6314   unsigned VShiftOpc =
6315       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6316   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6317 }
6318 
6319 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6320                                 const ARMSubtarget *ST) {
6321   EVT VT = N->getValueType(0);
6322   SDLoc dl(N);
6323 
6324   // We can get here for a node like i32 = ISD::SHL i32, i64
6325   if (VT != MVT::i64)
6326     return SDValue();
6327 
6328   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6329           N->getOpcode() == ISD::SHL) &&
6330          "Unknown shift to lower!");
6331 
6332   unsigned ShOpc = N->getOpcode();
6333   if (ST->hasMVEIntegerOps()) {
6334     SDValue ShAmt = N->getOperand(1);
6335     unsigned ShPartsOpc = ARMISD::LSLL;
6336     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6337 
6338     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6339     // then do the default optimisation
6340     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6341         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6342       return SDValue();
6343 
6344     // Extract the lower 32 bits of the shift amount if it's not an i32
6345     if (ShAmt->getValueType(0) != MVT::i32)
6346       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6347 
6348     if (ShOpc == ISD::SRL) {
6349       if (!Con)
6350         // There is no t2LSRLr instruction so negate and perform an lsll if the
6351         // shift amount is in a register, emulating a right shift.
6352         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6353                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6354       else
6355         // Else generate an lsrl on the immediate shift amount
6356         ShPartsOpc = ARMISD::LSRL;
6357     } else if (ShOpc == ISD::SRA)
6358       ShPartsOpc = ARMISD::ASRL;
6359 
6360     // Lower 32 bits of the destination/source
6361     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6362                              DAG.getConstant(0, dl, MVT::i32));
6363     // Upper 32 bits of the destination/source
6364     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6365                              DAG.getConstant(1, dl, MVT::i32));
6366 
6367     // Generate the shift operation as computed above
6368     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6369                      ShAmt);
6370     // The upper 32 bits come from the second return value of lsll
6371     Hi = SDValue(Lo.getNode(), 1);
6372     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6373   }
6374 
6375   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6376   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6377     return SDValue();
6378 
6379   // If we are in thumb mode, we don't have RRX.
6380   if (ST->isThumb1Only())
6381     return SDValue();
6382 
6383   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6384   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6385                            DAG.getConstant(0, dl, MVT::i32));
6386   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6387                            DAG.getConstant(1, dl, MVT::i32));
6388 
6389   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6390   // captures the result into a carry flag.
6391   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6392   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6393 
6394   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6395   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6396 
6397   // Merge the pieces into a single i64 value.
6398  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6399 }
6400 
6401 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6402                            const ARMSubtarget *ST) {
6403   bool Invert = false;
6404   bool Swap = false;
6405   unsigned Opc = ARMCC::AL;
6406 
6407   SDValue Op0 = Op.getOperand(0);
6408   SDValue Op1 = Op.getOperand(1);
6409   SDValue CC = Op.getOperand(2);
6410   EVT VT = Op.getValueType();
6411   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6412   SDLoc dl(Op);
6413 
6414   EVT CmpVT;
6415   if (ST->hasNEON())
6416     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6417   else {
6418     assert(ST->hasMVEIntegerOps() &&
6419            "No hardware support for integer vector comparison!");
6420 
6421     if (Op.getValueType().getVectorElementType() != MVT::i1)
6422       return SDValue();
6423 
6424     // Make sure we expand floating point setcc to scalar if we do not have
6425     // mve.fp, so that we can handle them from there.
6426     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6427       return SDValue();
6428 
6429     CmpVT = VT;
6430   }
6431 
6432   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6433       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6434     // Special-case integer 64-bit equality comparisons. They aren't legal,
6435     // but they can be lowered with a few vector instructions.
6436     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6437     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6438     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6439     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6440     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6441                               DAG.getCondCode(ISD::SETEQ));
6442     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6443     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6444     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6445     if (SetCCOpcode == ISD::SETNE)
6446       Merged = DAG.getNOT(dl, Merged, CmpVT);
6447     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6448     return Merged;
6449   }
6450 
6451   if (CmpVT.getVectorElementType() == MVT::i64)
6452     // 64-bit comparisons are not legal in general.
6453     return SDValue();
6454 
6455   if (Op1.getValueType().isFloatingPoint()) {
6456     switch (SetCCOpcode) {
6457     default: llvm_unreachable("Illegal FP comparison");
6458     case ISD::SETUNE:
6459     case ISD::SETNE:
6460       if (ST->hasMVEFloatOps()) {
6461         Opc = ARMCC::NE; break;
6462       } else {
6463         Invert = true; LLVM_FALLTHROUGH;
6464       }
6465     case ISD::SETOEQ:
6466     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6467     case ISD::SETOLT:
6468     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6469     case ISD::SETOGT:
6470     case ISD::SETGT:  Opc = ARMCC::GT; break;
6471     case ISD::SETOLE:
6472     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6473     case ISD::SETOGE:
6474     case ISD::SETGE: Opc = ARMCC::GE; break;
6475     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6476     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6477     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6478     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6479     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6480     case ISD::SETONE: {
6481       // Expand this to (OLT | OGT).
6482       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6483                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6484       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6485                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6486       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6487       if (Invert)
6488         Result = DAG.getNOT(dl, Result, VT);
6489       return Result;
6490     }
6491     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6492     case ISD::SETO: {
6493       // Expand this to (OLT | OGE).
6494       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6495                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6496       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6497                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6498       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6499       if (Invert)
6500         Result = DAG.getNOT(dl, Result, VT);
6501       return Result;
6502     }
6503     }
6504   } else {
6505     // Integer comparisons.
6506     switch (SetCCOpcode) {
6507     default: llvm_unreachable("Illegal integer comparison");
6508     case ISD::SETNE:
6509       if (ST->hasMVEIntegerOps()) {
6510         Opc = ARMCC::NE; break;
6511       } else {
6512         Invert = true; LLVM_FALLTHROUGH;
6513       }
6514     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6515     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6516     case ISD::SETGT:  Opc = ARMCC::GT; break;
6517     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6518     case ISD::SETGE:  Opc = ARMCC::GE; break;
6519     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6520     case ISD::SETUGT: Opc = ARMCC::HI; break;
6521     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6522     case ISD::SETUGE: Opc = ARMCC::HS; break;
6523     }
6524 
6525     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6526     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6527       SDValue AndOp;
6528       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6529         AndOp = Op0;
6530       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6531         AndOp = Op1;
6532 
6533       // Ignore bitconvert.
6534       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6535         AndOp = AndOp.getOperand(0);
6536 
6537       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6538         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6539         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6540         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6541         if (!Invert)
6542           Result = DAG.getNOT(dl, Result, VT);
6543         return Result;
6544       }
6545     }
6546   }
6547 
6548   if (Swap)
6549     std::swap(Op0, Op1);
6550 
6551   // If one of the operands is a constant vector zero, attempt to fold the
6552   // comparison to a specialized compare-against-zero form.
6553   SDValue SingleOp;
6554   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6555     SingleOp = Op0;
6556   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6557     if (Opc == ARMCC::GE)
6558       Opc = ARMCC::LE;
6559     else if (Opc == ARMCC::GT)
6560       Opc = ARMCC::LT;
6561     SingleOp = Op1;
6562   }
6563 
6564   SDValue Result;
6565   if (SingleOp.getNode()) {
6566     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6567                          DAG.getConstant(Opc, dl, MVT::i32));
6568   } else {
6569     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6570                          DAG.getConstant(Opc, dl, MVT::i32));
6571   }
6572 
6573   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6574 
6575   if (Invert)
6576     Result = DAG.getNOT(dl, Result, VT);
6577 
6578   return Result;
6579 }
6580 
6581 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6582   SDValue LHS = Op.getOperand(0);
6583   SDValue RHS = Op.getOperand(1);
6584   SDValue Carry = Op.getOperand(2);
6585   SDValue Cond = Op.getOperand(3);
6586   SDLoc DL(Op);
6587 
6588   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6589 
6590   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6591   // have to invert the carry first.
6592   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6593                       DAG.getConstant(1, DL, MVT::i32), Carry);
6594   // This converts the boolean value carry into the carry flag.
6595   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6596 
6597   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6598   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6599 
6600   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6601   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6602   SDValue ARMcc = DAG.getConstant(
6603       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6604   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6605   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6606                                    Cmp.getValue(1), SDValue());
6607   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6608                      CCR, Chain.getValue(1));
6609 }
6610 
6611 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6612 /// valid vector constant for a NEON or MVE instruction with a "modified
6613 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6614 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6615                                  unsigned SplatBitSize, SelectionDAG &DAG,
6616                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
6617                                  VMOVModImmType type) {
6618   unsigned OpCmode, Imm;
6619   bool is128Bits = VectorVT.is128BitVector();
6620 
6621   // SplatBitSize is set to the smallest size that splats the vector, so a
6622   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6623   // immediate instructions others than VMOV do not support the 8-bit encoding
6624   // of a zero vector, and the default encoding of zero is supposed to be the
6625   // 32-bit version.
6626   if (SplatBits == 0)
6627     SplatBitSize = 32;
6628 
6629   switch (SplatBitSize) {
6630   case 8:
6631     if (type != VMOVModImm)
6632       return SDValue();
6633     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6634     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6635     OpCmode = 0xe;
6636     Imm = SplatBits;
6637     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6638     break;
6639 
6640   case 16:
6641     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6642     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6643     if ((SplatBits & ~0xff) == 0) {
6644       // Value = 0x00nn: Op=x, Cmode=100x.
6645       OpCmode = 0x8;
6646       Imm = SplatBits;
6647       break;
6648     }
6649     if ((SplatBits & ~0xff00) == 0) {
6650       // Value = 0xnn00: Op=x, Cmode=101x.
6651       OpCmode = 0xa;
6652       Imm = SplatBits >> 8;
6653       break;
6654     }
6655     return SDValue();
6656 
6657   case 32:
6658     // NEON's 32-bit VMOV supports splat values where:
6659     // * only one byte is nonzero, or
6660     // * the least significant byte is 0xff and the second byte is nonzero, or
6661     // * the least significant 2 bytes are 0xff and the third is nonzero.
6662     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6663     if ((SplatBits & ~0xff) == 0) {
6664       // Value = 0x000000nn: Op=x, Cmode=000x.
6665       OpCmode = 0;
6666       Imm = SplatBits;
6667       break;
6668     }
6669     if ((SplatBits & ~0xff00) == 0) {
6670       // Value = 0x0000nn00: Op=x, Cmode=001x.
6671       OpCmode = 0x2;
6672       Imm = SplatBits >> 8;
6673       break;
6674     }
6675     if ((SplatBits & ~0xff0000) == 0) {
6676       // Value = 0x00nn0000: Op=x, Cmode=010x.
6677       OpCmode = 0x4;
6678       Imm = SplatBits >> 16;
6679       break;
6680     }
6681     if ((SplatBits & ~0xff000000) == 0) {
6682       // Value = 0xnn000000: Op=x, Cmode=011x.
6683       OpCmode = 0x6;
6684       Imm = SplatBits >> 24;
6685       break;
6686     }
6687 
6688     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6689     if (type == OtherModImm) return SDValue();
6690 
6691     if ((SplatBits & ~0xffff) == 0 &&
6692         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6693       // Value = 0x0000nnff: Op=x, Cmode=1100.
6694       OpCmode = 0xc;
6695       Imm = SplatBits >> 8;
6696       break;
6697     }
6698 
6699     // cmode == 0b1101 is not supported for MVE VMVN
6700     if (type == MVEVMVNModImm)
6701       return SDValue();
6702 
6703     if ((SplatBits & ~0xffffff) == 0 &&
6704         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6705       // Value = 0x00nnffff: Op=x, Cmode=1101.
6706       OpCmode = 0xd;
6707       Imm = SplatBits >> 16;
6708       break;
6709     }
6710 
6711     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6712     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6713     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6714     // and fall through here to test for a valid 64-bit splat.  But, then the
6715     // caller would also need to check and handle the change in size.
6716     return SDValue();
6717 
6718   case 64: {
6719     if (type != VMOVModImm)
6720       return SDValue();
6721     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6722     uint64_t BitMask = 0xff;
6723     uint64_t Val = 0;
6724     unsigned ImmMask = 1;
6725     Imm = 0;
6726     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6727       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6728         Val |= BitMask;
6729         Imm |= ImmMask;
6730       } else if ((SplatBits & BitMask) != 0) {
6731         return SDValue();
6732       }
6733       BitMask <<= 8;
6734       ImmMask <<= 1;
6735     }
6736 
6737     if (DAG.getDataLayout().isBigEndian()) {
6738       // Reverse the order of elements within the vector.
6739       unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6740       unsigned Mask = (1 << BytesPerElem) - 1;
6741       unsigned NumElems = 8 / BytesPerElem;
6742       unsigned NewImm = 0;
6743       for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6744         unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6745         NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6746       }
6747       Imm = NewImm;
6748     }
6749 
6750     // Op=1, Cmode=1110.
6751     OpCmode = 0x1e;
6752     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6753     break;
6754   }
6755 
6756   default:
6757     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6758   }
6759 
6760   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6761   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6762 }
6763 
6764 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6765                                            const ARMSubtarget *ST) const {
6766   EVT VT = Op.getValueType();
6767   bool IsDouble = (VT == MVT::f64);
6768   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6769   const APFloat &FPVal = CFP->getValueAPF();
6770 
6771   // Prevent floating-point constants from using literal loads
6772   // when execute-only is enabled.
6773   if (ST->genExecuteOnly()) {
6774     // If we can represent the constant as an immediate, don't lower it
6775     if (isFPImmLegal(FPVal, VT))
6776       return Op;
6777     // Otherwise, construct as integer, and move to float register
6778     APInt INTVal = FPVal.bitcastToAPInt();
6779     SDLoc DL(CFP);
6780     switch (VT.getSimpleVT().SimpleTy) {
6781       default:
6782         llvm_unreachable("Unknown floating point type!");
6783         break;
6784       case MVT::f64: {
6785         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6786         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6787         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6788       }
6789       case MVT::f32:
6790           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6791               DAG.getConstant(INTVal, DL, MVT::i32));
6792     }
6793   }
6794 
6795   if (!ST->hasVFP3Base())
6796     return SDValue();
6797 
6798   // Use the default (constant pool) lowering for double constants when we have
6799   // an SP-only FPU
6800   if (IsDouble && !Subtarget->hasFP64())
6801     return SDValue();
6802 
6803   // Try splatting with a VMOV.f32...
6804   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6805 
6806   if (ImmVal != -1) {
6807     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6808       // We have code in place to select a valid ConstantFP already, no need to
6809       // do any mangling.
6810       return Op;
6811     }
6812 
6813     // It's a float and we are trying to use NEON operations where
6814     // possible. Lower it to a splat followed by an extract.
6815     SDLoc DL(Op);
6816     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6817     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6818                                       NewVal);
6819     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6820                        DAG.getConstant(0, DL, MVT::i32));
6821   }
6822 
6823   // The rest of our options are NEON only, make sure that's allowed before
6824   // proceeding..
6825   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6826     return SDValue();
6827 
6828   EVT VMovVT;
6829   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6830 
6831   // It wouldn't really be worth bothering for doubles except for one very
6832   // important value, which does happen to match: 0.0. So make sure we don't do
6833   // anything stupid.
6834   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6835     return SDValue();
6836 
6837   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6838   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6839                                      VMovVT, VT, VMOVModImm);
6840   if (NewVal != SDValue()) {
6841     SDLoc DL(Op);
6842     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6843                                       NewVal);
6844     if (IsDouble)
6845       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6846 
6847     // It's a float: cast and extract a vector element.
6848     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6849                                        VecConstant);
6850     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6851                        DAG.getConstant(0, DL, MVT::i32));
6852   }
6853 
6854   // Finally, try a VMVN.i32
6855   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6856                              VT, VMVNModImm);
6857   if (NewVal != SDValue()) {
6858     SDLoc DL(Op);
6859     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6860 
6861     if (IsDouble)
6862       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6863 
6864     // It's a float: cast and extract a vector element.
6865     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6866                                        VecConstant);
6867     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6868                        DAG.getConstant(0, DL, MVT::i32));
6869   }
6870 
6871   return SDValue();
6872 }
6873 
6874 // check if an VEXT instruction can handle the shuffle mask when the
6875 // vector sources of the shuffle are the same.
6876 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6877   unsigned NumElts = VT.getVectorNumElements();
6878 
6879   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6880   if (M[0] < 0)
6881     return false;
6882 
6883   Imm = M[0];
6884 
6885   // If this is a VEXT shuffle, the immediate value is the index of the first
6886   // element.  The other shuffle indices must be the successive elements after
6887   // the first one.
6888   unsigned ExpectedElt = Imm;
6889   for (unsigned i = 1; i < NumElts; ++i) {
6890     // Increment the expected index.  If it wraps around, just follow it
6891     // back to index zero and keep going.
6892     ++ExpectedElt;
6893     if (ExpectedElt == NumElts)
6894       ExpectedElt = 0;
6895 
6896     if (M[i] < 0) continue; // ignore UNDEF indices
6897     if (ExpectedElt != static_cast<unsigned>(M[i]))
6898       return false;
6899   }
6900 
6901   return true;
6902 }
6903 
6904 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6905                        bool &ReverseVEXT, unsigned &Imm) {
6906   unsigned NumElts = VT.getVectorNumElements();
6907   ReverseVEXT = false;
6908 
6909   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6910   if (M[0] < 0)
6911     return false;
6912 
6913   Imm = M[0];
6914 
6915   // If this is a VEXT shuffle, the immediate value is the index of the first
6916   // element.  The other shuffle indices must be the successive elements after
6917   // the first one.
6918   unsigned ExpectedElt = Imm;
6919   for (unsigned i = 1; i < NumElts; ++i) {
6920     // Increment the expected index.  If it wraps around, it may still be
6921     // a VEXT but the source vectors must be swapped.
6922     ExpectedElt += 1;
6923     if (ExpectedElt == NumElts * 2) {
6924       ExpectedElt = 0;
6925       ReverseVEXT = true;
6926     }
6927 
6928     if (M[i] < 0) continue; // ignore UNDEF indices
6929     if (ExpectedElt != static_cast<unsigned>(M[i]))
6930       return false;
6931   }
6932 
6933   // Adjust the index value if the source operands will be swapped.
6934   if (ReverseVEXT)
6935     Imm -= NumElts;
6936 
6937   return true;
6938 }
6939 
6940 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6941 /// instruction with the specified blocksize.  (The order of the elements
6942 /// within each block of the vector is reversed.)
6943 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6944   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6945          "Only possible block sizes for VREV are: 16, 32, 64");
6946 
6947   unsigned EltSz = VT.getScalarSizeInBits();
6948   if (EltSz == 64)
6949     return false;
6950 
6951   unsigned NumElts = VT.getVectorNumElements();
6952   unsigned BlockElts = M[0] + 1;
6953   // If the first shuffle index is UNDEF, be optimistic.
6954   if (M[0] < 0)
6955     BlockElts = BlockSize / EltSz;
6956 
6957   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6958     return false;
6959 
6960   for (unsigned i = 0; i < NumElts; ++i) {
6961     if (M[i] < 0) continue; // ignore UNDEF indices
6962     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6963       return false;
6964   }
6965 
6966   return true;
6967 }
6968 
6969 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6970   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6971   // range, then 0 is placed into the resulting vector. So pretty much any mask
6972   // of 8 elements can work here.
6973   return VT == MVT::v8i8 && M.size() == 8;
6974 }
6975 
6976 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6977                                unsigned Index) {
6978   if (Mask.size() == Elements * 2)
6979     return Index / Elements;
6980   return Mask[Index] == 0 ? 0 : 1;
6981 }
6982 
6983 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6984 // checking that pairs of elements in the shuffle mask represent the same index
6985 // in each vector, incrementing the expected index by 2 at each step.
6986 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6987 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6988 //  v2={e,f,g,h}
6989 // WhichResult gives the offset for each element in the mask based on which
6990 // of the two results it belongs to.
6991 //
6992 // The transpose can be represented either as:
6993 // result1 = shufflevector v1, v2, result1_shuffle_mask
6994 // result2 = shufflevector v1, v2, result2_shuffle_mask
6995 // where v1/v2 and the shuffle masks have the same number of elements
6996 // (here WhichResult (see below) indicates which result is being checked)
6997 //
6998 // or as:
6999 // results = shufflevector v1, v2, shuffle_mask
7000 // where both results are returned in one vector and the shuffle mask has twice
7001 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
7002 // want to check the low half and high half of the shuffle mask as if it were
7003 // the other case
7004 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7005   unsigned EltSz = VT.getScalarSizeInBits();
7006   if (EltSz == 64)
7007     return false;
7008 
7009   unsigned NumElts = VT.getVectorNumElements();
7010   if (M.size() != NumElts && M.size() != NumElts*2)
7011     return false;
7012 
7013   // If the mask is twice as long as the input vector then we need to check the
7014   // upper and lower parts of the mask with a matching value for WhichResult
7015   // FIXME: A mask with only even values will be rejected in case the first
7016   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7017   // M[0] is used to determine WhichResult
7018   for (unsigned i = 0; i < M.size(); i += NumElts) {
7019     WhichResult = SelectPairHalf(NumElts, M, i);
7020     for (unsigned j = 0; j < NumElts; j += 2) {
7021       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7022           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7023         return false;
7024     }
7025   }
7026 
7027   if (M.size() == NumElts*2)
7028     WhichResult = 0;
7029 
7030   return true;
7031 }
7032 
7033 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7034 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7035 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7036 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7037   unsigned EltSz = VT.getScalarSizeInBits();
7038   if (EltSz == 64)
7039     return false;
7040 
7041   unsigned NumElts = VT.getVectorNumElements();
7042   if (M.size() != NumElts && M.size() != NumElts*2)
7043     return false;
7044 
7045   for (unsigned i = 0; i < M.size(); i += NumElts) {
7046     WhichResult = SelectPairHalf(NumElts, M, i);
7047     for (unsigned j = 0; j < NumElts; j += 2) {
7048       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7049           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7050         return false;
7051     }
7052   }
7053 
7054   if (M.size() == NumElts*2)
7055     WhichResult = 0;
7056 
7057   return true;
7058 }
7059 
7060 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7061 // that the mask elements are either all even and in steps of size 2 or all odd
7062 // and in steps of size 2.
7063 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7064 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7065 //  v2={e,f,g,h}
7066 // Requires similar checks to that of isVTRNMask with
7067 // respect the how results are returned.
7068 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7069   unsigned EltSz = VT.getScalarSizeInBits();
7070   if (EltSz == 64)
7071     return false;
7072 
7073   unsigned NumElts = VT.getVectorNumElements();
7074   if (M.size() != NumElts && M.size() != NumElts*2)
7075     return false;
7076 
7077   for (unsigned i = 0; i < M.size(); i += NumElts) {
7078     WhichResult = SelectPairHalf(NumElts, M, i);
7079     for (unsigned j = 0; j < NumElts; ++j) {
7080       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7081         return false;
7082     }
7083   }
7084 
7085   if (M.size() == NumElts*2)
7086     WhichResult = 0;
7087 
7088   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7089   if (VT.is64BitVector() && EltSz == 32)
7090     return false;
7091 
7092   return true;
7093 }
7094 
7095 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7096 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7097 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7098 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7099   unsigned EltSz = VT.getScalarSizeInBits();
7100   if (EltSz == 64)
7101     return false;
7102 
7103   unsigned NumElts = VT.getVectorNumElements();
7104   if (M.size() != NumElts && M.size() != NumElts*2)
7105     return false;
7106 
7107   unsigned Half = NumElts / 2;
7108   for (unsigned i = 0; i < M.size(); i += NumElts) {
7109     WhichResult = SelectPairHalf(NumElts, M, i);
7110     for (unsigned j = 0; j < NumElts; j += Half) {
7111       unsigned Idx = WhichResult;
7112       for (unsigned k = 0; k < Half; ++k) {
7113         int MIdx = M[i + j + k];
7114         if (MIdx >= 0 && (unsigned) MIdx != Idx)
7115           return false;
7116         Idx += 2;
7117       }
7118     }
7119   }
7120 
7121   if (M.size() == NumElts*2)
7122     WhichResult = 0;
7123 
7124   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7125   if (VT.is64BitVector() && EltSz == 32)
7126     return false;
7127 
7128   return true;
7129 }
7130 
7131 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7132 // that pairs of elements of the shufflemask represent the same index in each
7133 // vector incrementing sequentially through the vectors.
7134 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7135 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7136 //  v2={e,f,g,h}
7137 // Requires similar checks to that of isVTRNMask with respect the how results
7138 // are returned.
7139 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7140   unsigned EltSz = VT.getScalarSizeInBits();
7141   if (EltSz == 64)
7142     return false;
7143 
7144   unsigned NumElts = VT.getVectorNumElements();
7145   if (M.size() != NumElts && M.size() != NumElts*2)
7146     return false;
7147 
7148   for (unsigned i = 0; i < M.size(); i += NumElts) {
7149     WhichResult = SelectPairHalf(NumElts, M, i);
7150     unsigned Idx = WhichResult * NumElts / 2;
7151     for (unsigned j = 0; j < NumElts; j += 2) {
7152       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7153           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7154         return false;
7155       Idx += 1;
7156     }
7157   }
7158 
7159   if (M.size() == NumElts*2)
7160     WhichResult = 0;
7161 
7162   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7163   if (VT.is64BitVector() && EltSz == 32)
7164     return false;
7165 
7166   return true;
7167 }
7168 
7169 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7170 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7171 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7172 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7173   unsigned EltSz = VT.getScalarSizeInBits();
7174   if (EltSz == 64)
7175     return false;
7176 
7177   unsigned NumElts = VT.getVectorNumElements();
7178   if (M.size() != NumElts && M.size() != NumElts*2)
7179     return false;
7180 
7181   for (unsigned i = 0; i < M.size(); i += NumElts) {
7182     WhichResult = SelectPairHalf(NumElts, M, i);
7183     unsigned Idx = WhichResult * NumElts / 2;
7184     for (unsigned j = 0; j < NumElts; j += 2) {
7185       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7186           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7187         return false;
7188       Idx += 1;
7189     }
7190   }
7191 
7192   if (M.size() == NumElts*2)
7193     WhichResult = 0;
7194 
7195   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7196   if (VT.is64BitVector() && EltSz == 32)
7197     return false;
7198 
7199   return true;
7200 }
7201 
7202 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7203 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7204 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7205                                            unsigned &WhichResult,
7206                                            bool &isV_UNDEF) {
7207   isV_UNDEF = false;
7208   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7209     return ARMISD::VTRN;
7210   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7211     return ARMISD::VUZP;
7212   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7213     return ARMISD::VZIP;
7214 
7215   isV_UNDEF = true;
7216   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7217     return ARMISD::VTRN;
7218   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7219     return ARMISD::VUZP;
7220   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7221     return ARMISD::VZIP;
7222 
7223   return 0;
7224 }
7225 
7226 /// \return true if this is a reverse operation on an vector.
7227 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7228   unsigned NumElts = VT.getVectorNumElements();
7229   // Make sure the mask has the right size.
7230   if (NumElts != M.size())
7231       return false;
7232 
7233   // Look for <15, ..., 3, -1, 1, 0>.
7234   for (unsigned i = 0; i != NumElts; ++i)
7235     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7236       return false;
7237 
7238   return true;
7239 }
7240 
7241 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7242   unsigned NumElts = VT.getVectorNumElements();
7243   // Make sure the mask has the right size.
7244   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7245       return false;
7246 
7247   // If Top
7248   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7249   //   This inserts Input2 into Input1
7250   // else if not Top
7251   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7252   //   This inserts Input1 into Input2
7253   unsigned Offset = Top ? 0 : 1;
7254   for (unsigned i = 0; i < NumElts; i+=2) {
7255     if (M[i] >= 0 && M[i] != (int)i)
7256       return false;
7257     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7258       return false;
7259   }
7260 
7261   return true;
7262 }
7263 
7264 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7265 // from a pair of inputs. For example:
7266 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7267 //             FP_ROUND(EXTRACT_ELT(Y, 0),
7268 //             FP_ROUND(EXTRACT_ELT(X, 1),
7269 //             FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7270 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7271                                          const ARMSubtarget *ST) {
7272   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7273   if (!ST->hasMVEFloatOps())
7274     return SDValue();
7275 
7276   SDLoc dl(BV);
7277   EVT VT = BV.getValueType();
7278   if (VT != MVT::v8f16)
7279     return SDValue();
7280 
7281   // We are looking for a buildvector of fptrunc elements, where all the
7282   // elements are interleavingly extracted from two sources. Check the first two
7283   // items are valid enough and extract some info from them (they are checked
7284   // properly in the loop below).
7285   if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7286       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7287       BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7288     return SDValue();
7289   if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7290       BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7291       BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7292     return SDValue();
7293   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7294   SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7295   if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7296     return SDValue();
7297 
7298   // Check all the values in the BuildVector line up with our expectations.
7299   for (unsigned i = 1; i < 4; i++) {
7300     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7301       return Trunc.getOpcode() == ISD::FP_ROUND &&
7302              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7303              Trunc.getOperand(0).getOperand(0) == Op &&
7304              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7305     };
7306     if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7307       return SDValue();
7308     if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7309       return SDValue();
7310   }
7311 
7312   SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7313                            DAG.getConstant(0, dl, MVT::i32));
7314   return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7315                      DAG.getConstant(1, dl, MVT::i32));
7316 }
7317 
7318 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7319 // from a single input on alternating lanes. For example:
7320 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7321 //             FP_ROUND(EXTRACT_ELT(X, 2),
7322 //             FP_ROUND(EXTRACT_ELT(X, 4), ...)
7323 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7324                                        const ARMSubtarget *ST) {
7325   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7326   if (!ST->hasMVEFloatOps())
7327     return SDValue();
7328 
7329   SDLoc dl(BV);
7330   EVT VT = BV.getValueType();
7331   if (VT != MVT::v4f32)
7332     return SDValue();
7333 
7334   // We are looking for a buildvector of fptext elements, where all the
7335   // elements are alternating lanes from a single source. For example <0,2,4,6>
7336   // or <1,3,5,7>. Check the first two items are valid enough and extract some
7337   // info from them (they are checked properly in the loop below).
7338   if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7339       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7340     return SDValue();
7341   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7342   int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7343   if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7344     return SDValue();
7345 
7346   // Check all the values in the BuildVector line up with our expectations.
7347   for (unsigned i = 1; i < 4; i++) {
7348     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7349       return Trunc.getOpcode() == ISD::FP_EXTEND &&
7350              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7351              Trunc.getOperand(0).getOperand(0) == Op &&
7352              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7353     };
7354     if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7355       return SDValue();
7356   }
7357 
7358   return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7359                      DAG.getConstant(Offset, dl, MVT::i32));
7360 }
7361 
7362 // If N is an integer constant that can be moved into a register in one
7363 // instruction, return an SDValue of such a constant (will become a MOV
7364 // instruction).  Otherwise return null.
7365 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7366                                      const ARMSubtarget *ST, const SDLoc &dl) {
7367   uint64_t Val;
7368   if (!isa<ConstantSDNode>(N))
7369     return SDValue();
7370   Val = cast<ConstantSDNode>(N)->getZExtValue();
7371 
7372   if (ST->isThumb1Only()) {
7373     if (Val <= 255 || ~Val <= 255)
7374       return DAG.getConstant(Val, dl, MVT::i32);
7375   } else {
7376     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7377       return DAG.getConstant(Val, dl, MVT::i32);
7378   }
7379   return SDValue();
7380 }
7381 
7382 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7383                                     const ARMSubtarget *ST) {
7384   SDLoc dl(Op);
7385   EVT VT = Op.getValueType();
7386 
7387   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7388 
7389   unsigned NumElts = VT.getVectorNumElements();
7390   unsigned BoolMask;
7391   unsigned BitsPerBool;
7392   if (NumElts == 4) {
7393     BitsPerBool = 4;
7394     BoolMask = 0xf;
7395   } else if (NumElts == 8) {
7396     BitsPerBool = 2;
7397     BoolMask = 0x3;
7398   } else if (NumElts == 16) {
7399     BitsPerBool = 1;
7400     BoolMask = 0x1;
7401   } else
7402     return SDValue();
7403 
7404   // If this is a single value copied into all lanes (a splat), we can just sign
7405   // extend that single value
7406   SDValue FirstOp = Op.getOperand(0);
7407   if (!isa<ConstantSDNode>(FirstOp) &&
7408       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7409                   [&FirstOp](SDUse &U) {
7410                     return U.get().isUndef() || U.get() == FirstOp;
7411                   })) {
7412     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7413                               DAG.getValueType(MVT::i1));
7414     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7415   }
7416 
7417   // First create base with bits set where known
7418   unsigned Bits32 = 0;
7419   for (unsigned i = 0; i < NumElts; ++i) {
7420     SDValue V = Op.getOperand(i);
7421     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7422       continue;
7423     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7424     if (BitSet)
7425       Bits32 |= BoolMask << (i * BitsPerBool);
7426   }
7427 
7428   // Add in unknown nodes
7429   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7430                              DAG.getConstant(Bits32, dl, MVT::i32));
7431   for (unsigned i = 0; i < NumElts; ++i) {
7432     SDValue V = Op.getOperand(i);
7433     if (isa<ConstantSDNode>(V) || V.isUndef())
7434       continue;
7435     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7436                        DAG.getConstant(i, dl, MVT::i32));
7437   }
7438 
7439   return Base;
7440 }
7441 
7442 // If this is a case we can't handle, return null and let the default
7443 // expansion code take care of it.
7444 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7445                                              const ARMSubtarget *ST) const {
7446   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7447   SDLoc dl(Op);
7448   EVT VT = Op.getValueType();
7449 
7450   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7451     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7452 
7453   APInt SplatBits, SplatUndef;
7454   unsigned SplatBitSize;
7455   bool HasAnyUndefs;
7456   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7457     if (SplatUndef.isAllOnesValue())
7458       return DAG.getUNDEF(VT);
7459 
7460     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7461         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7462       // Check if an immediate VMOV works.
7463       EVT VmovVT;
7464       SDValue Val =
7465           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7466                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7467 
7468       if (Val.getNode()) {
7469         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7470         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7471       }
7472 
7473       // Try an immediate VMVN.
7474       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7475       Val = isVMOVModifiedImm(
7476           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7477           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7478       if (Val.getNode()) {
7479         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7480         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7481       }
7482 
7483       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7484       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7485         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7486         if (ImmVal != -1) {
7487           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7488           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7489         }
7490       }
7491     }
7492   }
7493 
7494   // Scan through the operands to see if only one value is used.
7495   //
7496   // As an optimisation, even if more than one value is used it may be more
7497   // profitable to splat with one value then change some lanes.
7498   //
7499   // Heuristically we decide to do this if the vector has a "dominant" value,
7500   // defined as splatted to more than half of the lanes.
7501   unsigned NumElts = VT.getVectorNumElements();
7502   bool isOnlyLowElement = true;
7503   bool usesOnlyOneValue = true;
7504   bool hasDominantValue = false;
7505   bool isConstant = true;
7506 
7507   // Map of the number of times a particular SDValue appears in the
7508   // element list.
7509   DenseMap<SDValue, unsigned> ValueCounts;
7510   SDValue Value;
7511   for (unsigned i = 0; i < NumElts; ++i) {
7512     SDValue V = Op.getOperand(i);
7513     if (V.isUndef())
7514       continue;
7515     if (i > 0)
7516       isOnlyLowElement = false;
7517     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7518       isConstant = false;
7519 
7520     ValueCounts.insert(std::make_pair(V, 0));
7521     unsigned &Count = ValueCounts[V];
7522 
7523     // Is this value dominant? (takes up more than half of the lanes)
7524     if (++Count > (NumElts / 2)) {
7525       hasDominantValue = true;
7526       Value = V;
7527     }
7528   }
7529   if (ValueCounts.size() != 1)
7530     usesOnlyOneValue = false;
7531   if (!Value.getNode() && !ValueCounts.empty())
7532     Value = ValueCounts.begin()->first;
7533 
7534   if (ValueCounts.empty())
7535     return DAG.getUNDEF(VT);
7536 
7537   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7538   // Keep going if we are hitting this case.
7539   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7540     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7541 
7542   unsigned EltSize = VT.getScalarSizeInBits();
7543 
7544   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7545   // i32 and try again.
7546   if (hasDominantValue && EltSize <= 32) {
7547     if (!isConstant) {
7548       SDValue N;
7549 
7550       // If we are VDUPing a value that comes directly from a vector, that will
7551       // cause an unnecessary move to and from a GPR, where instead we could
7552       // just use VDUPLANE. We can only do this if the lane being extracted
7553       // is at a constant index, as the VDUP from lane instructions only have
7554       // constant-index forms.
7555       ConstantSDNode *constIndex;
7556       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7557           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7558         // We need to create a new undef vector to use for the VDUPLANE if the
7559         // size of the vector from which we get the value is different than the
7560         // size of the vector that we need to create. We will insert the element
7561         // such that the register coalescer will remove unnecessary copies.
7562         if (VT != Value->getOperand(0).getValueType()) {
7563           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7564                              VT.getVectorNumElements();
7565           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7566                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7567                         Value, DAG.getConstant(index, dl, MVT::i32)),
7568                            DAG.getConstant(index, dl, MVT::i32));
7569         } else
7570           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7571                         Value->getOperand(0), Value->getOperand(1));
7572       } else
7573         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7574 
7575       if (!usesOnlyOneValue) {
7576         // The dominant value was splatted as 'N', but we now have to insert
7577         // all differing elements.
7578         for (unsigned I = 0; I < NumElts; ++I) {
7579           if (Op.getOperand(I) == Value)
7580             continue;
7581           SmallVector<SDValue, 3> Ops;
7582           Ops.push_back(N);
7583           Ops.push_back(Op.getOperand(I));
7584           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7585           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7586         }
7587       }
7588       return N;
7589     }
7590     if (VT.getVectorElementType().isFloatingPoint()) {
7591       SmallVector<SDValue, 8> Ops;
7592       MVT FVT = VT.getVectorElementType().getSimpleVT();
7593       assert(FVT == MVT::f32 || FVT == MVT::f16);
7594       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7595       for (unsigned i = 0; i < NumElts; ++i)
7596         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7597                                   Op.getOperand(i)));
7598       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7599       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7600       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7601       if (Val.getNode())
7602         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7603     }
7604     if (usesOnlyOneValue) {
7605       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7606       if (isConstant && Val.getNode())
7607         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7608     }
7609   }
7610 
7611   // If all elements are constants and the case above didn't get hit, fall back
7612   // to the default expansion, which will generate a load from the constant
7613   // pool.
7614   if (isConstant)
7615     return SDValue();
7616 
7617   // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7618   // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7619   // length <= 2.
7620   if (NumElts >= 4)
7621     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7622       return shuffle;
7623 
7624   // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7625   // VCVT's
7626   if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7627     return VCVT;
7628   if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7629     return VCVT;
7630 
7631   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7632     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7633     // into two 64-bit vectors; we might discover a better way to lower it.
7634     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7635     EVT ExtVT = VT.getVectorElementType();
7636     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7637     SDValue Lower =
7638         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7639     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7640       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7641     SDValue Upper = DAG.getBuildVector(
7642         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7643     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7644       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7645     if (Lower && Upper)
7646       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7647   }
7648 
7649   // Vectors with 32- or 64-bit elements can be built by directly assigning
7650   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7651   // will be legalized.
7652   if (EltSize >= 32) {
7653     // Do the expansion with floating-point types, since that is what the VFP
7654     // registers are defined to use, and since i64 is not legal.
7655     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7656     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7657     SmallVector<SDValue, 8> Ops;
7658     for (unsigned i = 0; i < NumElts; ++i)
7659       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7660     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7661     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7662   }
7663 
7664   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7665   // know the default expansion would otherwise fall back on something even
7666   // worse. For a vector with one or two non-undef values, that's
7667   // scalar_to_vector for the elements followed by a shuffle (provided the
7668   // shuffle is valid for the target) and materialization element by element
7669   // on the stack followed by a load for everything else.
7670   if (!isConstant && !usesOnlyOneValue) {
7671     SDValue Vec = DAG.getUNDEF(VT);
7672     for (unsigned i = 0 ; i < NumElts; ++i) {
7673       SDValue V = Op.getOperand(i);
7674       if (V.isUndef())
7675         continue;
7676       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7677       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7678     }
7679     return Vec;
7680   }
7681 
7682   return SDValue();
7683 }
7684 
7685 // Gather data to see if the operation can be modelled as a
7686 // shuffle in combination with VEXTs.
7687 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7688                                               SelectionDAG &DAG) const {
7689   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7690   SDLoc dl(Op);
7691   EVT VT = Op.getValueType();
7692   unsigned NumElts = VT.getVectorNumElements();
7693 
7694   struct ShuffleSourceInfo {
7695     SDValue Vec;
7696     unsigned MinElt = std::numeric_limits<unsigned>::max();
7697     unsigned MaxElt = 0;
7698 
7699     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7700     // be compatible with the shuffle we intend to construct. As a result
7701     // ShuffleVec will be some sliding window into the original Vec.
7702     SDValue ShuffleVec;
7703 
7704     // Code should guarantee that element i in Vec starts at element "WindowBase
7705     // + i * WindowScale in ShuffleVec".
7706     int WindowBase = 0;
7707     int WindowScale = 1;
7708 
7709     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7710 
7711     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7712   };
7713 
7714   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7715   // node.
7716   SmallVector<ShuffleSourceInfo, 2> Sources;
7717   for (unsigned i = 0; i < NumElts; ++i) {
7718     SDValue V = Op.getOperand(i);
7719     if (V.isUndef())
7720       continue;
7721     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7722       // A shuffle can only come from building a vector from various
7723       // elements of other vectors.
7724       return SDValue();
7725     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7726       // Furthermore, shuffles require a constant mask, whereas extractelts
7727       // accept variable indices.
7728       return SDValue();
7729     }
7730 
7731     // Add this element source to the list if it's not already there.
7732     SDValue SourceVec = V.getOperand(0);
7733     auto Source = llvm::find(Sources, SourceVec);
7734     if (Source == Sources.end())
7735       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7736 
7737     // Update the minimum and maximum lane number seen.
7738     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7739     Source->MinElt = std::min(Source->MinElt, EltNo);
7740     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7741   }
7742 
7743   // Currently only do something sane when at most two source vectors
7744   // are involved.
7745   if (Sources.size() > 2)
7746     return SDValue();
7747 
7748   // Find out the smallest element size among result and two sources, and use
7749   // it as element size to build the shuffle_vector.
7750   EVT SmallestEltTy = VT.getVectorElementType();
7751   for (auto &Source : Sources) {
7752     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7753     if (SrcEltTy.bitsLT(SmallestEltTy))
7754       SmallestEltTy = SrcEltTy;
7755   }
7756   unsigned ResMultiplier =
7757       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7758   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7759   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7760 
7761   // If the source vector is too wide or too narrow, we may nevertheless be able
7762   // to construct a compatible shuffle either by concatenating it with UNDEF or
7763   // extracting a suitable range of elements.
7764   for (auto &Src : Sources) {
7765     EVT SrcVT = Src.ShuffleVec.getValueType();
7766 
7767     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7768     uint64_t VTSize = VT.getFixedSizeInBits();
7769     if (SrcVTSize == VTSize)
7770       continue;
7771 
7772     // This stage of the search produces a source with the same element type as
7773     // the original, but with a total width matching the BUILD_VECTOR output.
7774     EVT EltVT = SrcVT.getVectorElementType();
7775     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7776     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7777 
7778     if (SrcVTSize < VTSize) {
7779       if (2 * SrcVTSize != VTSize)
7780         return SDValue();
7781       // We can pad out the smaller vector for free, so if it's part of a
7782       // shuffle...
7783       Src.ShuffleVec =
7784           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7785                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7786       continue;
7787     }
7788 
7789     if (SrcVTSize != 2 * VTSize)
7790       return SDValue();
7791 
7792     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7793       // Span too large for a VEXT to cope
7794       return SDValue();
7795     }
7796 
7797     if (Src.MinElt >= NumSrcElts) {
7798       // The extraction can just take the second half
7799       Src.ShuffleVec =
7800           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7801                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7802       Src.WindowBase = -NumSrcElts;
7803     } else if (Src.MaxElt < NumSrcElts) {
7804       // The extraction can just take the first half
7805       Src.ShuffleVec =
7806           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7807                       DAG.getConstant(0, dl, MVT::i32));
7808     } else {
7809       // An actual VEXT is needed
7810       SDValue VEXTSrc1 =
7811           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7812                       DAG.getConstant(0, dl, MVT::i32));
7813       SDValue VEXTSrc2 =
7814           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7815                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7816 
7817       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7818                                    VEXTSrc2,
7819                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7820       Src.WindowBase = -Src.MinElt;
7821     }
7822   }
7823 
7824   // Another possible incompatibility occurs from the vector element types. We
7825   // can fix this by bitcasting the source vectors to the same type we intend
7826   // for the shuffle.
7827   for (auto &Src : Sources) {
7828     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7829     if (SrcEltTy == SmallestEltTy)
7830       continue;
7831     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7832     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7833     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7834     Src.WindowBase *= Src.WindowScale;
7835   }
7836 
7837   // Final sanity check before we try to actually produce a shuffle.
7838   LLVM_DEBUG(for (auto Src
7839                   : Sources)
7840                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7841 
7842   // The stars all align, our next step is to produce the mask for the shuffle.
7843   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7844   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7845   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7846     SDValue Entry = Op.getOperand(i);
7847     if (Entry.isUndef())
7848       continue;
7849 
7850     auto Src = llvm::find(Sources, Entry.getOperand(0));
7851     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7852 
7853     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7854     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7855     // segment.
7856     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7857     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
7858                                VT.getScalarSizeInBits());
7859     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7860 
7861     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7862     // starting at the appropriate offset.
7863     int *LaneMask = &Mask[i * ResMultiplier];
7864 
7865     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7866     ExtractBase += NumElts * (Src - Sources.begin());
7867     for (int j = 0; j < LanesDefined; ++j)
7868       LaneMask[j] = ExtractBase + j;
7869   }
7870 
7871 
7872   // We can't handle more than two sources. This should have already
7873   // been checked before this point.
7874   assert(Sources.size() <= 2 && "Too many sources!");
7875 
7876   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7877   for (unsigned i = 0; i < Sources.size(); ++i)
7878     ShuffleOps[i] = Sources[i].ShuffleVec;
7879 
7880   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7881                                             ShuffleOps[1], Mask, DAG);
7882   if (!Shuffle)
7883     return SDValue();
7884   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7885 }
7886 
7887 enum ShuffleOpCodes {
7888   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7889   OP_VREV,
7890   OP_VDUP0,
7891   OP_VDUP1,
7892   OP_VDUP2,
7893   OP_VDUP3,
7894   OP_VEXT1,
7895   OP_VEXT2,
7896   OP_VEXT3,
7897   OP_VUZPL, // VUZP, left result
7898   OP_VUZPR, // VUZP, right result
7899   OP_VZIPL, // VZIP, left result
7900   OP_VZIPR, // VZIP, right result
7901   OP_VTRNL, // VTRN, left result
7902   OP_VTRNR  // VTRN, right result
7903 };
7904 
7905 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7906   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7907   switch (OpNum) {
7908   case OP_COPY:
7909   case OP_VREV:
7910   case OP_VDUP0:
7911   case OP_VDUP1:
7912   case OP_VDUP2:
7913   case OP_VDUP3:
7914     return true;
7915   }
7916   return false;
7917 }
7918 
7919 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7920 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7921 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7922 /// are assumed to be legal.
7923 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7924   if (VT.getVectorNumElements() == 4 &&
7925       (VT.is128BitVector() || VT.is64BitVector())) {
7926     unsigned PFIndexes[4];
7927     for (unsigned i = 0; i != 4; ++i) {
7928       if (M[i] < 0)
7929         PFIndexes[i] = 8;
7930       else
7931         PFIndexes[i] = M[i];
7932     }
7933 
7934     // Compute the index in the perfect shuffle table.
7935     unsigned PFTableIndex =
7936       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7937     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7938     unsigned Cost = (PFEntry >> 30);
7939 
7940     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7941       return true;
7942   }
7943 
7944   bool ReverseVEXT, isV_UNDEF;
7945   unsigned Imm, WhichResult;
7946 
7947   unsigned EltSize = VT.getScalarSizeInBits();
7948   if (EltSize >= 32 ||
7949       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7950       ShuffleVectorInst::isIdentityMask(M) ||
7951       isVREVMask(M, VT, 64) ||
7952       isVREVMask(M, VT, 32) ||
7953       isVREVMask(M, VT, 16))
7954     return true;
7955   else if (Subtarget->hasNEON() &&
7956            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7957             isVTBLMask(M, VT) ||
7958             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7959     return true;
7960   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7961            isReverseMask(M, VT))
7962     return true;
7963   else if (Subtarget->hasMVEIntegerOps() &&
7964            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7965     return true;
7966   else
7967     return false;
7968 }
7969 
7970 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7971 /// the specified operations to build the shuffle.
7972 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7973                                       SDValue RHS, SelectionDAG &DAG,
7974                                       const SDLoc &dl) {
7975   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7976   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7977   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7978 
7979   if (OpNum == OP_COPY) {
7980     if (LHSID == (1*9+2)*9+3) return LHS;
7981     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7982     return RHS;
7983   }
7984 
7985   SDValue OpLHS, OpRHS;
7986   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7987   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7988   EVT VT = OpLHS.getValueType();
7989 
7990   switch (OpNum) {
7991   default: llvm_unreachable("Unknown shuffle opcode!");
7992   case OP_VREV:
7993     // VREV divides the vector in half and swaps within the half.
7994     if (VT.getVectorElementType() == MVT::i32 ||
7995         VT.getVectorElementType() == MVT::f32)
7996       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7997     // vrev <4 x i16> -> VREV32
7998     if (VT.getVectorElementType() == MVT::i16)
7999       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
8000     // vrev <4 x i8> -> VREV16
8001     assert(VT.getVectorElementType() == MVT::i8);
8002     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
8003   case OP_VDUP0:
8004   case OP_VDUP1:
8005   case OP_VDUP2:
8006   case OP_VDUP3:
8007     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
8008                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8009   case OP_VEXT1:
8010   case OP_VEXT2:
8011   case OP_VEXT3:
8012     return DAG.getNode(ARMISD::VEXT, dl, VT,
8013                        OpLHS, OpRHS,
8014                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8015   case OP_VUZPL:
8016   case OP_VUZPR:
8017     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8018                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8019   case OP_VZIPL:
8020   case OP_VZIPR:
8021     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8022                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8023   case OP_VTRNL:
8024   case OP_VTRNR:
8025     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8026                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8027   }
8028 }
8029 
8030 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8031                                        ArrayRef<int> ShuffleMask,
8032                                        SelectionDAG &DAG) {
8033   // Check to see if we can use the VTBL instruction.
8034   SDValue V1 = Op.getOperand(0);
8035   SDValue V2 = Op.getOperand(1);
8036   SDLoc DL(Op);
8037 
8038   SmallVector<SDValue, 8> VTBLMask;
8039   for (ArrayRef<int>::iterator
8040          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
8041     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
8042 
8043   if (V2.getNode()->isUndef())
8044     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8045                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8046 
8047   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8048                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8049 }
8050 
8051 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
8052                                                       SelectionDAG &DAG) {
8053   SDLoc DL(Op);
8054   SDValue OpLHS = Op.getOperand(0);
8055   EVT VT = OpLHS.getValueType();
8056 
8057   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
8058          "Expect an v8i16/v16i8 type");
8059   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
8060   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
8061   // extract the first 8 bytes into the top double word and the last 8 bytes
8062   // into the bottom double word. The v8i16 case is similar.
8063   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
8064   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
8065                      DAG.getConstant(ExtractNum, DL, MVT::i32));
8066 }
8067 
8068 static EVT getVectorTyFromPredicateVector(EVT VT) {
8069   switch (VT.getSimpleVT().SimpleTy) {
8070   case MVT::v4i1:
8071     return MVT::v4i32;
8072   case MVT::v8i1:
8073     return MVT::v8i16;
8074   case MVT::v16i1:
8075     return MVT::v16i8;
8076   default:
8077     llvm_unreachable("Unexpected vector predicate type");
8078   }
8079 }
8080 
8081 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8082                                     SelectionDAG &DAG) {
8083   // Converting from boolean predicates to integers involves creating a vector
8084   // of all ones or all zeroes and selecting the lanes based upon the real
8085   // predicate.
8086   SDValue AllOnes =
8087       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8088   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8089 
8090   SDValue AllZeroes =
8091       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8092   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8093 
8094   // Get full vector type from predicate type
8095   EVT NewVT = getVectorTyFromPredicateVector(VT);
8096 
8097   SDValue RecastV1;
8098   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8099   // this to a v16i1. This cannot be done with an ordinary bitcast because the
8100   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8101   // since we know in hardware the sizes are really the same.
8102   if (VT != MVT::v16i1)
8103     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8104   else
8105     RecastV1 = Pred;
8106 
8107   // Select either all ones or zeroes depending upon the real predicate bits.
8108   SDValue PredAsVector =
8109       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8110 
8111   // Recast our new predicate-as-integer v16i8 vector into something
8112   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8113   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8114 }
8115 
8116 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8117                                       const ARMSubtarget *ST) {
8118   EVT VT = Op.getValueType();
8119   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8120   ArrayRef<int> ShuffleMask = SVN->getMask();
8121 
8122   assert(ST->hasMVEIntegerOps() &&
8123          "No support for vector shuffle of boolean predicates");
8124 
8125   SDValue V1 = Op.getOperand(0);
8126   SDLoc dl(Op);
8127   if (isReverseMask(ShuffleMask, VT)) {
8128     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8129     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8130     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8131                               DAG.getConstant(16, dl, MVT::i32));
8132     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8133   }
8134 
8135   // Until we can come up with optimised cases for every single vector
8136   // shuffle in existence we have chosen the least painful strategy. This is
8137   // to essentially promote the boolean predicate to a 8-bit integer, where
8138   // each predicate represents a byte. Then we fall back on a normal integer
8139   // vector shuffle and convert the result back into a predicate vector. In
8140   // many cases the generated code might be even better than scalar code
8141   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8142   // fields in a register into 8 other arbitrary 2-bit fields!
8143   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8144   EVT NewVT = PredAsVector.getValueType();
8145 
8146   // Do the shuffle!
8147   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8148                                           DAG.getUNDEF(NewVT), ShuffleMask);
8149 
8150   // Now return the result of comparing the shuffled vector with zero,
8151   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8152   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8153                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8154 }
8155 
8156 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8157                                             ArrayRef<int> ShuffleMask,
8158                                             SelectionDAG &DAG) {
8159   // Attempt to lower the vector shuffle using as many whole register movs as
8160   // possible. This is useful for types smaller than 32bits, which would
8161   // often otherwise become a series for grp movs.
8162   SDLoc dl(Op);
8163   EVT VT = Op.getValueType();
8164   if (VT.getScalarSizeInBits() >= 32)
8165     return SDValue();
8166 
8167   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8168          "Unexpected vector type");
8169   int NumElts = VT.getVectorNumElements();
8170   int QuarterSize = NumElts / 4;
8171   // The four final parts of the vector, as i32's
8172   SDValue Parts[4];
8173 
8174   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8175   // <u,u,u,u>), returning the vmov lane index
8176   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8177     // Detect which mov lane this would be from the first non-undef element.
8178     int MovIdx = -1;
8179     for (int i = 0; i < Length; i++) {
8180       if (ShuffleMask[Start + i] >= 0) {
8181         if (ShuffleMask[Start + i] % Length != i)
8182           return -1;
8183         MovIdx = ShuffleMask[Start + i] / Length;
8184         break;
8185       }
8186     }
8187     // If all items are undef, leave this for other combines
8188     if (MovIdx == -1)
8189       return -1;
8190     // Check the remaining values are the correct part of the same mov
8191     for (int i = 1; i < Length; i++) {
8192       if (ShuffleMask[Start + i] >= 0 &&
8193           (ShuffleMask[Start + i] / Length != MovIdx ||
8194            ShuffleMask[Start + i] % Length != i))
8195         return -1;
8196     }
8197     return MovIdx;
8198   };
8199 
8200   for (int Part = 0; Part < 4; ++Part) {
8201     // Does this part look like a mov
8202     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8203     if (Elt != -1) {
8204       SDValue Input = Op->getOperand(0);
8205       if (Elt >= 4) {
8206         Input = Op->getOperand(1);
8207         Elt -= 4;
8208       }
8209       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
8210       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
8211                                 DAG.getConstant(Elt, dl, MVT::i32));
8212     }
8213   }
8214 
8215   // Nothing interesting found, just return
8216   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8217     return SDValue();
8218 
8219   // The other parts need to be built with the old shuffle vector, cast to a
8220   // v4i32 and extract_vector_elts
8221   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8222     SmallVector<int, 16> NewShuffleMask;
8223     for (int Part = 0; Part < 4; ++Part)
8224       for (int i = 0; i < QuarterSize; i++)
8225         NewShuffleMask.push_back(
8226             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8227     SDValue NewShuffle = DAG.getVectorShuffle(
8228         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8229     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
8230 
8231     for (int Part = 0; Part < 4; ++Part)
8232       if (!Parts[Part])
8233         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8234                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
8235   }
8236   // Build a vector out of the various parts and bitcast it back to the original
8237   // type.
8238   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
8239   return DAG.getBitcast(VT, NewVec);
8240 }
8241 
8242 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8243                                    const ARMSubtarget *ST) {
8244   SDValue V1 = Op.getOperand(0);
8245   SDValue V2 = Op.getOperand(1);
8246   SDLoc dl(Op);
8247   EVT VT = Op.getValueType();
8248   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8249   unsigned EltSize = VT.getScalarSizeInBits();
8250 
8251   if (ST->hasMVEIntegerOps() && EltSize == 1)
8252     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8253 
8254   // Convert shuffles that are directly supported on NEON to target-specific
8255   // DAG nodes, instead of keeping them as shuffles and matching them again
8256   // during code selection.  This is more efficient and avoids the possibility
8257   // of inconsistencies between legalization and selection.
8258   // FIXME: floating-point vectors should be canonicalized to integer vectors
8259   // of the same time so that they get CSEd properly.
8260   ArrayRef<int> ShuffleMask = SVN->getMask();
8261 
8262   if (EltSize <= 32) {
8263     if (SVN->isSplat()) {
8264       int Lane = SVN->getSplatIndex();
8265       // If this is undef splat, generate it via "just" vdup, if possible.
8266       if (Lane == -1) Lane = 0;
8267 
8268       // Test if V1 is a SCALAR_TO_VECTOR.
8269       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8270         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8271       }
8272       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8273       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8274       // reaches it).
8275       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8276           !isa<ConstantSDNode>(V1.getOperand(0))) {
8277         bool IsScalarToVector = true;
8278         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8279           if (!V1.getOperand(i).isUndef()) {
8280             IsScalarToVector = false;
8281             break;
8282           }
8283         if (IsScalarToVector)
8284           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8285       }
8286       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8287                          DAG.getConstant(Lane, dl, MVT::i32));
8288     }
8289 
8290     bool ReverseVEXT = false;
8291     unsigned Imm = 0;
8292     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8293       if (ReverseVEXT)
8294         std::swap(V1, V2);
8295       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8296                          DAG.getConstant(Imm, dl, MVT::i32));
8297     }
8298 
8299     if (isVREVMask(ShuffleMask, VT, 64))
8300       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8301     if (isVREVMask(ShuffleMask, VT, 32))
8302       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8303     if (isVREVMask(ShuffleMask, VT, 16))
8304       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8305 
8306     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8307       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8308                          DAG.getConstant(Imm, dl, MVT::i32));
8309     }
8310 
8311     // Check for Neon shuffles that modify both input vectors in place.
8312     // If both results are used, i.e., if there are two shuffles with the same
8313     // source operands and with masks corresponding to both results of one of
8314     // these operations, DAG memoization will ensure that a single node is
8315     // used for both shuffles.
8316     unsigned WhichResult = 0;
8317     bool isV_UNDEF = false;
8318     if (ST->hasNEON()) {
8319       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8320               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8321         if (isV_UNDEF)
8322           V2 = V1;
8323         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8324             .getValue(WhichResult);
8325       }
8326     }
8327     if (ST->hasMVEIntegerOps()) {
8328       if (isVMOVNMask(ShuffleMask, VT, 0))
8329         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8330                            DAG.getConstant(0, dl, MVT::i32));
8331       if (isVMOVNMask(ShuffleMask, VT, 1))
8332         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8333                            DAG.getConstant(1, dl, MVT::i32));
8334     }
8335 
8336     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8337     // shuffles that produce a result larger than their operands with:
8338     //   shuffle(concat(v1, undef), concat(v2, undef))
8339     // ->
8340     //   shuffle(concat(v1, v2), undef)
8341     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8342     //
8343     // This is useful in the general case, but there are special cases where
8344     // native shuffles produce larger results: the two-result ops.
8345     //
8346     // Look through the concat when lowering them:
8347     //   shuffle(concat(v1, v2), undef)
8348     // ->
8349     //   concat(VZIP(v1, v2):0, :1)
8350     //
8351     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8352       SDValue SubV1 = V1->getOperand(0);
8353       SDValue SubV2 = V1->getOperand(1);
8354       EVT SubVT = SubV1.getValueType();
8355 
8356       // We expect these to have been canonicalized to -1.
8357       assert(llvm::all_of(ShuffleMask, [&](int i) {
8358         return i < (int)VT.getVectorNumElements();
8359       }) && "Unexpected shuffle index into UNDEF operand!");
8360 
8361       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8362               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8363         if (isV_UNDEF)
8364           SubV2 = SubV1;
8365         assert((WhichResult == 0) &&
8366                "In-place shuffle of concat can only have one result!");
8367         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8368                                   SubV1, SubV2);
8369         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8370                            Res.getValue(1));
8371       }
8372     }
8373   }
8374 
8375   // If the shuffle is not directly supported and it has 4 elements, use
8376   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8377   unsigned NumElts = VT.getVectorNumElements();
8378   if (NumElts == 4) {
8379     unsigned PFIndexes[4];
8380     for (unsigned i = 0; i != 4; ++i) {
8381       if (ShuffleMask[i] < 0)
8382         PFIndexes[i] = 8;
8383       else
8384         PFIndexes[i] = ShuffleMask[i];
8385     }
8386 
8387     // Compute the index in the perfect shuffle table.
8388     unsigned PFTableIndex =
8389       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8390     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8391     unsigned Cost = (PFEntry >> 30);
8392 
8393     if (Cost <= 4) {
8394       if (ST->hasNEON())
8395         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8396       else if (isLegalMVEShuffleOp(PFEntry)) {
8397         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8398         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8399         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8400         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8401         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8402           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8403       }
8404     }
8405   }
8406 
8407   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8408   if (EltSize >= 32) {
8409     // Do the expansion with floating-point types, since that is what the VFP
8410     // registers are defined to use, and since i64 is not legal.
8411     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8412     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8413     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8414     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8415     SmallVector<SDValue, 8> Ops;
8416     for (unsigned i = 0; i < NumElts; ++i) {
8417       if (ShuffleMask[i] < 0)
8418         Ops.push_back(DAG.getUNDEF(EltVT));
8419       else
8420         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8421                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8422                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8423                                                   dl, MVT::i32)));
8424     }
8425     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8426     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8427   }
8428 
8429   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8430     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8431 
8432   if (ST->hasNEON() && VT == MVT::v8i8)
8433     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8434       return NewOp;
8435 
8436   if (ST->hasMVEIntegerOps())
8437     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8438       return NewOp;
8439 
8440   return SDValue();
8441 }
8442 
8443 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8444                                          const ARMSubtarget *ST) {
8445   EVT VecVT = Op.getOperand(0).getValueType();
8446   SDLoc dl(Op);
8447 
8448   assert(ST->hasMVEIntegerOps() &&
8449          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8450 
8451   SDValue Conv =
8452       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8453   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8454   unsigned LaneWidth =
8455       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8456   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8457   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8458                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8459   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8460                             DAG.getConstant(~Mask, dl, MVT::i32));
8461   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8462 }
8463 
8464 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8465                                                   SelectionDAG &DAG) const {
8466   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8467   SDValue Lane = Op.getOperand(2);
8468   if (!isa<ConstantSDNode>(Lane))
8469     return SDValue();
8470 
8471   SDValue Elt = Op.getOperand(1);
8472   EVT EltVT = Elt.getValueType();
8473 
8474   if (Subtarget->hasMVEIntegerOps() &&
8475       Op.getValueType().getScalarSizeInBits() == 1)
8476     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8477 
8478   if (getTypeAction(*DAG.getContext(), EltVT) ==
8479       TargetLowering::TypePromoteFloat) {
8480     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8481     // but the type system will try to do that if we don't intervene.
8482     // Reinterpret any such vector-element insertion as one with the
8483     // corresponding integer types.
8484 
8485     SDLoc dl(Op);
8486 
8487     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8488     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8489            TargetLowering::TypePromoteFloat);
8490 
8491     SDValue VecIn = Op.getOperand(0);
8492     EVT VecVT = VecIn.getValueType();
8493     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8494                                   VecVT.getVectorNumElements());
8495 
8496     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8497     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8498     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8499                                   IVecIn, IElt, Lane);
8500     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8501   }
8502 
8503   return Op;
8504 }
8505 
8506 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8507                                           const ARMSubtarget *ST) {
8508   EVT VecVT = Op.getOperand(0).getValueType();
8509   SDLoc dl(Op);
8510 
8511   assert(ST->hasMVEIntegerOps() &&
8512          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8513 
8514   SDValue Conv =
8515       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8516   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8517   unsigned LaneWidth =
8518       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8519   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8520                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8521   return Shift;
8522 }
8523 
8524 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8525                                        const ARMSubtarget *ST) {
8526   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8527   SDValue Lane = Op.getOperand(1);
8528   if (!isa<ConstantSDNode>(Lane))
8529     return SDValue();
8530 
8531   SDValue Vec = Op.getOperand(0);
8532   EVT VT = Vec.getValueType();
8533 
8534   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8535     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8536 
8537   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8538     SDLoc dl(Op);
8539     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8540   }
8541 
8542   return Op;
8543 }
8544 
8545 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8546                                       const ARMSubtarget *ST) {
8547   SDValue V1 = Op.getOperand(0);
8548   SDValue V2 = Op.getOperand(1);
8549   SDLoc dl(Op);
8550   EVT VT = Op.getValueType();
8551   EVT Op1VT = V1.getValueType();
8552   EVT Op2VT = V2.getValueType();
8553   unsigned NumElts = VT.getVectorNumElements();
8554 
8555   assert(Op1VT == Op2VT && "Operand types don't match!");
8556   assert(VT.getScalarSizeInBits() == 1 &&
8557          "Unexpected custom CONCAT_VECTORS lowering");
8558   assert(ST->hasMVEIntegerOps() &&
8559          "CONCAT_VECTORS lowering only supported for MVE");
8560 
8561   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8562   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8563 
8564   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8565   // promoted to v8i16, etc.
8566 
8567   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8568 
8569   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8570   // to be the right size for the destination. For example, if Op1 is v4i1 then
8571   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8572   // which when promoted is v8i16. That means each i32 element from Op1 needs
8573   // truncating to i16 and inserting in the result.
8574   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8575   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8576   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8577     EVT NewVT = NewV.getValueType();
8578     EVT ConcatVT = ConVec.getValueType();
8579     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8580       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8581                                 DAG.getIntPtrConstant(i, dl));
8582       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8583                            DAG.getConstant(j, dl, MVT::i32));
8584     }
8585     return ConVec;
8586   };
8587   unsigned j = 0;
8588   ConVec = ExractInto(NewV1, ConVec, j);
8589   ConVec = ExractInto(NewV2, ConVec, j);
8590 
8591   // Now return the result of comparing the subvector with zero,
8592   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8593   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8594                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8595 }
8596 
8597 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8598                                    const ARMSubtarget *ST) {
8599   EVT VT = Op->getValueType(0);
8600   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8601     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8602 
8603   // The only time a CONCAT_VECTORS operation can have legal types is when
8604   // two 64-bit vectors are concatenated to a 128-bit vector.
8605   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8606          "unexpected CONCAT_VECTORS");
8607   SDLoc dl(Op);
8608   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8609   SDValue Op0 = Op.getOperand(0);
8610   SDValue Op1 = Op.getOperand(1);
8611   if (!Op0.isUndef())
8612     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8613                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8614                       DAG.getIntPtrConstant(0, dl));
8615   if (!Op1.isUndef())
8616     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8617                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8618                       DAG.getIntPtrConstant(1, dl));
8619   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8620 }
8621 
8622 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8623                                       const ARMSubtarget *ST) {
8624   SDValue V1 = Op.getOperand(0);
8625   SDValue V2 = Op.getOperand(1);
8626   SDLoc dl(Op);
8627   EVT VT = Op.getValueType();
8628   EVT Op1VT = V1.getValueType();
8629   unsigned NumElts = VT.getVectorNumElements();
8630   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8631 
8632   assert(VT.getScalarSizeInBits() == 1 &&
8633          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8634   assert(ST->hasMVEIntegerOps() &&
8635          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8636 
8637   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8638 
8639   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8640   // promoted to v8i16, etc.
8641 
8642   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8643 
8644   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8645   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8646   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8647     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8648                               DAG.getIntPtrConstant(i, dl));
8649     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8650                          DAG.getConstant(j, dl, MVT::i32));
8651   }
8652 
8653   // Now return the result of comparing the subvector with zero,
8654   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8655   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8656                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8657 }
8658 
8659 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8660 /// element has been zero/sign-extended, depending on the isSigned parameter,
8661 /// from an integer type half its size.
8662 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8663                                    bool isSigned) {
8664   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8665   EVT VT = N->getValueType(0);
8666   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8667     SDNode *BVN = N->getOperand(0).getNode();
8668     if (BVN->getValueType(0) != MVT::v4i32 ||
8669         BVN->getOpcode() != ISD::BUILD_VECTOR)
8670       return false;
8671     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8672     unsigned HiElt = 1 - LoElt;
8673     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8674     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8675     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8676     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8677     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8678       return false;
8679     if (isSigned) {
8680       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8681           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8682         return true;
8683     } else {
8684       if (Hi0->isNullValue() && Hi1->isNullValue())
8685         return true;
8686     }
8687     return false;
8688   }
8689 
8690   if (N->getOpcode() != ISD::BUILD_VECTOR)
8691     return false;
8692 
8693   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8694     SDNode *Elt = N->getOperand(i).getNode();
8695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8696       unsigned EltSize = VT.getScalarSizeInBits();
8697       unsigned HalfSize = EltSize / 2;
8698       if (isSigned) {
8699         if (!isIntN(HalfSize, C->getSExtValue()))
8700           return false;
8701       } else {
8702         if (!isUIntN(HalfSize, C->getZExtValue()))
8703           return false;
8704       }
8705       continue;
8706     }
8707     return false;
8708   }
8709 
8710   return true;
8711 }
8712 
8713 /// isSignExtended - Check if a node is a vector value that is sign-extended
8714 /// or a constant BUILD_VECTOR with sign-extended elements.
8715 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8716   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8717     return true;
8718   if (isExtendedBUILD_VECTOR(N, DAG, true))
8719     return true;
8720   return false;
8721 }
8722 
8723 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8724 /// or a constant BUILD_VECTOR with zero-extended elements.
8725 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8726   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8727     return true;
8728   if (isExtendedBUILD_VECTOR(N, DAG, false))
8729     return true;
8730   return false;
8731 }
8732 
8733 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8734   if (OrigVT.getSizeInBits() >= 64)
8735     return OrigVT;
8736 
8737   assert(OrigVT.isSimple() && "Expecting a simple value type");
8738 
8739   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8740   switch (OrigSimpleTy) {
8741   default: llvm_unreachable("Unexpected Vector Type");
8742   case MVT::v2i8:
8743   case MVT::v2i16:
8744      return MVT::v2i32;
8745   case MVT::v4i8:
8746     return  MVT::v4i16;
8747   }
8748 }
8749 
8750 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8751 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8752 /// We insert the required extension here to get the vector to fill a D register.
8753 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8754                                             const EVT &OrigTy,
8755                                             const EVT &ExtTy,
8756                                             unsigned ExtOpcode) {
8757   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8758   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8759   // 64-bits we need to insert a new extension so that it will be 64-bits.
8760   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8761   if (OrigTy.getSizeInBits() >= 64)
8762     return N;
8763 
8764   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8765   EVT NewVT = getExtensionTo64Bits(OrigTy);
8766 
8767   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8768 }
8769 
8770 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8771 /// does not do any sign/zero extension. If the original vector is less
8772 /// than 64 bits, an appropriate extension will be added after the load to
8773 /// reach a total size of 64 bits. We have to add the extension separately
8774 /// because ARM does not have a sign/zero extending load for vectors.
8775 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8776   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8777 
8778   // The load already has the right type.
8779   if (ExtendedTy == LD->getMemoryVT())
8780     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8781                        LD->getBasePtr(), LD->getPointerInfo(),
8782                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8783 
8784   // We need to create a zextload/sextload. We cannot just create a load
8785   // followed by a zext/zext node because LowerMUL is also run during normal
8786   // operation legalization where we can't create illegal types.
8787   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8788                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8789                         LD->getMemoryVT(), LD->getAlignment(),
8790                         LD->getMemOperand()->getFlags());
8791 }
8792 
8793 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8794 /// extending load, or BUILD_VECTOR with extended elements, return the
8795 /// unextended value. The unextended vector should be 64 bits so that it can
8796 /// be used as an operand to a VMULL instruction. If the original vector size
8797 /// before extension is less than 64 bits we add a an extension to resize
8798 /// the vector to 64 bits.
8799 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8800   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8801     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8802                                         N->getOperand(0)->getValueType(0),
8803                                         N->getValueType(0),
8804                                         N->getOpcode());
8805 
8806   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8807     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8808            "Expected extending load");
8809 
8810     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8811     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8812     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8813     SDValue extLoad =
8814         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8815     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8816 
8817     return newLoad;
8818   }
8819 
8820   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8821   // have been legalized as a BITCAST from v4i32.
8822   if (N->getOpcode() == ISD::BITCAST) {
8823     SDNode *BVN = N->getOperand(0).getNode();
8824     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8825            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8826     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8827     return DAG.getBuildVector(
8828         MVT::v2i32, SDLoc(N),
8829         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8830   }
8831   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8832   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8833   EVT VT = N->getValueType(0);
8834   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8835   unsigned NumElts = VT.getVectorNumElements();
8836   MVT TruncVT = MVT::getIntegerVT(EltSize);
8837   SmallVector<SDValue, 8> Ops;
8838   SDLoc dl(N);
8839   for (unsigned i = 0; i != NumElts; ++i) {
8840     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8841     const APInt &CInt = C->getAPIntValue();
8842     // Element types smaller than 32 bits are not legal, so use i32 elements.
8843     // The values are implicitly truncated so sext vs. zext doesn't matter.
8844     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8845   }
8846   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8847 }
8848 
8849 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8850   unsigned Opcode = N->getOpcode();
8851   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8852     SDNode *N0 = N->getOperand(0).getNode();
8853     SDNode *N1 = N->getOperand(1).getNode();
8854     return N0->hasOneUse() && N1->hasOneUse() &&
8855       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8856   }
8857   return false;
8858 }
8859 
8860 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8861   unsigned Opcode = N->getOpcode();
8862   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8863     SDNode *N0 = N->getOperand(0).getNode();
8864     SDNode *N1 = N->getOperand(1).getNode();
8865     return N0->hasOneUse() && N1->hasOneUse() &&
8866       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8867   }
8868   return false;
8869 }
8870 
8871 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8872   // Multiplications are only custom-lowered for 128-bit vectors so that
8873   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8874   EVT VT = Op.getValueType();
8875   assert(VT.is128BitVector() && VT.isInteger() &&
8876          "unexpected type for custom-lowering ISD::MUL");
8877   SDNode *N0 = Op.getOperand(0).getNode();
8878   SDNode *N1 = Op.getOperand(1).getNode();
8879   unsigned NewOpc = 0;
8880   bool isMLA = false;
8881   bool isN0SExt = isSignExtended(N0, DAG);
8882   bool isN1SExt = isSignExtended(N1, DAG);
8883   if (isN0SExt && isN1SExt)
8884     NewOpc = ARMISD::VMULLs;
8885   else {
8886     bool isN0ZExt = isZeroExtended(N0, DAG);
8887     bool isN1ZExt = isZeroExtended(N1, DAG);
8888     if (isN0ZExt && isN1ZExt)
8889       NewOpc = ARMISD::VMULLu;
8890     else if (isN1SExt || isN1ZExt) {
8891       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8892       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8893       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8894         NewOpc = ARMISD::VMULLs;
8895         isMLA = true;
8896       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8897         NewOpc = ARMISD::VMULLu;
8898         isMLA = true;
8899       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8900         std::swap(N0, N1);
8901         NewOpc = ARMISD::VMULLu;
8902         isMLA = true;
8903       }
8904     }
8905 
8906     if (!NewOpc) {
8907       if (VT == MVT::v2i64)
8908         // Fall through to expand this.  It is not legal.
8909         return SDValue();
8910       else
8911         // Other vector multiplications are legal.
8912         return Op;
8913     }
8914   }
8915 
8916   // Legalize to a VMULL instruction.
8917   SDLoc DL(Op);
8918   SDValue Op0;
8919   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8920   if (!isMLA) {
8921     Op0 = SkipExtensionForVMULL(N0, DAG);
8922     assert(Op0.getValueType().is64BitVector() &&
8923            Op1.getValueType().is64BitVector() &&
8924            "unexpected types for extended operands to VMULL");
8925     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8926   }
8927 
8928   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8929   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8930   //   vmull q0, d4, d6
8931   //   vmlal q0, d5, d6
8932   // is faster than
8933   //   vaddl q0, d4, d5
8934   //   vmovl q1, d6
8935   //   vmul  q0, q0, q1
8936   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8937   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8938   EVT Op1VT = Op1.getValueType();
8939   return DAG.getNode(N0->getOpcode(), DL, VT,
8940                      DAG.getNode(NewOpc, DL, VT,
8941                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8942                      DAG.getNode(NewOpc, DL, VT,
8943                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8944 }
8945 
8946 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8947                               SelectionDAG &DAG) {
8948   // TODO: Should this propagate fast-math-flags?
8949 
8950   // Convert to float
8951   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8952   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8953   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8954   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8955   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8956   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8957   // Get reciprocal estimate.
8958   // float4 recip = vrecpeq_f32(yf);
8959   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8960                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8961                    Y);
8962   // Because char has a smaller range than uchar, we can actually get away
8963   // without any newton steps.  This requires that we use a weird bias
8964   // of 0xb000, however (again, this has been exhaustively tested).
8965   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8966   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8967   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8968   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8969   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8970   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8971   // Convert back to short.
8972   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8973   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8974   return X;
8975 }
8976 
8977 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8978                                SelectionDAG &DAG) {
8979   // TODO: Should this propagate fast-math-flags?
8980 
8981   SDValue N2;
8982   // Convert to float.
8983   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8984   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8985   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8986   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8987   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8988   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8989 
8990   // Use reciprocal estimate and one refinement step.
8991   // float4 recip = vrecpeq_f32(yf);
8992   // recip *= vrecpsq_f32(yf, recip);
8993   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8994                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8995                    N1);
8996   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8997                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8998                    N1, N2);
8999   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9000   // Because short has a smaller range than ushort, we can actually get away
9001   // with only a single newton step.  This requires that we use a weird bias
9002   // of 89, however (again, this has been exhaustively tested).
9003   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
9004   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9005   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9006   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
9007   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9008   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9009   // Convert back to integer and return.
9010   // return vmovn_s32(vcvt_s32_f32(result));
9011   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9012   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9013   return N0;
9014 }
9015 
9016 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9017                          const ARMSubtarget *ST) {
9018   EVT VT = Op.getValueType();
9019   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9020          "unexpected type for custom-lowering ISD::SDIV");
9021 
9022   SDLoc dl(Op);
9023   SDValue N0 = Op.getOperand(0);
9024   SDValue N1 = Op.getOperand(1);
9025   SDValue N2, N3;
9026 
9027   if (VT == MVT::v8i8) {
9028     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9029     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9030 
9031     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9032                      DAG.getIntPtrConstant(4, dl));
9033     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9034                      DAG.getIntPtrConstant(4, dl));
9035     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9036                      DAG.getIntPtrConstant(0, dl));
9037     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9038                      DAG.getIntPtrConstant(0, dl));
9039 
9040     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9041     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9042 
9043     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9044     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9045 
9046     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9047     return N0;
9048   }
9049   return LowerSDIV_v4i16(N0, N1, dl, DAG);
9050 }
9051 
9052 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9053                          const ARMSubtarget *ST) {
9054   // TODO: Should this propagate fast-math-flags?
9055   EVT VT = Op.getValueType();
9056   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9057          "unexpected type for custom-lowering ISD::UDIV");
9058 
9059   SDLoc dl(Op);
9060   SDValue N0 = Op.getOperand(0);
9061   SDValue N1 = Op.getOperand(1);
9062   SDValue N2, N3;
9063 
9064   if (VT == MVT::v8i8) {
9065     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9066     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9067 
9068     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9069                      DAG.getIntPtrConstant(4, dl));
9070     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9071                      DAG.getIntPtrConstant(4, dl));
9072     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9073                      DAG.getIntPtrConstant(0, dl));
9074     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9075                      DAG.getIntPtrConstant(0, dl));
9076 
9077     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9078     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9079 
9080     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9081     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9082 
9083     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9084                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9085                                      MVT::i32),
9086                      N0);
9087     return N0;
9088   }
9089 
9090   // v4i16 sdiv ... Convert to float.
9091   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9092   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9093   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9094   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9095   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9096   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9097 
9098   // Use reciprocal estimate and two refinement steps.
9099   // float4 recip = vrecpeq_f32(yf);
9100   // recip *= vrecpsq_f32(yf, recip);
9101   // recip *= vrecpsq_f32(yf, recip);
9102   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9103                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9104                    BN1);
9105   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9106                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9107                    BN1, N2);
9108   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9109   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9110                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9111                    BN1, N2);
9112   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9113   // Simply multiplying by the reciprocal estimate can leave us a few ulps
9114   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9115   // and that it will never cause us to return an answer too large).
9116   // float4 result = as_float4(as_int4(xf*recip) + 2);
9117   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9118   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9119   N1 = DAG.getConstant(2, dl, MVT::v4i32);
9120   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9121   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9122   // Convert back to integer and return.
9123   // return vmovn_u32(vcvt_s32_f32(result));
9124   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9125   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9126   return N0;
9127 }
9128 
9129 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9130   SDNode *N = Op.getNode();
9131   EVT VT = N->getValueType(0);
9132   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9133 
9134   SDValue Carry = Op.getOperand(2);
9135 
9136   SDLoc DL(Op);
9137 
9138   SDValue Result;
9139   if (Op.getOpcode() == ISD::ADDCARRY) {
9140     // This converts the boolean value carry into the carry flag.
9141     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9142 
9143     // Do the addition proper using the carry flag we wanted.
9144     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9145                          Op.getOperand(1), Carry);
9146 
9147     // Now convert the carry flag into a boolean value.
9148     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9149   } else {
9150     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9151     // have to invert the carry first.
9152     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9153                         DAG.getConstant(1, DL, MVT::i32), Carry);
9154     // This converts the boolean value carry into the carry flag.
9155     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9156 
9157     // Do the subtraction proper using the carry flag we wanted.
9158     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9159                          Op.getOperand(1), Carry);
9160 
9161     // Now convert the carry flag into a boolean value.
9162     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9163     // But the carry returned by ARMISD::SUBE is not a borrow as expected
9164     // by ISD::SUBCARRY, so compute 1 - C.
9165     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9166                         DAG.getConstant(1, DL, MVT::i32), Carry);
9167   }
9168 
9169   // Return both values.
9170   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9171 }
9172 
9173 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9174   assert(Subtarget->isTargetDarwin());
9175 
9176   // For iOS, we want to call an alternative entry point: __sincos_stret,
9177   // return values are passed via sret.
9178   SDLoc dl(Op);
9179   SDValue Arg = Op.getOperand(0);
9180   EVT ArgVT = Arg.getValueType();
9181   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9182   auto PtrVT = getPointerTy(DAG.getDataLayout());
9183 
9184   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9186 
9187   // Pair of floats / doubles used to pass the result.
9188   Type *RetTy = StructType::get(ArgTy, ArgTy);
9189   auto &DL = DAG.getDataLayout();
9190 
9191   ArgListTy Args;
9192   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9193   SDValue SRet;
9194   if (ShouldUseSRet) {
9195     // Create stack object for sret.
9196     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9197     const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9198     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9199     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9200 
9201     ArgListEntry Entry;
9202     Entry.Node = SRet;
9203     Entry.Ty = RetTy->getPointerTo();
9204     Entry.IsSExt = false;
9205     Entry.IsZExt = false;
9206     Entry.IsSRet = true;
9207     Args.push_back(Entry);
9208     RetTy = Type::getVoidTy(*DAG.getContext());
9209   }
9210 
9211   ArgListEntry Entry;
9212   Entry.Node = Arg;
9213   Entry.Ty = ArgTy;
9214   Entry.IsSExt = false;
9215   Entry.IsZExt = false;
9216   Args.push_back(Entry);
9217 
9218   RTLIB::Libcall LC =
9219       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9220   const char *LibcallName = getLibcallName(LC);
9221   CallingConv::ID CC = getLibcallCallingConv(LC);
9222   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9223 
9224   TargetLowering::CallLoweringInfo CLI(DAG);
9225   CLI.setDebugLoc(dl)
9226       .setChain(DAG.getEntryNode())
9227       .setCallee(CC, RetTy, Callee, std::move(Args))
9228       .setDiscardResult(ShouldUseSRet);
9229   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9230 
9231   if (!ShouldUseSRet)
9232     return CallResult.first;
9233 
9234   SDValue LoadSin =
9235       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9236 
9237   // Address of cos field.
9238   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9239                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9240   SDValue LoadCos =
9241       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9242 
9243   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9244   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9245                      LoadSin.getValue(0), LoadCos.getValue(0));
9246 }
9247 
9248 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9249                                                   bool Signed,
9250                                                   SDValue &Chain) const {
9251   EVT VT = Op.getValueType();
9252   assert((VT == MVT::i32 || VT == MVT::i64) &&
9253          "unexpected type for custom lowering DIV");
9254   SDLoc dl(Op);
9255 
9256   const auto &DL = DAG.getDataLayout();
9257   const auto &TLI = DAG.getTargetLoweringInfo();
9258 
9259   const char *Name = nullptr;
9260   if (Signed)
9261     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9262   else
9263     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9264 
9265   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9266 
9267   ARMTargetLowering::ArgListTy Args;
9268 
9269   for (auto AI : {1, 0}) {
9270     ArgListEntry Arg;
9271     Arg.Node = Op.getOperand(AI);
9272     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9273     Args.push_back(Arg);
9274   }
9275 
9276   CallLoweringInfo CLI(DAG);
9277   CLI.setDebugLoc(dl)
9278     .setChain(Chain)
9279     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9280                ES, std::move(Args));
9281 
9282   return LowerCallTo(CLI).first;
9283 }
9284 
9285 // This is a code size optimisation: return the original SDIV node to
9286 // DAGCombiner when we don't want to expand SDIV into a sequence of
9287 // instructions, and an empty node otherwise which will cause the
9288 // SDIV to be expanded in DAGCombine.
9289 SDValue
9290 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9291                                  SelectionDAG &DAG,
9292                                  SmallVectorImpl<SDNode *> &Created) const {
9293   // TODO: Support SREM
9294   if (N->getOpcode() != ISD::SDIV)
9295     return SDValue();
9296 
9297   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9298   const bool MinSize = ST.hasMinSize();
9299   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9300                                       : ST.hasDivideInARMMode();
9301 
9302   // Don't touch vector types; rewriting this may lead to scalarizing
9303   // the int divs.
9304   if (N->getOperand(0).getValueType().isVector())
9305     return SDValue();
9306 
9307   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9308   // hwdiv support for this to be really profitable.
9309   if (!(MinSize && HasDivide))
9310     return SDValue();
9311 
9312   // ARM mode is a bit simpler than Thumb: we can handle large power
9313   // of 2 immediates with 1 mov instruction; no further checks required,
9314   // just return the sdiv node.
9315   if (!ST.isThumb())
9316     return SDValue(N, 0);
9317 
9318   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9319   // and thus lose the code size benefits of a MOVS that requires only 2.
9320   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9321   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9322   if (Divisor.sgt(128))
9323     return SDValue();
9324 
9325   return SDValue(N, 0);
9326 }
9327 
9328 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9329                                             bool Signed) const {
9330   assert(Op.getValueType() == MVT::i32 &&
9331          "unexpected type for custom lowering DIV");
9332   SDLoc dl(Op);
9333 
9334   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9335                                DAG.getEntryNode(), Op.getOperand(1));
9336 
9337   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9338 }
9339 
9340 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9341   SDLoc DL(N);
9342   SDValue Op = N->getOperand(1);
9343   if (N->getValueType(0) == MVT::i32)
9344     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9345   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9346                            DAG.getConstant(0, DL, MVT::i32));
9347   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9348                            DAG.getConstant(1, DL, MVT::i32));
9349   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9350                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9351 }
9352 
9353 void ARMTargetLowering::ExpandDIV_Windows(
9354     SDValue Op, SelectionDAG &DAG, bool Signed,
9355     SmallVectorImpl<SDValue> &Results) const {
9356   const auto &DL = DAG.getDataLayout();
9357   const auto &TLI = DAG.getTargetLoweringInfo();
9358 
9359   assert(Op.getValueType() == MVT::i64 &&
9360          "unexpected type for custom lowering DIV");
9361   SDLoc dl(Op);
9362 
9363   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9364 
9365   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9366 
9367   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9368   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9369                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9370   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9371 
9372   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9373 }
9374 
9375 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9376   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9377   EVT MemVT = LD->getMemoryVT();
9378   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9379          "Expected a predicate type!");
9380   assert(MemVT == Op.getValueType());
9381   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9382          "Expected a non-extending load");
9383   assert(LD->isUnindexed() && "Expected a unindexed load");
9384 
9385   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9386   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9387   // need to make sure that 8/4 bits are actually loaded into the correct
9388   // place, which means loading the value and then shuffling the values into
9389   // the bottom bits of the predicate.
9390   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9391   // for BE).
9392 
9393   SDLoc dl(Op);
9394   SDValue Load = DAG.getExtLoad(
9395       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9396       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9397       LD->getMemOperand());
9398   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9399   if (MemVT != MVT::v16i1)
9400     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9401                        DAG.getConstant(0, dl, MVT::i32));
9402   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9403 }
9404 
9405 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9406                                   SelectionDAG &DAG) const {
9407   LoadSDNode *LD = cast<LoadSDNode>(N);
9408   EVT MemVT = LD->getMemoryVT();
9409   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9410 
9411   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9412       !Subtarget->isThumb1Only() && LD->isVolatile()) {
9413     SDLoc dl(N);
9414     SDValue Result = DAG.getMemIntrinsicNode(
9415         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9416         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9417     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9418     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9419     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9420     Results.append({Pair, Result.getValue(2)});
9421   }
9422 }
9423 
9424 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9425   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9426   EVT MemVT = ST->getMemoryVT();
9427   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9428          "Expected a predicate type!");
9429   assert(MemVT == ST->getValue().getValueType());
9430   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9431   assert(ST->isUnindexed() && "Expected a unindexed store");
9432 
9433   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9434   // unset and a scalar store.
9435   SDLoc dl(Op);
9436   SDValue Build = ST->getValue();
9437   if (MemVT != MVT::v16i1) {
9438     SmallVector<SDValue, 16> Ops;
9439     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9440       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9441                                 DAG.getConstant(I, dl, MVT::i32)));
9442     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9443       Ops.push_back(DAG.getUNDEF(MVT::i32));
9444     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9445   }
9446   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9447   return DAG.getTruncStore(
9448       ST->getChain(), dl, GRP, ST->getBasePtr(),
9449       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9450       ST->getMemOperand());
9451 }
9452 
9453 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9454                           const ARMSubtarget *Subtarget) {
9455   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9456   EVT MemVT = ST->getMemoryVT();
9457   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9458 
9459   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9460       !Subtarget->isThumb1Only() && ST->isVolatile()) {
9461     SDNode *N = Op.getNode();
9462     SDLoc dl(N);
9463 
9464     SDValue Lo = DAG.getNode(
9465         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9466         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9467                               MVT::i32));
9468     SDValue Hi = DAG.getNode(
9469         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9470         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9471                               MVT::i32));
9472 
9473     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9474                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9475                                    MemVT, ST->getMemOperand());
9476   } else if (Subtarget->hasMVEIntegerOps() &&
9477              ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9478                MemVT == MVT::v16i1))) {
9479     return LowerPredicateStore(Op, DAG);
9480   }
9481 
9482   return SDValue();
9483 }
9484 
9485 static bool isZeroVector(SDValue N) {
9486   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9487           (N->getOpcode() == ARMISD::VMOVIMM &&
9488            isNullConstant(N->getOperand(0))));
9489 }
9490 
9491 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9492   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9493   MVT VT = Op.getSimpleValueType();
9494   SDValue Mask = N->getMask();
9495   SDValue PassThru = N->getPassThru();
9496   SDLoc dl(Op);
9497 
9498   if (isZeroVector(PassThru))
9499     return Op;
9500 
9501   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9502   // zero too, and other values are lowered to a select.
9503   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9504                                 DAG.getTargetConstant(0, dl, MVT::i32));
9505   SDValue NewLoad = DAG.getMaskedLoad(
9506       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9507       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9508       N->getExtensionType(), N->isExpandingLoad());
9509   SDValue Combo = NewLoad;
9510   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9511                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9512                             isZeroVector(PassThru->getOperand(0));
9513   if (!PassThru.isUndef() && !PassThruIsCastZero)
9514     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9515   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9516 }
9517 
9518 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
9519                               const ARMSubtarget *ST) {
9520   if (!ST->hasMVEIntegerOps())
9521     return SDValue();
9522 
9523   SDLoc dl(Op);
9524   unsigned BaseOpcode = 0;
9525   switch (Op->getOpcode()) {
9526   default: llvm_unreachable("Expected VECREDUCE opcode");
9527   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
9528   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
9529   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
9530   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
9531   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
9532   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
9533   case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
9534   case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
9535   }
9536 
9537   SDValue Op0 = Op->getOperand(0);
9538   EVT VT = Op0.getValueType();
9539   EVT EltVT = VT.getVectorElementType();
9540   unsigned NumElts = VT.getVectorNumElements();
9541   unsigned NumActiveLanes = NumElts;
9542 
9543   assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
9544           NumActiveLanes == 2) &&
9545          "Only expected a power 2 vector size");
9546 
9547   // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
9548   // allows us to easily extract vector elements from the lanes.
9549   while (NumActiveLanes > 4) {
9550     unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
9551     SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
9552     Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
9553     NumActiveLanes /= 2;
9554   }
9555 
9556   SDValue Res;
9557   if (NumActiveLanes == 4) {
9558     // The remaining 4 elements are summed sequentially
9559     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9560                               DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
9561     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9562                               DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
9563     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9564                               DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
9565     SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9566                               DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
9567     SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9568     SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
9569     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
9570   } else {
9571     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9572                               DAG.getConstant(0, dl, MVT::i32));
9573     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9574                               DAG.getConstant(1, dl, MVT::i32));
9575     Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9576   }
9577 
9578   // Result type may be wider than element type.
9579   if (EltVT != Op->getValueType(0))
9580     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
9581   return Res;
9582 }
9583 
9584 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
9585                                const ARMSubtarget *ST) {
9586   if (!ST->hasMVEFloatOps())
9587     return SDValue();
9588   return LowerVecReduce(Op, DAG, ST);
9589 }
9590 
9591 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9592   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9593     // Acquire/Release load/store is not legal for targets without a dmb or
9594     // equivalent available.
9595     return SDValue();
9596 
9597   // Monotonic load/store is legal for all targets.
9598   return Op;
9599 }
9600 
9601 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9602                                     SmallVectorImpl<SDValue> &Results,
9603                                     SelectionDAG &DAG,
9604                                     const ARMSubtarget *Subtarget) {
9605   SDLoc DL(N);
9606   // Under Power Management extensions, the cycle-count is:
9607   //    mrc p15, #0, <Rt>, c9, c13, #0
9608   SDValue Ops[] = { N->getOperand(0), // Chain
9609                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9610                     DAG.getTargetConstant(15, DL, MVT::i32),
9611                     DAG.getTargetConstant(0, DL, MVT::i32),
9612                     DAG.getTargetConstant(9, DL, MVT::i32),
9613                     DAG.getTargetConstant(13, DL, MVT::i32),
9614                     DAG.getTargetConstant(0, DL, MVT::i32)
9615   };
9616 
9617   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9618                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9619   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9620                                 DAG.getConstant(0, DL, MVT::i32)));
9621   Results.push_back(Cycles32.getValue(1));
9622 }
9623 
9624 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9625   SDLoc dl(V.getNode());
9626   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9627   SDValue VHi = DAG.getAnyExtOrTrunc(
9628       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9629       dl, MVT::i32);
9630   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9631   if (isBigEndian)
9632     std::swap (VLo, VHi);
9633   SDValue RegClass =
9634       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9635   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9636   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9637   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9638   return SDValue(
9639       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9640 }
9641 
9642 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9643                                        SmallVectorImpl<SDValue> & Results,
9644                                        SelectionDAG &DAG) {
9645   assert(N->getValueType(0) == MVT::i64 &&
9646          "AtomicCmpSwap on types less than 64 should be legal");
9647   SDValue Ops[] = {N->getOperand(1),
9648                    createGPRPairNode(DAG, N->getOperand(2)),
9649                    createGPRPairNode(DAG, N->getOperand(3)),
9650                    N->getOperand(0)};
9651   SDNode *CmpSwap = DAG.getMachineNode(
9652       ARM::CMP_SWAP_64, SDLoc(N),
9653       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9654 
9655   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9656   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9657 
9658   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9659 
9660   SDValue Lo =
9661       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9662                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9663   SDValue Hi =
9664       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9665                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9666   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9667   Results.push_back(SDValue(CmpSwap, 2));
9668 }
9669 
9670 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9671   SDLoc dl(Op);
9672   EVT VT = Op.getValueType();
9673   SDValue Chain = Op.getOperand(0);
9674   SDValue LHS = Op.getOperand(1);
9675   SDValue RHS = Op.getOperand(2);
9676   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9677   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9678 
9679   // If we don't have instructions of this float type then soften to a libcall
9680   // and use SETCC instead.
9681   if (isUnsupportedFloatingType(LHS.getValueType())) {
9682     DAG.getTargetLoweringInfo().softenSetCCOperands(
9683       DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9684     if (!RHS.getNode()) {
9685       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9686       CC = ISD::SETNE;
9687     }
9688     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9689                                  DAG.getCondCode(CC));
9690     return DAG.getMergeValues({Result, Chain}, dl);
9691   }
9692 
9693   ARMCC::CondCodes CondCode, CondCode2;
9694   FPCCToARMCC(CC, CondCode, CondCode2);
9695 
9696   // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9697   // in CMPFP and CMPFPE, but instead it should be made explicit by these
9698   // instructions using a chain instead of glue. This would also fix the problem
9699   // here (and also in LowerSELECT_CC) where we generate two comparisons when
9700   // CondCode2 != AL.
9701   SDValue True = DAG.getConstant(1, dl, VT);
9702   SDValue False =  DAG.getConstant(0, dl, VT);
9703   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9704   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9705   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9706   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9707   if (CondCode2 != ARMCC::AL) {
9708     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9709     Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9710     Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9711   }
9712   return DAG.getMergeValues({Result, Chain}, dl);
9713 }
9714 
9715 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9716   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9717   switch (Op.getOpcode()) {
9718   default: llvm_unreachable("Don't know how to custom lower this!");
9719   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9720   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9721   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9722   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9723   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9724   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9725   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9726   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9727   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9728   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9729   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9730   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9731   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9732   case ISD::SINT_TO_FP:
9733   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9734   case ISD::STRICT_FP_TO_SINT:
9735   case ISD::STRICT_FP_TO_UINT:
9736   case ISD::FP_TO_SINT:
9737   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9738   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9739   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9740   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9741   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9742   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9743   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9744   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9745   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9746                                                                Subtarget);
9747   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9748   case ISD::SHL:
9749   case ISD::SRL:
9750   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9751   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9752   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9753   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9754   case ISD::SRL_PARTS:
9755   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9756   case ISD::CTTZ:
9757   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9758   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9759   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9760   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9761   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9762   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9763   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9764   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9765   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9766   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9767   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9768   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9769   case ISD::MUL:           return LowerMUL(Op, DAG);
9770   case ISD::SDIV:
9771     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9772       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9773     return LowerSDIV(Op, DAG, Subtarget);
9774   case ISD::UDIV:
9775     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9776       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9777     return LowerUDIV(Op, DAG, Subtarget);
9778   case ISD::ADDCARRY:
9779   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9780   case ISD::SADDO:
9781   case ISD::SSUBO:
9782     return LowerSignedALUO(Op, DAG);
9783   case ISD::UADDO:
9784   case ISD::USUBO:
9785     return LowerUnsignedALUO(Op, DAG);
9786   case ISD::SADDSAT:
9787   case ISD::SSUBSAT:
9788     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9789   case ISD::LOAD:
9790     return LowerPredicateLoad(Op, DAG);
9791   case ISD::STORE:
9792     return LowerSTORE(Op, DAG, Subtarget);
9793   case ISD::MLOAD:
9794     return LowerMLOAD(Op, DAG);
9795   case ISD::VECREDUCE_MUL:
9796   case ISD::VECREDUCE_AND:
9797   case ISD::VECREDUCE_OR:
9798   case ISD::VECREDUCE_XOR:
9799     return LowerVecReduce(Op, DAG, Subtarget);
9800   case ISD::VECREDUCE_FADD:
9801   case ISD::VECREDUCE_FMUL:
9802   case ISD::VECREDUCE_FMIN:
9803   case ISD::VECREDUCE_FMAX:
9804     return LowerVecReduceF(Op, DAG, Subtarget);
9805   case ISD::ATOMIC_LOAD:
9806   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9807   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9808   case ISD::SDIVREM:
9809   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9810   case ISD::DYNAMIC_STACKALLOC:
9811     if (Subtarget->isTargetWindows())
9812       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9813     llvm_unreachable("Don't know how to custom lower this!");
9814   case ISD::STRICT_FP_ROUND:
9815   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9816   case ISD::STRICT_FP_EXTEND:
9817   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9818   case ISD::STRICT_FSETCC:
9819   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9820   case ARMISD::WIN__DBZCHK: return SDValue();
9821   }
9822 }
9823 
9824 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9825                                  SelectionDAG &DAG) {
9826   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9827   unsigned Opc = 0;
9828   if (IntNo == Intrinsic::arm_smlald)
9829     Opc = ARMISD::SMLALD;
9830   else if (IntNo == Intrinsic::arm_smlaldx)
9831     Opc = ARMISD::SMLALDX;
9832   else if (IntNo == Intrinsic::arm_smlsld)
9833     Opc = ARMISD::SMLSLD;
9834   else if (IntNo == Intrinsic::arm_smlsldx)
9835     Opc = ARMISD::SMLSLDX;
9836   else
9837     return;
9838 
9839   SDLoc dl(N);
9840   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9841                            N->getOperand(3),
9842                            DAG.getConstant(0, dl, MVT::i32));
9843   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9844                            N->getOperand(3),
9845                            DAG.getConstant(1, dl, MVT::i32));
9846 
9847   SDValue LongMul = DAG.getNode(Opc, dl,
9848                                 DAG.getVTList(MVT::i32, MVT::i32),
9849                                 N->getOperand(1), N->getOperand(2),
9850                                 Lo, Hi);
9851   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9852                                 LongMul.getValue(0), LongMul.getValue(1)));
9853 }
9854 
9855 /// ReplaceNodeResults - Replace the results of node with an illegal result
9856 /// type with new values built out of custom code.
9857 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9858                                            SmallVectorImpl<SDValue> &Results,
9859                                            SelectionDAG &DAG) const {
9860   SDValue Res;
9861   switch (N->getOpcode()) {
9862   default:
9863     llvm_unreachable("Don't know how to custom expand this!");
9864   case ISD::READ_REGISTER:
9865     ExpandREAD_REGISTER(N, Results, DAG);
9866     break;
9867   case ISD::BITCAST:
9868     Res = ExpandBITCAST(N, DAG, Subtarget);
9869     break;
9870   case ISD::SRL:
9871   case ISD::SRA:
9872   case ISD::SHL:
9873     Res = Expand64BitShift(N, DAG, Subtarget);
9874     break;
9875   case ISD::SREM:
9876   case ISD::UREM:
9877     Res = LowerREM(N, DAG);
9878     break;
9879   case ISD::SDIVREM:
9880   case ISD::UDIVREM:
9881     Res = LowerDivRem(SDValue(N, 0), DAG);
9882     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9883     Results.push_back(Res.getValue(0));
9884     Results.push_back(Res.getValue(1));
9885     return;
9886   case ISD::SADDSAT:
9887   case ISD::SSUBSAT:
9888     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9889     break;
9890   case ISD::READCYCLECOUNTER:
9891     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9892     return;
9893   case ISD::UDIV:
9894   case ISD::SDIV:
9895     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9896     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9897                              Results);
9898   case ISD::ATOMIC_CMP_SWAP:
9899     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9900     return;
9901   case ISD::INTRINSIC_WO_CHAIN:
9902     return ReplaceLongIntrinsic(N, Results, DAG);
9903   case ISD::ABS:
9904      lowerABS(N, Results, DAG);
9905      return ;
9906   case ISD::LOAD:
9907     LowerLOAD(N, Results, DAG);
9908     break;
9909   }
9910   if (Res.getNode())
9911     Results.push_back(Res);
9912 }
9913 
9914 //===----------------------------------------------------------------------===//
9915 //                           ARM Scheduler Hooks
9916 //===----------------------------------------------------------------------===//
9917 
9918 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9919 /// registers the function context.
9920 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9921                                                MachineBasicBlock *MBB,
9922                                                MachineBasicBlock *DispatchBB,
9923                                                int FI) const {
9924   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9925          "ROPI/RWPI not currently supported with SjLj");
9926   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9927   DebugLoc dl = MI.getDebugLoc();
9928   MachineFunction *MF = MBB->getParent();
9929   MachineRegisterInfo *MRI = &MF->getRegInfo();
9930   MachineConstantPool *MCP = MF->getConstantPool();
9931   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9932   const Function &F = MF->getFunction();
9933 
9934   bool isThumb = Subtarget->isThumb();
9935   bool isThumb2 = Subtarget->isThumb2();
9936 
9937   unsigned PCLabelId = AFI->createPICLabelUId();
9938   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9939   ARMConstantPoolValue *CPV =
9940     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9941   unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
9942 
9943   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9944                                            : &ARM::GPRRegClass;
9945 
9946   // Grab constant pool and fixed stack memory operands.
9947   MachineMemOperand *CPMMO =
9948       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9949                                MachineMemOperand::MOLoad, 4, Align(4));
9950 
9951   MachineMemOperand *FIMMOSt =
9952       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9953                                MachineMemOperand::MOStore, 4, Align(4));
9954 
9955   // Load the address of the dispatch MBB into the jump buffer.
9956   if (isThumb2) {
9957     // Incoming value: jbuf
9958     //   ldr.n  r5, LCPI1_1
9959     //   orr    r5, r5, #1
9960     //   add    r5, pc
9961     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9962     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9963     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9964         .addConstantPoolIndex(CPI)
9965         .addMemOperand(CPMMO)
9966         .add(predOps(ARMCC::AL));
9967     // Set the low bit because of thumb mode.
9968     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9969     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9970         .addReg(NewVReg1, RegState::Kill)
9971         .addImm(0x01)
9972         .add(predOps(ARMCC::AL))
9973         .add(condCodeOp());
9974     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9975     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9976       .addReg(NewVReg2, RegState::Kill)
9977       .addImm(PCLabelId);
9978     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9979         .addReg(NewVReg3, RegState::Kill)
9980         .addFrameIndex(FI)
9981         .addImm(36) // &jbuf[1] :: pc
9982         .addMemOperand(FIMMOSt)
9983         .add(predOps(ARMCC::AL));
9984   } else if (isThumb) {
9985     // Incoming value: jbuf
9986     //   ldr.n  r1, LCPI1_4
9987     //   add    r1, pc
9988     //   mov    r2, #1
9989     //   orrs   r1, r2
9990     //   add    r2, $jbuf, #+4 ; &jbuf[1]
9991     //   str    r1, [r2]
9992     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9993     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9994         .addConstantPoolIndex(CPI)
9995         .addMemOperand(CPMMO)
9996         .add(predOps(ARMCC::AL));
9997     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9998     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9999       .addReg(NewVReg1, RegState::Kill)
10000       .addImm(PCLabelId);
10001     // Set the low bit because of thumb mode.
10002     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10003     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
10004         .addReg(ARM::CPSR, RegState::Define)
10005         .addImm(1)
10006         .add(predOps(ARMCC::AL));
10007     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10008     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10009         .addReg(ARM::CPSR, RegState::Define)
10010         .addReg(NewVReg2, RegState::Kill)
10011         .addReg(NewVReg3, RegState::Kill)
10012         .add(predOps(ARMCC::AL));
10013     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10014     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10015             .addFrameIndex(FI)
10016             .addImm(36); // &jbuf[1] :: pc
10017     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10018         .addReg(NewVReg4, RegState::Kill)
10019         .addReg(NewVReg5, RegState::Kill)
10020         .addImm(0)
10021         .addMemOperand(FIMMOSt)
10022         .add(predOps(ARMCC::AL));
10023   } else {
10024     // Incoming value: jbuf
10025     //   ldr  r1, LCPI1_1
10026     //   add  r1, pc, r1
10027     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
10028     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10029     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10030         .addConstantPoolIndex(CPI)
10031         .addImm(0)
10032         .addMemOperand(CPMMO)
10033         .add(predOps(ARMCC::AL));
10034     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10035     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10036         .addReg(NewVReg1, RegState::Kill)
10037         .addImm(PCLabelId)
10038         .add(predOps(ARMCC::AL));
10039     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10040         .addReg(NewVReg2, RegState::Kill)
10041         .addFrameIndex(FI)
10042         .addImm(36) // &jbuf[1] :: pc
10043         .addMemOperand(FIMMOSt)
10044         .add(predOps(ARMCC::AL));
10045   }
10046 }
10047 
10048 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10049                                               MachineBasicBlock *MBB) const {
10050   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10051   DebugLoc dl = MI.getDebugLoc();
10052   MachineFunction *MF = MBB->getParent();
10053   MachineRegisterInfo *MRI = &MF->getRegInfo();
10054   MachineFrameInfo &MFI = MF->getFrameInfo();
10055   int FI = MFI.getFunctionContextIndex();
10056 
10057   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10058                                                         : &ARM::GPRnopcRegClass;
10059 
10060   // Get a mapping of the call site numbers to all of the landing pads they're
10061   // associated with.
10062   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10063   unsigned MaxCSNum = 0;
10064   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
10065        ++BB) {
10066     if (!BB->isEHPad()) continue;
10067 
10068     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10069     // pad.
10070     for (MachineBasicBlock::iterator
10071            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
10072       if (!II->isEHLabel()) continue;
10073 
10074       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
10075       if (!MF->hasCallSiteLandingPad(Sym)) continue;
10076 
10077       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10078       for (SmallVectorImpl<unsigned>::iterator
10079              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
10080            CSI != CSE; ++CSI) {
10081         CallSiteNumToLPad[*CSI].push_back(&*BB);
10082         MaxCSNum = std::max(MaxCSNum, *CSI);
10083       }
10084       break;
10085     }
10086   }
10087 
10088   // Get an ordered list of the machine basic blocks for the jump table.
10089   std::vector<MachineBasicBlock*> LPadList;
10090   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10091   LPadList.reserve(CallSiteNumToLPad.size());
10092   for (unsigned I = 1; I <= MaxCSNum; ++I) {
10093     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10094     for (SmallVectorImpl<MachineBasicBlock*>::iterator
10095            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
10096       LPadList.push_back(*II);
10097       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
10098     }
10099   }
10100 
10101   assert(!LPadList.empty() &&
10102          "No landing pad destinations for the dispatch jump table!");
10103 
10104   // Create the jump table and associated information.
10105   MachineJumpTableInfo *JTI =
10106     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10107   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10108 
10109   // Create the MBBs for the dispatch code.
10110 
10111   // Shove the dispatch's address into the return slot in the function context.
10112   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10113   DispatchBB->setIsEHPad();
10114 
10115   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10116   unsigned trap_opcode;
10117   if (Subtarget->isThumb())
10118     trap_opcode = ARM::tTRAP;
10119   else
10120     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10121 
10122   BuildMI(TrapBB, dl, TII->get(trap_opcode));
10123   DispatchBB->addSuccessor(TrapBB);
10124 
10125   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10126   DispatchBB->addSuccessor(DispContBB);
10127 
10128   // Insert and MBBs.
10129   MF->insert(MF->end(), DispatchBB);
10130   MF->insert(MF->end(), DispContBB);
10131   MF->insert(MF->end(), TrapBB);
10132 
10133   // Insert code into the entry block that creates and registers the function
10134   // context.
10135   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10136 
10137   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10138       MachinePointerInfo::getFixedStack(*MF, FI),
10139       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10140 
10141   MachineInstrBuilder MIB;
10142   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10143 
10144   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10145   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10146 
10147   // Add a register mask with no preserved registers.  This results in all
10148   // registers being marked as clobbered. This can't work if the dispatch block
10149   // is in a Thumb1 function and is linked with ARM code which uses the FP
10150   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10151   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10152 
10153   bool IsPositionIndependent = isPositionIndependent();
10154   unsigned NumLPads = LPadList.size();
10155   if (Subtarget->isThumb2()) {
10156     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10157     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10158         .addFrameIndex(FI)
10159         .addImm(4)
10160         .addMemOperand(FIMMOLd)
10161         .add(predOps(ARMCC::AL));
10162 
10163     if (NumLPads < 256) {
10164       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10165           .addReg(NewVReg1)
10166           .addImm(LPadList.size())
10167           .add(predOps(ARMCC::AL));
10168     } else {
10169       Register VReg1 = MRI->createVirtualRegister(TRC);
10170       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10171           .addImm(NumLPads & 0xFFFF)
10172           .add(predOps(ARMCC::AL));
10173 
10174       unsigned VReg2 = VReg1;
10175       if ((NumLPads & 0xFFFF0000) != 0) {
10176         VReg2 = MRI->createVirtualRegister(TRC);
10177         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10178             .addReg(VReg1)
10179             .addImm(NumLPads >> 16)
10180             .add(predOps(ARMCC::AL));
10181       }
10182 
10183       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10184           .addReg(NewVReg1)
10185           .addReg(VReg2)
10186           .add(predOps(ARMCC::AL));
10187     }
10188 
10189     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10190       .addMBB(TrapBB)
10191       .addImm(ARMCC::HI)
10192       .addReg(ARM::CPSR);
10193 
10194     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10195     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10196         .addJumpTableIndex(MJTI)
10197         .add(predOps(ARMCC::AL));
10198 
10199     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10200     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10201         .addReg(NewVReg3, RegState::Kill)
10202         .addReg(NewVReg1)
10203         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10204         .add(predOps(ARMCC::AL))
10205         .add(condCodeOp());
10206 
10207     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10208       .addReg(NewVReg4, RegState::Kill)
10209       .addReg(NewVReg1)
10210       .addJumpTableIndex(MJTI);
10211   } else if (Subtarget->isThumb()) {
10212     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10213     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10214         .addFrameIndex(FI)
10215         .addImm(1)
10216         .addMemOperand(FIMMOLd)
10217         .add(predOps(ARMCC::AL));
10218 
10219     if (NumLPads < 256) {
10220       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10221           .addReg(NewVReg1)
10222           .addImm(NumLPads)
10223           .add(predOps(ARMCC::AL));
10224     } else {
10225       MachineConstantPool *ConstantPool = MF->getConstantPool();
10226       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10227       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10228 
10229       // MachineConstantPool wants an explicit alignment.
10230       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10231       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10232 
10233       Register VReg1 = MRI->createVirtualRegister(TRC);
10234       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10235           .addReg(VReg1, RegState::Define)
10236           .addConstantPoolIndex(Idx)
10237           .add(predOps(ARMCC::AL));
10238       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10239           .addReg(NewVReg1)
10240           .addReg(VReg1)
10241           .add(predOps(ARMCC::AL));
10242     }
10243 
10244     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10245       .addMBB(TrapBB)
10246       .addImm(ARMCC::HI)
10247       .addReg(ARM::CPSR);
10248 
10249     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10250     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10251         .addReg(ARM::CPSR, RegState::Define)
10252         .addReg(NewVReg1)
10253         .addImm(2)
10254         .add(predOps(ARMCC::AL));
10255 
10256     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10257     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10258         .addJumpTableIndex(MJTI)
10259         .add(predOps(ARMCC::AL));
10260 
10261     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10262     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10263         .addReg(ARM::CPSR, RegState::Define)
10264         .addReg(NewVReg2, RegState::Kill)
10265         .addReg(NewVReg3)
10266         .add(predOps(ARMCC::AL));
10267 
10268     MachineMemOperand *JTMMOLd =
10269         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10270                                  MachineMemOperand::MOLoad, 4, Align(4));
10271 
10272     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10273     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10274         .addReg(NewVReg4, RegState::Kill)
10275         .addImm(0)
10276         .addMemOperand(JTMMOLd)
10277         .add(predOps(ARMCC::AL));
10278 
10279     unsigned NewVReg6 = NewVReg5;
10280     if (IsPositionIndependent) {
10281       NewVReg6 = MRI->createVirtualRegister(TRC);
10282       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10283           .addReg(ARM::CPSR, RegState::Define)
10284           .addReg(NewVReg5, RegState::Kill)
10285           .addReg(NewVReg3)
10286           .add(predOps(ARMCC::AL));
10287     }
10288 
10289     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10290       .addReg(NewVReg6, RegState::Kill)
10291       .addJumpTableIndex(MJTI);
10292   } else {
10293     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10294     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10295         .addFrameIndex(FI)
10296         .addImm(4)
10297         .addMemOperand(FIMMOLd)
10298         .add(predOps(ARMCC::AL));
10299 
10300     if (NumLPads < 256) {
10301       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10302           .addReg(NewVReg1)
10303           .addImm(NumLPads)
10304           .add(predOps(ARMCC::AL));
10305     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10306       Register VReg1 = MRI->createVirtualRegister(TRC);
10307       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10308           .addImm(NumLPads & 0xFFFF)
10309           .add(predOps(ARMCC::AL));
10310 
10311       unsigned VReg2 = VReg1;
10312       if ((NumLPads & 0xFFFF0000) != 0) {
10313         VReg2 = MRI->createVirtualRegister(TRC);
10314         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10315             .addReg(VReg1)
10316             .addImm(NumLPads >> 16)
10317             .add(predOps(ARMCC::AL));
10318       }
10319 
10320       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10321           .addReg(NewVReg1)
10322           .addReg(VReg2)
10323           .add(predOps(ARMCC::AL));
10324     } else {
10325       MachineConstantPool *ConstantPool = MF->getConstantPool();
10326       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10327       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10328 
10329       // MachineConstantPool wants an explicit alignment.
10330       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10331       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10332 
10333       Register VReg1 = MRI->createVirtualRegister(TRC);
10334       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10335           .addReg(VReg1, RegState::Define)
10336           .addConstantPoolIndex(Idx)
10337           .addImm(0)
10338           .add(predOps(ARMCC::AL));
10339       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10340           .addReg(NewVReg1)
10341           .addReg(VReg1, RegState::Kill)
10342           .add(predOps(ARMCC::AL));
10343     }
10344 
10345     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10346       .addMBB(TrapBB)
10347       .addImm(ARMCC::HI)
10348       .addReg(ARM::CPSR);
10349 
10350     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10351     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10352         .addReg(NewVReg1)
10353         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10354         .add(predOps(ARMCC::AL))
10355         .add(condCodeOp());
10356     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10357     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10358         .addJumpTableIndex(MJTI)
10359         .add(predOps(ARMCC::AL));
10360 
10361     MachineMemOperand *JTMMOLd =
10362         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10363                                  MachineMemOperand::MOLoad, 4, Align(4));
10364     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10365     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10366         .addReg(NewVReg3, RegState::Kill)
10367         .addReg(NewVReg4)
10368         .addImm(0)
10369         .addMemOperand(JTMMOLd)
10370         .add(predOps(ARMCC::AL));
10371 
10372     if (IsPositionIndependent) {
10373       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10374         .addReg(NewVReg5, RegState::Kill)
10375         .addReg(NewVReg4)
10376         .addJumpTableIndex(MJTI);
10377     } else {
10378       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10379         .addReg(NewVReg5, RegState::Kill)
10380         .addJumpTableIndex(MJTI);
10381     }
10382   }
10383 
10384   // Add the jump table entries as successors to the MBB.
10385   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10386   for (std::vector<MachineBasicBlock*>::iterator
10387          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10388     MachineBasicBlock *CurMBB = *I;
10389     if (SeenMBBs.insert(CurMBB).second)
10390       DispContBB->addSuccessor(CurMBB);
10391   }
10392 
10393   // N.B. the order the invoke BBs are processed in doesn't matter here.
10394   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10395   SmallVector<MachineBasicBlock*, 64> MBBLPads;
10396   for (MachineBasicBlock *BB : InvokeBBs) {
10397 
10398     // Remove the landing pad successor from the invoke block and replace it
10399     // with the new dispatch block.
10400     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
10401                                                   BB->succ_end());
10402     while (!Successors.empty()) {
10403       MachineBasicBlock *SMBB = Successors.pop_back_val();
10404       if (SMBB->isEHPad()) {
10405         BB->removeSuccessor(SMBB);
10406         MBBLPads.push_back(SMBB);
10407       }
10408     }
10409 
10410     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10411     BB->normalizeSuccProbs();
10412 
10413     // Find the invoke call and mark all of the callee-saved registers as
10414     // 'implicit defined' so that they're spilled. This prevents code from
10415     // moving instructions to before the EH block, where they will never be
10416     // executed.
10417     for (MachineBasicBlock::reverse_iterator
10418            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10419       if (!II->isCall()) continue;
10420 
10421       DenseMap<unsigned, bool> DefRegs;
10422       for (MachineInstr::mop_iterator
10423              OI = II->operands_begin(), OE = II->operands_end();
10424            OI != OE; ++OI) {
10425         if (!OI->isReg()) continue;
10426         DefRegs[OI->getReg()] = true;
10427       }
10428 
10429       MachineInstrBuilder MIB(*MF, &*II);
10430 
10431       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10432         unsigned Reg = SavedRegs[i];
10433         if (Subtarget->isThumb2() &&
10434             !ARM::tGPRRegClass.contains(Reg) &&
10435             !ARM::hGPRRegClass.contains(Reg))
10436           continue;
10437         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10438           continue;
10439         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10440           continue;
10441         if (!DefRegs[Reg])
10442           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10443       }
10444 
10445       break;
10446     }
10447   }
10448 
10449   // Mark all former landing pads as non-landing pads. The dispatch is the only
10450   // landing pad now.
10451   for (SmallVectorImpl<MachineBasicBlock*>::iterator
10452          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10453     (*I)->setIsEHPad(false);
10454 
10455   // The instruction is gone now.
10456   MI.eraseFromParent();
10457 }
10458 
10459 static
10460 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10461   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10462        E = MBB->succ_end(); I != E; ++I)
10463     if (*I != Succ)
10464       return *I;
10465   llvm_unreachable("Expecting a BB with two successors!");
10466 }
10467 
10468 /// Return the load opcode for a given load size. If load size >= 8,
10469 /// neon opcode will be returned.
10470 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10471   if (LdSize >= 8)
10472     return LdSize == 16 ? ARM::VLD1q32wb_fixed
10473                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10474   if (IsThumb1)
10475     return LdSize == 4 ? ARM::tLDRi
10476                        : LdSize == 2 ? ARM::tLDRHi
10477                                      : LdSize == 1 ? ARM::tLDRBi : 0;
10478   if (IsThumb2)
10479     return LdSize == 4 ? ARM::t2LDR_POST
10480                        : LdSize == 2 ? ARM::t2LDRH_POST
10481                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10482   return LdSize == 4 ? ARM::LDR_POST_IMM
10483                      : LdSize == 2 ? ARM::LDRH_POST
10484                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10485 }
10486 
10487 /// Return the store opcode for a given store size. If store size >= 8,
10488 /// neon opcode will be returned.
10489 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10490   if (StSize >= 8)
10491     return StSize == 16 ? ARM::VST1q32wb_fixed
10492                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10493   if (IsThumb1)
10494     return StSize == 4 ? ARM::tSTRi
10495                        : StSize == 2 ? ARM::tSTRHi
10496                                      : StSize == 1 ? ARM::tSTRBi : 0;
10497   if (IsThumb2)
10498     return StSize == 4 ? ARM::t2STR_POST
10499                        : StSize == 2 ? ARM::t2STRH_POST
10500                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
10501   return StSize == 4 ? ARM::STR_POST_IMM
10502                      : StSize == 2 ? ARM::STRH_POST
10503                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10504 }
10505 
10506 /// Emit a post-increment load operation with given size. The instructions
10507 /// will be added to BB at Pos.
10508 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10509                        const TargetInstrInfo *TII, const DebugLoc &dl,
10510                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10511                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10512   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10513   assert(LdOpc != 0 && "Should have a load opcode");
10514   if (LdSize >= 8) {
10515     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10516         .addReg(AddrOut, RegState::Define)
10517         .addReg(AddrIn)
10518         .addImm(0)
10519         .add(predOps(ARMCC::AL));
10520   } else if (IsThumb1) {
10521     // load + update AddrIn
10522     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10523         .addReg(AddrIn)
10524         .addImm(0)
10525         .add(predOps(ARMCC::AL));
10526     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10527         .add(t1CondCodeOp())
10528         .addReg(AddrIn)
10529         .addImm(LdSize)
10530         .add(predOps(ARMCC::AL));
10531   } else if (IsThumb2) {
10532     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10533         .addReg(AddrOut, RegState::Define)
10534         .addReg(AddrIn)
10535         .addImm(LdSize)
10536         .add(predOps(ARMCC::AL));
10537   } else { // arm
10538     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10539         .addReg(AddrOut, RegState::Define)
10540         .addReg(AddrIn)
10541         .addReg(0)
10542         .addImm(LdSize)
10543         .add(predOps(ARMCC::AL));
10544   }
10545 }
10546 
10547 /// Emit a post-increment store operation with given size. The instructions
10548 /// will be added to BB at Pos.
10549 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10550                        const TargetInstrInfo *TII, const DebugLoc &dl,
10551                        unsigned StSize, unsigned Data, unsigned AddrIn,
10552                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10553   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10554   assert(StOpc != 0 && "Should have a store opcode");
10555   if (StSize >= 8) {
10556     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10557         .addReg(AddrIn)
10558         .addImm(0)
10559         .addReg(Data)
10560         .add(predOps(ARMCC::AL));
10561   } else if (IsThumb1) {
10562     // store + update AddrIn
10563     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10564         .addReg(Data)
10565         .addReg(AddrIn)
10566         .addImm(0)
10567         .add(predOps(ARMCC::AL));
10568     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10569         .add(t1CondCodeOp())
10570         .addReg(AddrIn)
10571         .addImm(StSize)
10572         .add(predOps(ARMCC::AL));
10573   } else if (IsThumb2) {
10574     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10575         .addReg(Data)
10576         .addReg(AddrIn)
10577         .addImm(StSize)
10578         .add(predOps(ARMCC::AL));
10579   } else { // arm
10580     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10581         .addReg(Data)
10582         .addReg(AddrIn)
10583         .addReg(0)
10584         .addImm(StSize)
10585         .add(predOps(ARMCC::AL));
10586   }
10587 }
10588 
10589 MachineBasicBlock *
10590 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10591                                    MachineBasicBlock *BB) const {
10592   // This pseudo instruction has 3 operands: dst, src, size
10593   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10594   // Otherwise, we will generate unrolled scalar copies.
10595   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10596   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10597   MachineFunction::iterator It = ++BB->getIterator();
10598 
10599   Register dest = MI.getOperand(0).getReg();
10600   Register src = MI.getOperand(1).getReg();
10601   unsigned SizeVal = MI.getOperand(2).getImm();
10602   unsigned Alignment = MI.getOperand(3).getImm();
10603   DebugLoc dl = MI.getDebugLoc();
10604 
10605   MachineFunction *MF = BB->getParent();
10606   MachineRegisterInfo &MRI = MF->getRegInfo();
10607   unsigned UnitSize = 0;
10608   const TargetRegisterClass *TRC = nullptr;
10609   const TargetRegisterClass *VecTRC = nullptr;
10610 
10611   bool IsThumb1 = Subtarget->isThumb1Only();
10612   bool IsThumb2 = Subtarget->isThumb2();
10613   bool IsThumb = Subtarget->isThumb();
10614 
10615   if (Alignment & 1) {
10616     UnitSize = 1;
10617   } else if (Alignment & 2) {
10618     UnitSize = 2;
10619   } else {
10620     // Check whether we can use NEON instructions.
10621     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10622         Subtarget->hasNEON()) {
10623       if ((Alignment % 16 == 0) && SizeVal >= 16)
10624         UnitSize = 16;
10625       else if ((Alignment % 8 == 0) && SizeVal >= 8)
10626         UnitSize = 8;
10627     }
10628     // Can't use NEON instructions.
10629     if (UnitSize == 0)
10630       UnitSize = 4;
10631   }
10632 
10633   // Select the correct opcode and register class for unit size load/store
10634   bool IsNeon = UnitSize >= 8;
10635   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10636   if (IsNeon)
10637     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10638                             : UnitSize == 8 ? &ARM::DPRRegClass
10639                                             : nullptr;
10640 
10641   unsigned BytesLeft = SizeVal % UnitSize;
10642   unsigned LoopSize = SizeVal - BytesLeft;
10643 
10644   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10645     // Use LDR and STR to copy.
10646     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10647     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10648     unsigned srcIn = src;
10649     unsigned destIn = dest;
10650     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10651       Register srcOut = MRI.createVirtualRegister(TRC);
10652       Register destOut = MRI.createVirtualRegister(TRC);
10653       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10654       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10655                  IsThumb1, IsThumb2);
10656       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10657                  IsThumb1, IsThumb2);
10658       srcIn = srcOut;
10659       destIn = destOut;
10660     }
10661 
10662     // Handle the leftover bytes with LDRB and STRB.
10663     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10664     // [destOut] = STRB_POST(scratch, destIn, 1)
10665     for (unsigned i = 0; i < BytesLeft; i++) {
10666       Register srcOut = MRI.createVirtualRegister(TRC);
10667       Register destOut = MRI.createVirtualRegister(TRC);
10668       Register scratch = MRI.createVirtualRegister(TRC);
10669       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10670                  IsThumb1, IsThumb2);
10671       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10672                  IsThumb1, IsThumb2);
10673       srcIn = srcOut;
10674       destIn = destOut;
10675     }
10676     MI.eraseFromParent(); // The instruction is gone now.
10677     return BB;
10678   }
10679 
10680   // Expand the pseudo op to a loop.
10681   // thisMBB:
10682   //   ...
10683   //   movw varEnd, # --> with thumb2
10684   //   movt varEnd, #
10685   //   ldrcp varEnd, idx --> without thumb2
10686   //   fallthrough --> loopMBB
10687   // loopMBB:
10688   //   PHI varPhi, varEnd, varLoop
10689   //   PHI srcPhi, src, srcLoop
10690   //   PHI destPhi, dst, destLoop
10691   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10692   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10693   //   subs varLoop, varPhi, #UnitSize
10694   //   bne loopMBB
10695   //   fallthrough --> exitMBB
10696   // exitMBB:
10697   //   epilogue to handle left-over bytes
10698   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10699   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10700   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10701   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10702   MF->insert(It, loopMBB);
10703   MF->insert(It, exitMBB);
10704 
10705   // Transfer the remainder of BB and its successor edges to exitMBB.
10706   exitMBB->splice(exitMBB->begin(), BB,
10707                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10708   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10709 
10710   // Load an immediate to varEnd.
10711   Register varEnd = MRI.createVirtualRegister(TRC);
10712   if (Subtarget->useMovt()) {
10713     unsigned Vtmp = varEnd;
10714     if ((LoopSize & 0xFFFF0000) != 0)
10715       Vtmp = MRI.createVirtualRegister(TRC);
10716     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10717         .addImm(LoopSize & 0xFFFF)
10718         .add(predOps(ARMCC::AL));
10719 
10720     if ((LoopSize & 0xFFFF0000) != 0)
10721       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10722           .addReg(Vtmp)
10723           .addImm(LoopSize >> 16)
10724           .add(predOps(ARMCC::AL));
10725   } else {
10726     MachineConstantPool *ConstantPool = MF->getConstantPool();
10727     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10728     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10729 
10730     // MachineConstantPool wants an explicit alignment.
10731     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10732     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10733     MachineMemOperand *CPMMO =
10734         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10735                                  MachineMemOperand::MOLoad, 4, Align(4));
10736 
10737     if (IsThumb)
10738       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10739           .addReg(varEnd, RegState::Define)
10740           .addConstantPoolIndex(Idx)
10741           .add(predOps(ARMCC::AL))
10742           .addMemOperand(CPMMO);
10743     else
10744       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10745           .addReg(varEnd, RegState::Define)
10746           .addConstantPoolIndex(Idx)
10747           .addImm(0)
10748           .add(predOps(ARMCC::AL))
10749           .addMemOperand(CPMMO);
10750   }
10751   BB->addSuccessor(loopMBB);
10752 
10753   // Generate the loop body:
10754   //   varPhi = PHI(varLoop, varEnd)
10755   //   srcPhi = PHI(srcLoop, src)
10756   //   destPhi = PHI(destLoop, dst)
10757   MachineBasicBlock *entryBB = BB;
10758   BB = loopMBB;
10759   Register varLoop = MRI.createVirtualRegister(TRC);
10760   Register varPhi = MRI.createVirtualRegister(TRC);
10761   Register srcLoop = MRI.createVirtualRegister(TRC);
10762   Register srcPhi = MRI.createVirtualRegister(TRC);
10763   Register destLoop = MRI.createVirtualRegister(TRC);
10764   Register destPhi = MRI.createVirtualRegister(TRC);
10765 
10766   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10767     .addReg(varLoop).addMBB(loopMBB)
10768     .addReg(varEnd).addMBB(entryBB);
10769   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10770     .addReg(srcLoop).addMBB(loopMBB)
10771     .addReg(src).addMBB(entryBB);
10772   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10773     .addReg(destLoop).addMBB(loopMBB)
10774     .addReg(dest).addMBB(entryBB);
10775 
10776   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10777   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10778   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10779   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10780              IsThumb1, IsThumb2);
10781   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10782              IsThumb1, IsThumb2);
10783 
10784   // Decrement loop variable by UnitSize.
10785   if (IsThumb1) {
10786     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10787         .add(t1CondCodeOp())
10788         .addReg(varPhi)
10789         .addImm(UnitSize)
10790         .add(predOps(ARMCC::AL));
10791   } else {
10792     MachineInstrBuilder MIB =
10793         BuildMI(*BB, BB->end(), dl,
10794                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10795     MIB.addReg(varPhi)
10796         .addImm(UnitSize)
10797         .add(predOps(ARMCC::AL))
10798         .add(condCodeOp());
10799     MIB->getOperand(5).setReg(ARM::CPSR);
10800     MIB->getOperand(5).setIsDef(true);
10801   }
10802   BuildMI(*BB, BB->end(), dl,
10803           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10804       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10805 
10806   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10807   BB->addSuccessor(loopMBB);
10808   BB->addSuccessor(exitMBB);
10809 
10810   // Add epilogue to handle BytesLeft.
10811   BB = exitMBB;
10812   auto StartOfExit = exitMBB->begin();
10813 
10814   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10815   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10816   unsigned srcIn = srcLoop;
10817   unsigned destIn = destLoop;
10818   for (unsigned i = 0; i < BytesLeft; i++) {
10819     Register srcOut = MRI.createVirtualRegister(TRC);
10820     Register destOut = MRI.createVirtualRegister(TRC);
10821     Register scratch = MRI.createVirtualRegister(TRC);
10822     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10823                IsThumb1, IsThumb2);
10824     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10825                IsThumb1, IsThumb2);
10826     srcIn = srcOut;
10827     destIn = destOut;
10828   }
10829 
10830   MI.eraseFromParent(); // The instruction is gone now.
10831   return BB;
10832 }
10833 
10834 MachineBasicBlock *
10835 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10836                                        MachineBasicBlock *MBB) const {
10837   const TargetMachine &TM = getTargetMachine();
10838   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10839   DebugLoc DL = MI.getDebugLoc();
10840 
10841   assert(Subtarget->isTargetWindows() &&
10842          "__chkstk is only supported on Windows");
10843   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10844 
10845   // __chkstk takes the number of words to allocate on the stack in R4, and
10846   // returns the stack adjustment in number of bytes in R4.  This will not
10847   // clober any other registers (other than the obvious lr).
10848   //
10849   // Although, technically, IP should be considered a register which may be
10850   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10851   // thumb-2 environment, so there is no interworking required.  As a result, we
10852   // do not expect a veneer to be emitted by the linker, clobbering IP.
10853   //
10854   // Each module receives its own copy of __chkstk, so no import thunk is
10855   // required, again, ensuring that IP is not clobbered.
10856   //
10857   // Finally, although some linkers may theoretically provide a trampoline for
10858   // out of range calls (which is quite common due to a 32M range limitation of
10859   // branches for Thumb), we can generate the long-call version via
10860   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10861   // IP.
10862 
10863   switch (TM.getCodeModel()) {
10864   case CodeModel::Tiny:
10865     llvm_unreachable("Tiny code model not available on ARM.");
10866   case CodeModel::Small:
10867   case CodeModel::Medium:
10868   case CodeModel::Kernel:
10869     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10870         .add(predOps(ARMCC::AL))
10871         .addExternalSymbol("__chkstk")
10872         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10873         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10874         .addReg(ARM::R12,
10875                 RegState::Implicit | RegState::Define | RegState::Dead)
10876         .addReg(ARM::CPSR,
10877                 RegState::Implicit | RegState::Define | RegState::Dead);
10878     break;
10879   case CodeModel::Large: {
10880     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10881     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10882 
10883     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10884       .addExternalSymbol("__chkstk");
10885     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10886         .add(predOps(ARMCC::AL))
10887         .addReg(Reg, RegState::Kill)
10888         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10889         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10890         .addReg(ARM::R12,
10891                 RegState::Implicit | RegState::Define | RegState::Dead)
10892         .addReg(ARM::CPSR,
10893                 RegState::Implicit | RegState::Define | RegState::Dead);
10894     break;
10895   }
10896   }
10897 
10898   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10899       .addReg(ARM::SP, RegState::Kill)
10900       .addReg(ARM::R4, RegState::Kill)
10901       .setMIFlags(MachineInstr::FrameSetup)
10902       .add(predOps(ARMCC::AL))
10903       .add(condCodeOp());
10904 
10905   MI.eraseFromParent();
10906   return MBB;
10907 }
10908 
10909 MachineBasicBlock *
10910 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10911                                        MachineBasicBlock *MBB) const {
10912   DebugLoc DL = MI.getDebugLoc();
10913   MachineFunction *MF = MBB->getParent();
10914   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10915 
10916   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10917   MF->insert(++MBB->getIterator(), ContBB);
10918   ContBB->splice(ContBB->begin(), MBB,
10919                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10920   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10921   MBB->addSuccessor(ContBB);
10922 
10923   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10924   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10925   MF->push_back(TrapBB);
10926   MBB->addSuccessor(TrapBB);
10927 
10928   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10929       .addReg(MI.getOperand(0).getReg())
10930       .addImm(0)
10931       .add(predOps(ARMCC::AL));
10932   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10933       .addMBB(TrapBB)
10934       .addImm(ARMCC::EQ)
10935       .addReg(ARM::CPSR);
10936 
10937   MI.eraseFromParent();
10938   return ContBB;
10939 }
10940 
10941 // The CPSR operand of SelectItr might be missing a kill marker
10942 // because there were multiple uses of CPSR, and ISel didn't know
10943 // which to mark. Figure out whether SelectItr should have had a
10944 // kill marker, and set it if it should. Returns the correct kill
10945 // marker value.
10946 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10947                                    MachineBasicBlock* BB,
10948                                    const TargetRegisterInfo* TRI) {
10949   // Scan forward through BB for a use/def of CPSR.
10950   MachineBasicBlock::iterator miI(std::next(SelectItr));
10951   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10952     const MachineInstr& mi = *miI;
10953     if (mi.readsRegister(ARM::CPSR))
10954       return false;
10955     if (mi.definesRegister(ARM::CPSR))
10956       break; // Should have kill-flag - update below.
10957   }
10958 
10959   // If we hit the end of the block, check whether CPSR is live into a
10960   // successor.
10961   if (miI == BB->end()) {
10962     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10963                                           sEnd = BB->succ_end();
10964          sItr != sEnd; ++sItr) {
10965       MachineBasicBlock* succ = *sItr;
10966       if (succ->isLiveIn(ARM::CPSR))
10967         return false;
10968     }
10969   }
10970 
10971   // We found a def, or hit the end of the basic block and CPSR wasn't live
10972   // out. SelectMI should have a kill flag on CPSR.
10973   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10974   return true;
10975 }
10976 
10977 MachineBasicBlock *
10978 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10979                                                MachineBasicBlock *BB) const {
10980   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10981   DebugLoc dl = MI.getDebugLoc();
10982   bool isThumb2 = Subtarget->isThumb2();
10983   switch (MI.getOpcode()) {
10984   default: {
10985     MI.print(errs());
10986     llvm_unreachable("Unexpected instr type to insert");
10987   }
10988 
10989   // Thumb1 post-indexed loads are really just single-register LDMs.
10990   case ARM::tLDR_postidx: {
10991     MachineOperand Def(MI.getOperand(1));
10992     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10993         .add(Def)  // Rn_wb
10994         .add(MI.getOperand(2))  // Rn
10995         .add(MI.getOperand(3))  // PredImm
10996         .add(MI.getOperand(4))  // PredReg
10997         .add(MI.getOperand(0))  // Rt
10998         .cloneMemRefs(MI);
10999     MI.eraseFromParent();
11000     return BB;
11001   }
11002 
11003   // The Thumb2 pre-indexed stores have the same MI operands, they just
11004   // define them differently in the .td files from the isel patterns, so
11005   // they need pseudos.
11006   case ARM::t2STR_preidx:
11007     MI.setDesc(TII->get(ARM::t2STR_PRE));
11008     return BB;
11009   case ARM::t2STRB_preidx:
11010     MI.setDesc(TII->get(ARM::t2STRB_PRE));
11011     return BB;
11012   case ARM::t2STRH_preidx:
11013     MI.setDesc(TII->get(ARM::t2STRH_PRE));
11014     return BB;
11015 
11016   case ARM::STRi_preidx:
11017   case ARM::STRBi_preidx: {
11018     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11019                                                          : ARM::STRB_PRE_IMM;
11020     // Decode the offset.
11021     unsigned Offset = MI.getOperand(4).getImm();
11022     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11023     Offset = ARM_AM::getAM2Offset(Offset);
11024     if (isSub)
11025       Offset = -Offset;
11026 
11027     MachineMemOperand *MMO = *MI.memoperands_begin();
11028     BuildMI(*BB, MI, dl, TII->get(NewOpc))
11029         .add(MI.getOperand(0)) // Rn_wb
11030         .add(MI.getOperand(1)) // Rt
11031         .add(MI.getOperand(2)) // Rn
11032         .addImm(Offset)        // offset (skip GPR==zero_reg)
11033         .add(MI.getOperand(5)) // pred
11034         .add(MI.getOperand(6))
11035         .addMemOperand(MMO);
11036     MI.eraseFromParent();
11037     return BB;
11038   }
11039   case ARM::STRr_preidx:
11040   case ARM::STRBr_preidx:
11041   case ARM::STRH_preidx: {
11042     unsigned NewOpc;
11043     switch (MI.getOpcode()) {
11044     default: llvm_unreachable("unexpected opcode!");
11045     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11046     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11047     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11048     }
11049     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11050     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
11051       MIB.add(MI.getOperand(i));
11052     MI.eraseFromParent();
11053     return BB;
11054   }
11055 
11056   case ARM::tMOVCCr_pseudo: {
11057     // To "insert" a SELECT_CC instruction, we actually have to insert the
11058     // diamond control-flow pattern.  The incoming instruction knows the
11059     // destination vreg to set, the condition code register to branch on, the
11060     // true/false values to select between, and a branch opcode to use.
11061     const BasicBlock *LLVM_BB = BB->getBasicBlock();
11062     MachineFunction::iterator It = ++BB->getIterator();
11063 
11064     //  thisMBB:
11065     //  ...
11066     //   TrueVal = ...
11067     //   cmpTY ccX, r1, r2
11068     //   bCC copy1MBB
11069     //   fallthrough --> copy0MBB
11070     MachineBasicBlock *thisMBB  = BB;
11071     MachineFunction *F = BB->getParent();
11072     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11073     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
11074     F->insert(It, copy0MBB);
11075     F->insert(It, sinkMBB);
11076 
11077     // Check whether CPSR is live past the tMOVCCr_pseudo.
11078     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11079     if (!MI.killsRegister(ARM::CPSR) &&
11080         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11081       copy0MBB->addLiveIn(ARM::CPSR);
11082       sinkMBB->addLiveIn(ARM::CPSR);
11083     }
11084 
11085     // Transfer the remainder of BB and its successor edges to sinkMBB.
11086     sinkMBB->splice(sinkMBB->begin(), BB,
11087                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11088     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11089 
11090     BB->addSuccessor(copy0MBB);
11091     BB->addSuccessor(sinkMBB);
11092 
11093     BuildMI(BB, dl, TII->get(ARM::tBcc))
11094         .addMBB(sinkMBB)
11095         .addImm(MI.getOperand(3).getImm())
11096         .addReg(MI.getOperand(4).getReg());
11097 
11098     //  copy0MBB:
11099     //   %FalseValue = ...
11100     //   # fallthrough to sinkMBB
11101     BB = copy0MBB;
11102 
11103     // Update machine-CFG edges
11104     BB->addSuccessor(sinkMBB);
11105 
11106     //  sinkMBB:
11107     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11108     //  ...
11109     BB = sinkMBB;
11110     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11111         .addReg(MI.getOperand(1).getReg())
11112         .addMBB(copy0MBB)
11113         .addReg(MI.getOperand(2).getReg())
11114         .addMBB(thisMBB);
11115 
11116     MI.eraseFromParent(); // The pseudo instruction is gone now.
11117     return BB;
11118   }
11119 
11120   case ARM::BCCi64:
11121   case ARM::BCCZi64: {
11122     // If there is an unconditional branch to the other successor, remove it.
11123     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11124 
11125     // Compare both parts that make up the double comparison separately for
11126     // equality.
11127     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11128 
11129     Register LHS1 = MI.getOperand(1).getReg();
11130     Register LHS2 = MI.getOperand(2).getReg();
11131     if (RHSisZero) {
11132       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11133           .addReg(LHS1)
11134           .addImm(0)
11135           .add(predOps(ARMCC::AL));
11136       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11137         .addReg(LHS2).addImm(0)
11138         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11139     } else {
11140       Register RHS1 = MI.getOperand(3).getReg();
11141       Register RHS2 = MI.getOperand(4).getReg();
11142       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11143           .addReg(LHS1)
11144           .addReg(RHS1)
11145           .add(predOps(ARMCC::AL));
11146       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11147         .addReg(LHS2).addReg(RHS2)
11148         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11149     }
11150 
11151     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
11152     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
11153     if (MI.getOperand(0).getImm() == ARMCC::NE)
11154       std::swap(destMBB, exitMBB);
11155 
11156     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
11157       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
11158     if (isThumb2)
11159       BuildMI(BB, dl, TII->get(ARM::t2B))
11160           .addMBB(exitMBB)
11161           .add(predOps(ARMCC::AL));
11162     else
11163       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
11164 
11165     MI.eraseFromParent(); // The pseudo instruction is gone now.
11166     return BB;
11167   }
11168 
11169   case ARM::Int_eh_sjlj_setjmp:
11170   case ARM::Int_eh_sjlj_setjmp_nofp:
11171   case ARM::tInt_eh_sjlj_setjmp:
11172   case ARM::t2Int_eh_sjlj_setjmp:
11173   case ARM::t2Int_eh_sjlj_setjmp_nofp:
11174     return BB;
11175 
11176   case ARM::Int_eh_sjlj_setup_dispatch:
11177     EmitSjLjDispatchBlock(MI, BB);
11178     return BB;
11179 
11180   case ARM::ABS:
11181   case ARM::t2ABS: {
11182     // To insert an ABS instruction, we have to insert the
11183     // diamond control-flow pattern.  The incoming instruction knows the
11184     // source vreg to test against 0, the destination vreg to set,
11185     // the condition code register to branch on, the
11186     // true/false values to select between, and a branch opcode to use.
11187     // It transforms
11188     //     V1 = ABS V0
11189     // into
11190     //     V2 = MOVS V0
11191     //     BCC                      (branch to SinkBB if V0 >= 0)
11192     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
11193     //     SinkBB: V1 = PHI(V2, V3)
11194     const BasicBlock *LLVM_BB = BB->getBasicBlock();
11195     MachineFunction::iterator BBI = ++BB->getIterator();
11196     MachineFunction *Fn = BB->getParent();
11197     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11198     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
11199     Fn->insert(BBI, RSBBB);
11200     Fn->insert(BBI, SinkBB);
11201 
11202     Register ABSSrcReg = MI.getOperand(1).getReg();
11203     Register ABSDstReg = MI.getOperand(0).getReg();
11204     bool ABSSrcKIll = MI.getOperand(1).isKill();
11205     bool isThumb2 = Subtarget->isThumb2();
11206     MachineRegisterInfo &MRI = Fn->getRegInfo();
11207     // In Thumb mode S must not be specified if source register is the SP or
11208     // PC and if destination register is the SP, so restrict register class
11209     Register NewRsbDstReg = MRI.createVirtualRegister(
11210         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
11211 
11212     // Transfer the remainder of BB and its successor edges to sinkMBB.
11213     SinkBB->splice(SinkBB->begin(), BB,
11214                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
11215     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
11216 
11217     BB->addSuccessor(RSBBB);
11218     BB->addSuccessor(SinkBB);
11219 
11220     // fall through to SinkMBB
11221     RSBBB->addSuccessor(SinkBB);
11222 
11223     // insert a cmp at the end of BB
11224     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11225         .addReg(ABSSrcReg)
11226         .addImm(0)
11227         .add(predOps(ARMCC::AL));
11228 
11229     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
11230     BuildMI(BB, dl,
11231       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
11232       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
11233 
11234     // insert rsbri in RSBBB
11235     // Note: BCC and rsbri will be converted into predicated rsbmi
11236     // by if-conversion pass
11237     BuildMI(*RSBBB, RSBBB->begin(), dl,
11238             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
11239         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
11240         .addImm(0)
11241         .add(predOps(ARMCC::AL))
11242         .add(condCodeOp());
11243 
11244     // insert PHI in SinkBB,
11245     // reuse ABSDstReg to not change uses of ABS instruction
11246     BuildMI(*SinkBB, SinkBB->begin(), dl,
11247       TII->get(ARM::PHI), ABSDstReg)
11248       .addReg(NewRsbDstReg).addMBB(RSBBB)
11249       .addReg(ABSSrcReg).addMBB(BB);
11250 
11251     // remove ABS instruction
11252     MI.eraseFromParent();
11253 
11254     // return last added BB
11255     return SinkBB;
11256   }
11257   case ARM::COPY_STRUCT_BYVAL_I32:
11258     ++NumLoopByVals;
11259     return EmitStructByval(MI, BB);
11260   case ARM::WIN__CHKSTK:
11261     return EmitLowered__chkstk(MI, BB);
11262   case ARM::WIN__DBZCHK:
11263     return EmitLowered__dbzchk(MI, BB);
11264   }
11265 }
11266 
11267 /// Attaches vregs to MEMCPY that it will use as scratch registers
11268 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
11269 /// instead of as a custom inserter because we need the use list from the SDNode.
11270 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
11271                                     MachineInstr &MI, const SDNode *Node) {
11272   bool isThumb1 = Subtarget->isThumb1Only();
11273 
11274   DebugLoc DL = MI.getDebugLoc();
11275   MachineFunction *MF = MI.getParent()->getParent();
11276   MachineRegisterInfo &MRI = MF->getRegInfo();
11277   MachineInstrBuilder MIB(*MF, MI);
11278 
11279   // If the new dst/src is unused mark it as dead.
11280   if (!Node->hasAnyUseOfValue(0)) {
11281     MI.getOperand(0).setIsDead(true);
11282   }
11283   if (!Node->hasAnyUseOfValue(1)) {
11284     MI.getOperand(1).setIsDead(true);
11285   }
11286 
11287   // The MEMCPY both defines and kills the scratch registers.
11288   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
11289     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
11290                                                          : &ARM::GPRRegClass);
11291     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
11292   }
11293 }
11294 
11295 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11296                                                       SDNode *Node) const {
11297   if (MI.getOpcode() == ARM::MEMCPY) {
11298     attachMEMCPYScratchRegs(Subtarget, MI, Node);
11299     return;
11300   }
11301 
11302   const MCInstrDesc *MCID = &MI.getDesc();
11303   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
11304   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
11305   // operand is still set to noreg. If needed, set the optional operand's
11306   // register to CPSR, and remove the redundant implicit def.
11307   //
11308   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
11309 
11310   // Rename pseudo opcodes.
11311   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
11312   unsigned ccOutIdx;
11313   if (NewOpc) {
11314     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
11315     MCID = &TII->get(NewOpc);
11316 
11317     assert(MCID->getNumOperands() ==
11318            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
11319         && "converted opcode should be the same except for cc_out"
11320            " (and, on Thumb1, pred)");
11321 
11322     MI.setDesc(*MCID);
11323 
11324     // Add the optional cc_out operand
11325     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
11326 
11327     // On Thumb1, move all input operands to the end, then add the predicate
11328     if (Subtarget->isThumb1Only()) {
11329       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
11330         MI.addOperand(MI.getOperand(1));
11331         MI.RemoveOperand(1);
11332       }
11333 
11334       // Restore the ties
11335       for (unsigned i = MI.getNumOperands(); i--;) {
11336         const MachineOperand& op = MI.getOperand(i);
11337         if (op.isReg() && op.isUse()) {
11338           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
11339           if (DefIdx != -1)
11340             MI.tieOperands(DefIdx, i);
11341         }
11342       }
11343 
11344       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
11345       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
11346       ccOutIdx = 1;
11347     } else
11348       ccOutIdx = MCID->getNumOperands() - 1;
11349   } else
11350     ccOutIdx = MCID->getNumOperands() - 1;
11351 
11352   // Any ARM instruction that sets the 's' bit should specify an optional
11353   // "cc_out" operand in the last operand position.
11354   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
11355     assert(!NewOpc && "Optional cc_out operand required");
11356     return;
11357   }
11358   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
11359   // since we already have an optional CPSR def.
11360   bool definesCPSR = false;
11361   bool deadCPSR = false;
11362   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
11363        ++i) {
11364     const MachineOperand &MO = MI.getOperand(i);
11365     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
11366       definesCPSR = true;
11367       if (MO.isDead())
11368         deadCPSR = true;
11369       MI.RemoveOperand(i);
11370       break;
11371     }
11372   }
11373   if (!definesCPSR) {
11374     assert(!NewOpc && "Optional cc_out operand required");
11375     return;
11376   }
11377   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
11378   if (deadCPSR) {
11379     assert(!MI.getOperand(ccOutIdx).getReg() &&
11380            "expect uninitialized optional cc_out operand");
11381     // Thumb1 instructions must have the S bit even if the CPSR is dead.
11382     if (!Subtarget->isThumb1Only())
11383       return;
11384   }
11385 
11386   // If this instruction was defined with an optional CPSR def and its dag node
11387   // had a live implicit CPSR def, then activate the optional CPSR def.
11388   MachineOperand &MO = MI.getOperand(ccOutIdx);
11389   MO.setReg(ARM::CPSR);
11390   MO.setIsDef(true);
11391 }
11392 
11393 //===----------------------------------------------------------------------===//
11394 //                           ARM Optimization Hooks
11395 //===----------------------------------------------------------------------===//
11396 
11397 // Helper function that checks if N is a null or all ones constant.
11398 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11399   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11400 }
11401 
11402 // Return true if N is conditionally 0 or all ones.
11403 // Detects these expressions where cc is an i1 value:
11404 //
11405 //   (select cc 0, y)   [AllOnes=0]
11406 //   (select cc y, 0)   [AllOnes=0]
11407 //   (zext cc)          [AllOnes=0]
11408 //   (sext cc)          [AllOnes=0/1]
11409 //   (select cc -1, y)  [AllOnes=1]
11410 //   (select cc y, -1)  [AllOnes=1]
11411 //
11412 // Invert is set when N is the null/all ones constant when CC is false.
11413 // OtherOp is set to the alternative value of N.
11414 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11415                                        SDValue &CC, bool &Invert,
11416                                        SDValue &OtherOp,
11417                                        SelectionDAG &DAG) {
11418   switch (N->getOpcode()) {
11419   default: return false;
11420   case ISD::SELECT: {
11421     CC = N->getOperand(0);
11422     SDValue N1 = N->getOperand(1);
11423     SDValue N2 = N->getOperand(2);
11424     if (isZeroOrAllOnes(N1, AllOnes)) {
11425       Invert = false;
11426       OtherOp = N2;
11427       return true;
11428     }
11429     if (isZeroOrAllOnes(N2, AllOnes)) {
11430       Invert = true;
11431       OtherOp = N1;
11432       return true;
11433     }
11434     return false;
11435   }
11436   case ISD::ZERO_EXTEND:
11437     // (zext cc) can never be the all ones value.
11438     if (AllOnes)
11439       return false;
11440     LLVM_FALLTHROUGH;
11441   case ISD::SIGN_EXTEND: {
11442     SDLoc dl(N);
11443     EVT VT = N->getValueType(0);
11444     CC = N->getOperand(0);
11445     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11446       return false;
11447     Invert = !AllOnes;
11448     if (AllOnes)
11449       // When looking for an AllOnes constant, N is an sext, and the 'other'
11450       // value is 0.
11451       OtherOp = DAG.getConstant(0, dl, VT);
11452     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11453       // When looking for a 0 constant, N can be zext or sext.
11454       OtherOp = DAG.getConstant(1, dl, VT);
11455     else
11456       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11457                                 VT);
11458     return true;
11459   }
11460   }
11461 }
11462 
11463 // Combine a constant select operand into its use:
11464 //
11465 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
11466 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
11467 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
11468 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
11469 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
11470 //
11471 // The transform is rejected if the select doesn't have a constant operand that
11472 // is null, or all ones when AllOnes is set.
11473 //
11474 // Also recognize sext/zext from i1:
11475 //
11476 //   (add (zext cc), x) -> (select cc (add x, 1), x)
11477 //   (add (sext cc), x) -> (select cc (add x, -1), x)
11478 //
11479 // These transformations eventually create predicated instructions.
11480 //
11481 // @param N       The node to transform.
11482 // @param Slct    The N operand that is a select.
11483 // @param OtherOp The other N operand (x above).
11484 // @param DCI     Context.
11485 // @param AllOnes Require the select constant to be all ones instead of null.
11486 // @returns The new node, or SDValue() on failure.
11487 static
11488 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11489                             TargetLowering::DAGCombinerInfo &DCI,
11490                             bool AllOnes = false) {
11491   SelectionDAG &DAG = DCI.DAG;
11492   EVT VT = N->getValueType(0);
11493   SDValue NonConstantVal;
11494   SDValue CCOp;
11495   bool SwapSelectOps;
11496   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11497                                   NonConstantVal, DAG))
11498     return SDValue();
11499 
11500   // Slct is now know to be the desired identity constant when CC is true.
11501   SDValue TrueVal = OtherOp;
11502   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11503                                  OtherOp, NonConstantVal);
11504   // Unless SwapSelectOps says CC should be false.
11505   if (SwapSelectOps)
11506     std::swap(TrueVal, FalseVal);
11507 
11508   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11509                      CCOp, TrueVal, FalseVal);
11510 }
11511 
11512 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11513 static
11514 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11515                                        TargetLowering::DAGCombinerInfo &DCI) {
11516   SDValue N0 = N->getOperand(0);
11517   SDValue N1 = N->getOperand(1);
11518   if (N0.getNode()->hasOneUse())
11519     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11520       return Result;
11521   if (N1.getNode()->hasOneUse())
11522     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11523       return Result;
11524   return SDValue();
11525 }
11526 
11527 static bool IsVUZPShuffleNode(SDNode *N) {
11528   // VUZP shuffle node.
11529   if (N->getOpcode() == ARMISD::VUZP)
11530     return true;
11531 
11532   // "VUZP" on i32 is an alias for VTRN.
11533   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11534     return true;
11535 
11536   return false;
11537 }
11538 
11539 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11540                                  TargetLowering::DAGCombinerInfo &DCI,
11541                                  const ARMSubtarget *Subtarget) {
11542   // Look for ADD(VUZP.0, VUZP.1).
11543   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11544       N0 == N1)
11545    return SDValue();
11546 
11547   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11548   if (!N->getValueType(0).is64BitVector())
11549     return SDValue();
11550 
11551   // Generate vpadd.
11552   SelectionDAG &DAG = DCI.DAG;
11553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11554   SDLoc dl(N);
11555   SDNode *Unzip = N0.getNode();
11556   EVT VT = N->getValueType(0);
11557 
11558   SmallVector<SDValue, 8> Ops;
11559   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11560                                 TLI.getPointerTy(DAG.getDataLayout())));
11561   Ops.push_back(Unzip->getOperand(0));
11562   Ops.push_back(Unzip->getOperand(1));
11563 
11564   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11565 }
11566 
11567 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11568                                       TargetLowering::DAGCombinerInfo &DCI,
11569                                       const ARMSubtarget *Subtarget) {
11570   // Check for two extended operands.
11571   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11572         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11573       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11574         N1.getOpcode() == ISD::ZERO_EXTEND))
11575     return SDValue();
11576 
11577   SDValue N00 = N0.getOperand(0);
11578   SDValue N10 = N1.getOperand(0);
11579 
11580   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11581   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11582       N00 == N10)
11583     return SDValue();
11584 
11585   // We only recognize Q register paddl here; this can't be reached until
11586   // after type legalization.
11587   if (!N00.getValueType().is64BitVector() ||
11588       !N0.getValueType().is128BitVector())
11589     return SDValue();
11590 
11591   // Generate vpaddl.
11592   SelectionDAG &DAG = DCI.DAG;
11593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11594   SDLoc dl(N);
11595   EVT VT = N->getValueType(0);
11596 
11597   SmallVector<SDValue, 8> Ops;
11598   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11599   unsigned Opcode;
11600   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11601     Opcode = Intrinsic::arm_neon_vpaddls;
11602   else
11603     Opcode = Intrinsic::arm_neon_vpaddlu;
11604   Ops.push_back(DAG.getConstant(Opcode, dl,
11605                                 TLI.getPointerTy(DAG.getDataLayout())));
11606   EVT ElemTy = N00.getValueType().getVectorElementType();
11607   unsigned NumElts = VT.getVectorNumElements();
11608   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11609   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11610                                N00.getOperand(0), N00.getOperand(1));
11611   Ops.push_back(Concat);
11612 
11613   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11614 }
11615 
11616 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11617 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11618 // much easier to match.
11619 static SDValue
11620 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11621                                TargetLowering::DAGCombinerInfo &DCI,
11622                                const ARMSubtarget *Subtarget) {
11623   // Only perform optimization if after legalize, and if NEON is available. We
11624   // also expected both operands to be BUILD_VECTORs.
11625   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11626       || N0.getOpcode() != ISD::BUILD_VECTOR
11627       || N1.getOpcode() != ISD::BUILD_VECTOR)
11628     return SDValue();
11629 
11630   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11631   EVT VT = N->getValueType(0);
11632   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11633     return SDValue();
11634 
11635   // Check that the vector operands are of the right form.
11636   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11637   // operands, where N is the size of the formed vector.
11638   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11639   // index such that we have a pair wise add pattern.
11640 
11641   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11642   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11643     return SDValue();
11644   SDValue Vec = N0->getOperand(0)->getOperand(0);
11645   SDNode *V = Vec.getNode();
11646   unsigned nextIndex = 0;
11647 
11648   // For each operands to the ADD which are BUILD_VECTORs,
11649   // check to see if each of their operands are an EXTRACT_VECTOR with
11650   // the same vector and appropriate index.
11651   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11652     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11653         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11654 
11655       SDValue ExtVec0 = N0->getOperand(i);
11656       SDValue ExtVec1 = N1->getOperand(i);
11657 
11658       // First operand is the vector, verify its the same.
11659       if (V != ExtVec0->getOperand(0).getNode() ||
11660           V != ExtVec1->getOperand(0).getNode())
11661         return SDValue();
11662 
11663       // Second is the constant, verify its correct.
11664       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11665       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11666 
11667       // For the constant, we want to see all the even or all the odd.
11668       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11669           || C1->getZExtValue() != nextIndex+1)
11670         return SDValue();
11671 
11672       // Increment index.
11673       nextIndex+=2;
11674     } else
11675       return SDValue();
11676   }
11677 
11678   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11679   // we're using the entire input vector, otherwise there's a size/legality
11680   // mismatch somewhere.
11681   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11682       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11683     return SDValue();
11684 
11685   // Create VPADDL node.
11686   SelectionDAG &DAG = DCI.DAG;
11687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11688 
11689   SDLoc dl(N);
11690 
11691   // Build operand list.
11692   SmallVector<SDValue, 8> Ops;
11693   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11694                                 TLI.getPointerTy(DAG.getDataLayout())));
11695 
11696   // Input is the vector.
11697   Ops.push_back(Vec);
11698 
11699   // Get widened type and narrowed type.
11700   MVT widenType;
11701   unsigned numElem = VT.getVectorNumElements();
11702 
11703   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11704   switch (inputLaneType.getSimpleVT().SimpleTy) {
11705     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11706     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11707     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11708     default:
11709       llvm_unreachable("Invalid vector element type for padd optimization.");
11710   }
11711 
11712   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11713   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11714   return DAG.getNode(ExtOp, dl, VT, tmp);
11715 }
11716 
11717 static SDValue findMUL_LOHI(SDValue V) {
11718   if (V->getOpcode() == ISD::UMUL_LOHI ||
11719       V->getOpcode() == ISD::SMUL_LOHI)
11720     return V;
11721   return SDValue();
11722 }
11723 
11724 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11725                                         TargetLowering::DAGCombinerInfo &DCI,
11726                                         const ARMSubtarget *Subtarget) {
11727   if (!Subtarget->hasBaseDSP())
11728     return SDValue();
11729 
11730   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11731   // accumulates the product into a 64-bit value. The 16-bit values will
11732   // be sign extended somehow or SRA'd into 32-bit values
11733   // (addc (adde (mul 16bit, 16bit), lo), hi)
11734   SDValue Mul = AddcNode->getOperand(0);
11735   SDValue Lo = AddcNode->getOperand(1);
11736   if (Mul.getOpcode() != ISD::MUL) {
11737     Lo = AddcNode->getOperand(0);
11738     Mul = AddcNode->getOperand(1);
11739     if (Mul.getOpcode() != ISD::MUL)
11740       return SDValue();
11741   }
11742 
11743   SDValue SRA = AddeNode->getOperand(0);
11744   SDValue Hi = AddeNode->getOperand(1);
11745   if (SRA.getOpcode() != ISD::SRA) {
11746     SRA = AddeNode->getOperand(1);
11747     Hi = AddeNode->getOperand(0);
11748     if (SRA.getOpcode() != ISD::SRA)
11749       return SDValue();
11750   }
11751   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11752     if (Const->getZExtValue() != 31)
11753       return SDValue();
11754   } else
11755     return SDValue();
11756 
11757   if (SRA.getOperand(0) != Mul)
11758     return SDValue();
11759 
11760   SelectionDAG &DAG = DCI.DAG;
11761   SDLoc dl(AddcNode);
11762   unsigned Opcode = 0;
11763   SDValue Op0;
11764   SDValue Op1;
11765 
11766   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11767     Opcode = ARMISD::SMLALBB;
11768     Op0 = Mul.getOperand(0);
11769     Op1 = Mul.getOperand(1);
11770   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11771     Opcode = ARMISD::SMLALBT;
11772     Op0 = Mul.getOperand(0);
11773     Op1 = Mul.getOperand(1).getOperand(0);
11774   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11775     Opcode = ARMISD::SMLALTB;
11776     Op0 = Mul.getOperand(0).getOperand(0);
11777     Op1 = Mul.getOperand(1);
11778   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11779     Opcode = ARMISD::SMLALTT;
11780     Op0 = Mul->getOperand(0).getOperand(0);
11781     Op1 = Mul->getOperand(1).getOperand(0);
11782   }
11783 
11784   if (!Op0 || !Op1)
11785     return SDValue();
11786 
11787   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11788                               Op0, Op1, Lo, Hi);
11789   // Replace the ADDs' nodes uses by the MLA node's values.
11790   SDValue HiMLALResult(SMLAL.getNode(), 1);
11791   SDValue LoMLALResult(SMLAL.getNode(), 0);
11792 
11793   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11794   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11795 
11796   // Return original node to notify the driver to stop replacing.
11797   SDValue resNode(AddcNode, 0);
11798   return resNode;
11799 }
11800 
11801 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11802                                      TargetLowering::DAGCombinerInfo &DCI,
11803                                      const ARMSubtarget *Subtarget) {
11804   // Look for multiply add opportunities.
11805   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11806   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11807   // a glue link from the first add to the second add.
11808   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11809   // a S/UMLAL instruction.
11810   //                  UMUL_LOHI
11811   //                 / :lo    \ :hi
11812   //                V          \          [no multiline comment]
11813   //    loAdd ->  ADDC         |
11814   //                 \ :carry /
11815   //                  V      V
11816   //                    ADDE   <- hiAdd
11817   //
11818   // In the special case where only the higher part of a signed result is used
11819   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11820   // a constant with the exact value of 0x80000000, we recognize we are dealing
11821   // with a "rounded multiply and add" (or subtract) and transform it into
11822   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11823 
11824   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11825           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11826          "Expect an ADDE or SUBE");
11827 
11828   assert(AddeSubeNode->getNumOperands() == 3 &&
11829          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11830          "ADDE node has the wrong inputs");
11831 
11832   // Check that we are chained to the right ADDC or SUBC node.
11833   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11834   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11835        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11836       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11837        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11838     return SDValue();
11839 
11840   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11841   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11842 
11843   // Check if the two operands are from the same mul_lohi node.
11844   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11845     return SDValue();
11846 
11847   assert(AddcSubcNode->getNumValues() == 2 &&
11848          AddcSubcNode->getValueType(0) == MVT::i32 &&
11849          "Expect ADDC with two result values. First: i32");
11850 
11851   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11852   // maybe a SMLAL which multiplies two 16-bit values.
11853   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11854       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11855       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11856       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11857       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11858     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11859 
11860   // Check for the triangle shape.
11861   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11862   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11863 
11864   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11865   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11866     return SDValue();
11867 
11868   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11869   bool IsLeftOperandMUL = false;
11870   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11871   if (MULOp == SDValue())
11872     MULOp = findMUL_LOHI(AddeSubeOp1);
11873   else
11874     IsLeftOperandMUL = true;
11875   if (MULOp == SDValue())
11876     return SDValue();
11877 
11878   // Figure out the right opcode.
11879   unsigned Opc = MULOp->getOpcode();
11880   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11881 
11882   // Figure out the high and low input values to the MLAL node.
11883   SDValue *HiAddSub = nullptr;
11884   SDValue *LoMul = nullptr;
11885   SDValue *LowAddSub = nullptr;
11886 
11887   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11888   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11889     return SDValue();
11890 
11891   if (IsLeftOperandMUL)
11892     HiAddSub = &AddeSubeOp1;
11893   else
11894     HiAddSub = &AddeSubeOp0;
11895 
11896   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11897   // whose low result is fed to the ADDC/SUBC we are checking.
11898 
11899   if (AddcSubcOp0 == MULOp.getValue(0)) {
11900     LoMul = &AddcSubcOp0;
11901     LowAddSub = &AddcSubcOp1;
11902   }
11903   if (AddcSubcOp1 == MULOp.getValue(0)) {
11904     LoMul = &AddcSubcOp1;
11905     LowAddSub = &AddcSubcOp0;
11906   }
11907 
11908   if (!LoMul)
11909     return SDValue();
11910 
11911   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11912   // the replacement below will create a cycle.
11913   if (AddcSubcNode == HiAddSub->getNode() ||
11914       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11915     return SDValue();
11916 
11917   // Create the merged node.
11918   SelectionDAG &DAG = DCI.DAG;
11919 
11920   // Start building operand list.
11921   SmallVector<SDValue, 8> Ops;
11922   Ops.push_back(LoMul->getOperand(0));
11923   Ops.push_back(LoMul->getOperand(1));
11924 
11925   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11926   // the case, we must be doing signed multiplication and only use the higher
11927   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11928   // addition or subtraction with the value of 0x800000.
11929   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11930       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11931       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11932       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11933           0x80000000) {
11934     Ops.push_back(*HiAddSub);
11935     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11936       FinalOpc = ARMISD::SMMLSR;
11937     } else {
11938       FinalOpc = ARMISD::SMMLAR;
11939     }
11940     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11941     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11942 
11943     return SDValue(AddeSubeNode, 0);
11944   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11945     // SMMLS is generated during instruction selection and the rest of this
11946     // function can not handle the case where AddcSubcNode is a SUBC.
11947     return SDValue();
11948 
11949   // Finish building the operand list for {U/S}MLAL
11950   Ops.push_back(*LowAddSub);
11951   Ops.push_back(*HiAddSub);
11952 
11953   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11954                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11955 
11956   // Replace the ADDs' nodes uses by the MLA node's values.
11957   SDValue HiMLALResult(MLALNode.getNode(), 1);
11958   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11959 
11960   SDValue LoMLALResult(MLALNode.getNode(), 0);
11961   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11962 
11963   // Return original node to notify the driver to stop replacing.
11964   return SDValue(AddeSubeNode, 0);
11965 }
11966 
11967 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11968                                       TargetLowering::DAGCombinerInfo &DCI,
11969                                       const ARMSubtarget *Subtarget) {
11970   // UMAAL is similar to UMLAL except that it adds two unsigned values.
11971   // While trying to combine for the other MLAL nodes, first search for the
11972   // chance to use UMAAL. Check if Addc uses a node which has already
11973   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11974   // as the addend, and it's handled in PerformUMLALCombine.
11975 
11976   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11977     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11978 
11979   // Check that we have a glued ADDC node.
11980   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11981   if (AddcNode->getOpcode() != ARMISD::ADDC)
11982     return SDValue();
11983 
11984   // Find the converted UMAAL or quit if it doesn't exist.
11985   SDNode *UmlalNode = nullptr;
11986   SDValue AddHi;
11987   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11988     UmlalNode = AddcNode->getOperand(0).getNode();
11989     AddHi = AddcNode->getOperand(1);
11990   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11991     UmlalNode = AddcNode->getOperand(1).getNode();
11992     AddHi = AddcNode->getOperand(0);
11993   } else {
11994     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11995   }
11996 
11997   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11998   // the ADDC as well as Zero.
11999   if (!isNullConstant(UmlalNode->getOperand(3)))
12000     return SDValue();
12001 
12002   if ((isNullConstant(AddeNode->getOperand(0)) &&
12003        AddeNode->getOperand(1).getNode() == UmlalNode) ||
12004       (AddeNode->getOperand(0).getNode() == UmlalNode &&
12005        isNullConstant(AddeNode->getOperand(1)))) {
12006     SelectionDAG &DAG = DCI.DAG;
12007     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
12008                       UmlalNode->getOperand(2), AddHi };
12009     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12010                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
12011 
12012     // Replace the ADDs' nodes uses by the UMAAL node's values.
12013     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12014     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12015 
12016     // Return original node to notify the driver to stop replacing.
12017     return SDValue(AddeNode, 0);
12018   }
12019   return SDValue();
12020 }
12021 
12022 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12023                                    const ARMSubtarget *Subtarget) {
12024   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12025     return SDValue();
12026 
12027   // Check that we have a pair of ADDC and ADDE as operands.
12028   // Both addends of the ADDE must be zero.
12029   SDNode* AddcNode = N->getOperand(2).getNode();
12030   SDNode* AddeNode = N->getOperand(3).getNode();
12031   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12032       (AddeNode->getOpcode() == ARMISD::ADDE) &&
12033       isNullConstant(AddeNode->getOperand(0)) &&
12034       isNullConstant(AddeNode->getOperand(1)) &&
12035       (AddeNode->getOperand(2).getNode() == AddcNode))
12036     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12037                        DAG.getVTList(MVT::i32, MVT::i32),
12038                        {N->getOperand(0), N->getOperand(1),
12039                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
12040   else
12041     return SDValue();
12042 }
12043 
12044 static SDValue PerformAddcSubcCombine(SDNode *N,
12045                                       TargetLowering::DAGCombinerInfo &DCI,
12046                                       const ARMSubtarget *Subtarget) {
12047   SelectionDAG &DAG(DCI.DAG);
12048 
12049   if (N->getOpcode() == ARMISD::SUBC) {
12050     // (SUBC (ADDE 0, 0, C), 1) -> C
12051     SDValue LHS = N->getOperand(0);
12052     SDValue RHS = N->getOperand(1);
12053     if (LHS->getOpcode() == ARMISD::ADDE &&
12054         isNullConstant(LHS->getOperand(0)) &&
12055         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12056       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12057     }
12058   }
12059 
12060   if (Subtarget->isThumb1Only()) {
12061     SDValue RHS = N->getOperand(1);
12062     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12063       int32_t imm = C->getSExtValue();
12064       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12065         SDLoc DL(N);
12066         RHS = DAG.getConstant(-imm, DL, MVT::i32);
12067         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12068                                                            : ARMISD::ADDC;
12069         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12070       }
12071     }
12072   }
12073 
12074   return SDValue();
12075 }
12076 
12077 static SDValue PerformAddeSubeCombine(SDNode *N,
12078                                       TargetLowering::DAGCombinerInfo &DCI,
12079                                       const ARMSubtarget *Subtarget) {
12080   if (Subtarget->isThumb1Only()) {
12081     SelectionDAG &DAG = DCI.DAG;
12082     SDValue RHS = N->getOperand(1);
12083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12084       int64_t imm = C->getSExtValue();
12085       if (imm < 0) {
12086         SDLoc DL(N);
12087 
12088         // The with-carry-in form matches bitwise not instead of the negation.
12089         // Effectively, the inverse interpretation of the carry flag already
12090         // accounts for part of the negation.
12091         RHS = DAG.getConstant(~imm, DL, MVT::i32);
12092 
12093         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12094                                                            : ARMISD::ADDE;
12095         return DAG.getNode(Opcode, DL, N->getVTList(),
12096                            N->getOperand(0), RHS, N->getOperand(2));
12097       }
12098     }
12099   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12100     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12101   }
12102   return SDValue();
12103 }
12104 
12105 static SDValue PerformSELECTCombine(SDNode *N,
12106                                     TargetLowering::DAGCombinerInfo &DCI,
12107                                     const ARMSubtarget *Subtarget) {
12108   if (!Subtarget->hasMVEIntegerOps())
12109     return SDValue();
12110 
12111   SDLoc dl(N);
12112   SDValue SetCC;
12113   SDValue LHS;
12114   SDValue RHS;
12115   ISD::CondCode CC;
12116   SDValue TrueVal;
12117   SDValue FalseVal;
12118 
12119   if (N->getOpcode() == ISD::SELECT &&
12120       N->getOperand(0)->getOpcode() == ISD::SETCC) {
12121     SetCC = N->getOperand(0);
12122     LHS = SetCC->getOperand(0);
12123     RHS = SetCC->getOperand(1);
12124     CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
12125     TrueVal = N->getOperand(1);
12126     FalseVal = N->getOperand(2);
12127   } else if (N->getOpcode() == ISD::SELECT_CC) {
12128     LHS = N->getOperand(0);
12129     RHS = N->getOperand(1);
12130     CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
12131     TrueVal = N->getOperand(2);
12132     FalseVal = N->getOperand(3);
12133   } else {
12134     return SDValue();
12135   }
12136 
12137   unsigned int Opcode = 0;
12138   if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMIN ||
12139        FalseVal->getOpcode() == ISD::VECREDUCE_UMIN) &&
12140       (CC == ISD::SETULT || CC == ISD::SETUGT)) {
12141     Opcode = ARMISD::VMINVu;
12142     if (CC == ISD::SETUGT)
12143       std::swap(TrueVal, FalseVal);
12144   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMIN ||
12145               FalseVal->getOpcode() == ISD::VECREDUCE_SMIN) &&
12146              (CC == ISD::SETLT || CC == ISD::SETGT)) {
12147     Opcode = ARMISD::VMINVs;
12148     if (CC == ISD::SETGT)
12149       std::swap(TrueVal, FalseVal);
12150   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_UMAX ||
12151               FalseVal->getOpcode() == ISD::VECREDUCE_UMAX) &&
12152              (CC == ISD::SETUGT || CC == ISD::SETULT)) {
12153     Opcode = ARMISD::VMAXVu;
12154     if (CC == ISD::SETULT)
12155       std::swap(TrueVal, FalseVal);
12156   } else if ((TrueVal->getOpcode() == ISD::VECREDUCE_SMAX ||
12157               FalseVal->getOpcode() == ISD::VECREDUCE_SMAX) &&
12158              (CC == ISD::SETGT || CC == ISD::SETLT)) {
12159     Opcode = ARMISD::VMAXVs;
12160     if (CC == ISD::SETLT)
12161       std::swap(TrueVal, FalseVal);
12162   } else
12163     return SDValue();
12164 
12165   // Normalise to the right hand side being the vector reduction
12166   switch (TrueVal->getOpcode()) {
12167   case ISD::VECREDUCE_UMIN:
12168   case ISD::VECREDUCE_SMIN:
12169   case ISD::VECREDUCE_UMAX:
12170   case ISD::VECREDUCE_SMAX:
12171     std::swap(LHS, RHS);
12172     std::swap(TrueVal, FalseVal);
12173     break;
12174   }
12175 
12176   EVT VectorType = FalseVal->getOperand(0).getValueType();
12177 
12178   if (VectorType != MVT::v16i8 && VectorType != MVT::v8i16 &&
12179       VectorType != MVT::v4i32)
12180     return SDValue();
12181 
12182   EVT VectorScalarType = VectorType.getVectorElementType();
12183 
12184   // The values being selected must also be the ones being compared
12185   if (TrueVal != LHS || FalseVal != RHS)
12186     return SDValue();
12187 
12188   EVT LeftType = LHS->getValueType(0);
12189   EVT RightType = RHS->getValueType(0);
12190 
12191   // The types must match the reduced type too
12192   if (LeftType != VectorScalarType || RightType != VectorScalarType)
12193     return SDValue();
12194 
12195   // Legalise the scalar to an i32
12196   if (VectorScalarType != MVT::i32)
12197     LHS = DCI.DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12198 
12199   // Generate the reduction as an i32 for legalisation purposes
12200   auto Reduction =
12201       DCI.DAG.getNode(Opcode, dl, MVT::i32, LHS, RHS->getOperand(0));
12202 
12203   // The result isn't actually an i32 so truncate it back to its original type
12204   if (VectorScalarType != MVT::i32)
12205     Reduction = DCI.DAG.getNode(ISD::TRUNCATE, dl, VectorScalarType, Reduction);
12206 
12207   return Reduction;
12208 }
12209 
12210 // A special combine for the vqdmulh family of instructions. This is one of the
12211 // potential set of patterns that could patch this instruction. The base pattern
12212 // you would expect to be min(max(ashr(mul(mul(sext(x), 2), sext(y)), 16))).
12213 // This matches the different min(max(ashr(mul(mul(sext(x), sext(y)), 2), 16))),
12214 // which llvm will have optimized to min(ashr(mul(sext(x), sext(y)), 15))) as
12215 // the max is unnecessary.
12216 static SDValue PerformVQDMULHCombine(SDNode *N, SelectionDAG &DAG) {
12217   EVT VT = N->getValueType(0);
12218   SDValue Shft;
12219   ConstantSDNode *Clamp;
12220 
12221   if (N->getOpcode() == ISD::SMIN) {
12222     Shft = N->getOperand(0);
12223     Clamp = isConstOrConstSplat(N->getOperand(1));
12224   } else if (N->getOpcode() == ISD::VSELECT) {
12225     // Detect a SMIN, which for an i64 node will be a vselect/setcc, not a smin.
12226     SDValue Cmp = N->getOperand(0);
12227     if (Cmp.getOpcode() != ISD::SETCC ||
12228         cast<CondCodeSDNode>(Cmp.getOperand(2))->get() != ISD::SETLT ||
12229         Cmp.getOperand(0) != N->getOperand(1) ||
12230         Cmp.getOperand(1) != N->getOperand(2))
12231       return SDValue();
12232     Shft = N->getOperand(1);
12233     Clamp = isConstOrConstSplat(N->getOperand(2));
12234   } else
12235     return SDValue();
12236 
12237   if (!Clamp)
12238     return SDValue();
12239 
12240   MVT ScalarType;
12241   int ShftAmt = 0;
12242   switch (Clamp->getSExtValue()) {
12243   case (1 << 7) - 1:
12244     ScalarType = MVT::i8;
12245     ShftAmt = 7;
12246     break;
12247   case (1 << 15) - 1:
12248     ScalarType = MVT::i16;
12249     ShftAmt = 15;
12250     break;
12251   case (1ULL << 31) - 1:
12252     ScalarType = MVT::i32;
12253     ShftAmt = 31;
12254     break;
12255   default:
12256     return SDValue();
12257   }
12258 
12259   if (Shft.getOpcode() != ISD::SRA)
12260     return SDValue();
12261   ConstantSDNode *N1 = isConstOrConstSplat(Shft.getOperand(1));
12262   if (!N1 || N1->getSExtValue() != ShftAmt)
12263     return SDValue();
12264 
12265   SDValue Mul = Shft.getOperand(0);
12266   if (Mul.getOpcode() != ISD::MUL)
12267     return SDValue();
12268 
12269   SDValue Ext0 = Mul.getOperand(0);
12270   SDValue Ext1 = Mul.getOperand(1);
12271   if (Ext0.getOpcode() != ISD::SIGN_EXTEND ||
12272       Ext1.getOpcode() != ISD::SIGN_EXTEND)
12273     return SDValue();
12274   EVT VecVT = Ext0.getOperand(0).getValueType();
12275   if (VecVT != MVT::v4i32 && VecVT != MVT::v8i16 && VecVT != MVT::v16i8)
12276     return SDValue();
12277   if (Ext1.getOperand(0).getValueType() != VecVT ||
12278       VecVT.getScalarType() != ScalarType ||
12279       VT.getScalarSizeInBits() < ScalarType.getScalarSizeInBits() * 2)
12280     return SDValue();
12281 
12282   SDLoc DL(Mul);
12283   SDValue VQDMULH = DAG.getNode(ARMISD::VQDMULH, DL, VecVT, Ext0.getOperand(0),
12284                                 Ext1.getOperand(0));
12285   return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, VQDMULH);
12286 }
12287 
12288 static SDValue PerformVSELECTCombine(SDNode *N,
12289                                      TargetLowering::DAGCombinerInfo &DCI,
12290                                      const ARMSubtarget *Subtarget) {
12291   if (!Subtarget->hasMVEIntegerOps())
12292     return SDValue();
12293 
12294   if (SDValue V = PerformVQDMULHCombine(N, DCI.DAG))
12295     return V;
12296 
12297   // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
12298   //
12299   // We need to re-implement this optimization here as the implementation in the
12300   // Target-Independent DAGCombiner does not handle the kind of constant we make
12301   // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
12302   // good reason, allowing truncation there would break other targets).
12303   //
12304   // Currently, this is only done for MVE, as it's the only target that benefits
12305   // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
12306   if (N->getOperand(0).getOpcode() != ISD::XOR)
12307     return SDValue();
12308   SDValue XOR = N->getOperand(0);
12309 
12310   // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
12311   // It is important to check with truncation allowed as the BUILD_VECTORs we
12312   // generate in those situations will truncate their operands.
12313   ConstantSDNode *Const =
12314       isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
12315                           /*AllowTruncation*/ true);
12316   if (!Const || !Const->isOne())
12317     return SDValue();
12318 
12319   // Rewrite into vselect(cond, rhs, lhs).
12320   SDValue Cond = XOR->getOperand(0);
12321   SDValue LHS = N->getOperand(1);
12322   SDValue RHS = N->getOperand(2);
12323   EVT Type = N->getValueType(0);
12324   return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
12325 }
12326 
12327 static SDValue PerformABSCombine(SDNode *N,
12328                                   TargetLowering::DAGCombinerInfo &DCI,
12329                                   const ARMSubtarget *Subtarget) {
12330   SDValue res;
12331   SelectionDAG &DAG = DCI.DAG;
12332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12333 
12334   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
12335     return SDValue();
12336 
12337   if (!TLI.expandABS(N, res, DAG))
12338       return SDValue();
12339 
12340   return res;
12341 }
12342 
12343 /// PerformADDECombine - Target-specific dag combine transform from
12344 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
12345 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
12346 static SDValue PerformADDECombine(SDNode *N,
12347                                   TargetLowering::DAGCombinerInfo &DCI,
12348                                   const ARMSubtarget *Subtarget) {
12349   // Only ARM and Thumb2 support UMLAL/SMLAL.
12350   if (Subtarget->isThumb1Only())
12351     return PerformAddeSubeCombine(N, DCI, Subtarget);
12352 
12353   // Only perform the checks after legalize when the pattern is available.
12354   if (DCI.isBeforeLegalize()) return SDValue();
12355 
12356   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
12357 }
12358 
12359 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
12360 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
12361 /// called with the default operands, and if that fails, with commuted
12362 /// operands.
12363 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
12364                                           TargetLowering::DAGCombinerInfo &DCI,
12365                                           const ARMSubtarget *Subtarget){
12366   // Attempt to create vpadd for this add.
12367   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
12368     return Result;
12369 
12370   // Attempt to create vpaddl for this add.
12371   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
12372     return Result;
12373   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
12374                                                       Subtarget))
12375     return Result;
12376 
12377   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12378   if (N0.getNode()->hasOneUse())
12379     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
12380       return Result;
12381   return SDValue();
12382 }
12383 
12384 static SDValue PerformADDVecReduce(SDNode *N,
12385                                    TargetLowering::DAGCombinerInfo &DCI,
12386                                    const ARMSubtarget *Subtarget) {
12387   if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
12388     return SDValue();
12389 
12390   SDValue N0 = N->getOperand(0);
12391   SDValue N1 = N->getOperand(1);
12392 
12393   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
12394   // will look like:
12395   //   t1: i32,i32 = ARMISD::VADDLVs x
12396   //   t2: i64 = build_pair t1, t1:1
12397   //   t3: i64 = add t2, y
12398   // We also need to check for sext / zext and commutitive adds.
12399   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
12400                            SDValue NB) {
12401     if (NB->getOpcode() != ISD::BUILD_PAIR)
12402       return SDValue();
12403     SDValue VecRed = NB->getOperand(0);
12404     if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
12405         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
12406       return SDValue();
12407 
12408     SDLoc dl(N);
12409     SmallVector<SDValue, 4> Ops;
12410     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12411                                   DCI.DAG.getConstant(0, dl, MVT::i32)));
12412     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12413                                   DCI.DAG.getConstant(1, dl, MVT::i32)));
12414     for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
12415       Ops.push_back(VecRed->getOperand(i));
12416     SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
12417                                   DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
12418     return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
12419                            SDValue(Red.getNode(), 1));
12420   };
12421 
12422   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
12423     return M;
12424   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
12425     return M;
12426   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
12427     return M;
12428   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
12429     return M;
12430   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
12431     return M;
12432   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
12433     return M;
12434   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
12435     return M;
12436   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
12437     return M;
12438   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
12439     return M;
12440   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
12441     return M;
12442   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
12443     return M;
12444   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
12445     return M;
12446   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
12447     return M;
12448   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
12449     return M;
12450   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
12451     return M;
12452   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
12453     return M;
12454   return SDValue();
12455 }
12456 
12457 bool
12458 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
12459                                                  CombineLevel Level) const {
12460   if (Level == BeforeLegalizeTypes)
12461     return true;
12462 
12463   if (N->getOpcode() != ISD::SHL)
12464     return true;
12465 
12466   if (Subtarget->isThumb1Only()) {
12467     // Avoid making expensive immediates by commuting shifts. (This logic
12468     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
12469     // for free.)
12470     if (N->getOpcode() != ISD::SHL)
12471       return true;
12472     SDValue N1 = N->getOperand(0);
12473     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
12474         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
12475       return true;
12476     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
12477       if (Const->getAPIntValue().ult(256))
12478         return false;
12479       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
12480           Const->getAPIntValue().sgt(-256))
12481         return false;
12482     }
12483     return true;
12484   }
12485 
12486   // Turn off commute-with-shift transform after legalization, so it doesn't
12487   // conflict with PerformSHLSimplify.  (We could try to detect when
12488   // PerformSHLSimplify would trigger more precisely, but it isn't
12489   // really necessary.)
12490   return false;
12491 }
12492 
12493 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
12494     const SDNode *N, CombineLevel Level) const {
12495   if (!Subtarget->isThumb1Only())
12496     return true;
12497 
12498   if (Level == BeforeLegalizeTypes)
12499     return true;
12500 
12501   return false;
12502 }
12503 
12504 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12505   if (!Subtarget->hasNEON()) {
12506     if (Subtarget->isThumb1Only())
12507       return VT.getScalarSizeInBits() <= 32;
12508     return true;
12509   }
12510   return VT.isScalarInteger();
12511 }
12512 
12513 static SDValue PerformSHLSimplify(SDNode *N,
12514                                 TargetLowering::DAGCombinerInfo &DCI,
12515                                 const ARMSubtarget *ST) {
12516   // Allow the generic combiner to identify potential bswaps.
12517   if (DCI.isBeforeLegalize())
12518     return SDValue();
12519 
12520   // DAG combiner will fold:
12521   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
12522   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
12523   // Other code patterns that can be also be modified have the following form:
12524   // b + ((a << 1) | 510)
12525   // b + ((a << 1) & 510)
12526   // b + ((a << 1) ^ 510)
12527   // b + ((a << 1) + 510)
12528 
12529   // Many instructions can  perform the shift for free, but it requires both
12530   // the operands to be registers. If c1 << c2 is too large, a mov immediate
12531   // instruction will needed. So, unfold back to the original pattern if:
12532   // - if c1 and c2 are small enough that they don't require mov imms.
12533   // - the user(s) of the node can perform an shl
12534 
12535   // No shifted operands for 16-bit instructions.
12536   if (ST->isThumb() && ST->isThumb1Only())
12537     return SDValue();
12538 
12539   // Check that all the users could perform the shl themselves.
12540   for (auto U : N->uses()) {
12541     switch(U->getOpcode()) {
12542     default:
12543       return SDValue();
12544     case ISD::SUB:
12545     case ISD::ADD:
12546     case ISD::AND:
12547     case ISD::OR:
12548     case ISD::XOR:
12549     case ISD::SETCC:
12550     case ARMISD::CMP:
12551       // Check that the user isn't already using a constant because there
12552       // aren't any instructions that support an immediate operand and a
12553       // shifted operand.
12554       if (isa<ConstantSDNode>(U->getOperand(0)) ||
12555           isa<ConstantSDNode>(U->getOperand(1)))
12556         return SDValue();
12557 
12558       // Check that it's not already using a shift.
12559       if (U->getOperand(0).getOpcode() == ISD::SHL ||
12560           U->getOperand(1).getOpcode() == ISD::SHL)
12561         return SDValue();
12562       break;
12563     }
12564   }
12565 
12566   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
12567       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
12568     return SDValue();
12569 
12570   if (N->getOperand(0).getOpcode() != ISD::SHL)
12571     return SDValue();
12572 
12573   SDValue SHL = N->getOperand(0);
12574 
12575   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
12576   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
12577   if (!C1ShlC2 || !C2)
12578     return SDValue();
12579 
12580   APInt C2Int = C2->getAPIntValue();
12581   APInt C1Int = C1ShlC2->getAPIntValue();
12582 
12583   // Check that performing a lshr will not lose any information.
12584   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
12585                                      C2Int.getBitWidth() - C2->getZExtValue());
12586   if ((C1Int & Mask) != C1Int)
12587     return SDValue();
12588 
12589   // Shift the first constant.
12590   C1Int.lshrInPlace(C2Int);
12591 
12592   // The immediates are encoded as an 8-bit value that can be rotated.
12593   auto LargeImm = [](const APInt &Imm) {
12594     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
12595     return Imm.getBitWidth() - Zeros > 8;
12596   };
12597 
12598   if (LargeImm(C1Int) || LargeImm(C2Int))
12599     return SDValue();
12600 
12601   SelectionDAG &DAG = DCI.DAG;
12602   SDLoc dl(N);
12603   SDValue X = SHL.getOperand(0);
12604   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
12605                               DAG.getConstant(C1Int, dl, MVT::i32));
12606   // Shift left to compensate for the lshr of C1Int.
12607   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
12608 
12609   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
12610              SHL.dump(); N->dump());
12611   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
12612   return Res;
12613 }
12614 
12615 
12616 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12617 ///
12618 static SDValue PerformADDCombine(SDNode *N,
12619                                  TargetLowering::DAGCombinerInfo &DCI,
12620                                  const ARMSubtarget *Subtarget) {
12621   SDValue N0 = N->getOperand(0);
12622   SDValue N1 = N->getOperand(1);
12623 
12624   // Only works one way, because it needs an immediate operand.
12625   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12626     return Result;
12627 
12628   if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12629     return Result;
12630 
12631   // First try with the default operand order.
12632   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12633     return Result;
12634 
12635   // If that didn't work, try again with the operands commuted.
12636   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12637 }
12638 
12639 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12640 ///
12641 static SDValue PerformSUBCombine(SDNode *N,
12642                                  TargetLowering::DAGCombinerInfo &DCI,
12643                                  const ARMSubtarget *Subtarget) {
12644   SDValue N0 = N->getOperand(0);
12645   SDValue N1 = N->getOperand(1);
12646 
12647   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12648   if (N1.getNode()->hasOneUse())
12649     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12650       return Result;
12651 
12652   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12653     return SDValue();
12654 
12655   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12656   // so that we can readily pattern match more mve instructions which can use
12657   // a scalar operand.
12658   SDValue VDup = N->getOperand(1);
12659   if (VDup->getOpcode() != ARMISD::VDUP)
12660     return SDValue();
12661 
12662   SDValue VMov = N->getOperand(0);
12663   if (VMov->getOpcode() == ISD::BITCAST)
12664     VMov = VMov->getOperand(0);
12665 
12666   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12667     return SDValue();
12668 
12669   SDLoc dl(N);
12670   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12671                                    DCI.DAG.getConstant(0, dl, MVT::i32),
12672                                    VDup->getOperand(0));
12673   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12674 }
12675 
12676 /// PerformVMULCombine
12677 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12678 /// special multiplier accumulator forwarding.
12679 ///   vmul d3, d0, d2
12680 ///   vmla d3, d1, d2
12681 /// is faster than
12682 ///   vadd d3, d0, d1
12683 ///   vmul d3, d3, d2
12684 //  However, for (A + B) * (A + B),
12685 //    vadd d2, d0, d1
12686 //    vmul d3, d0, d2
12687 //    vmla d3, d1, d2
12688 //  is slower than
12689 //    vadd d2, d0, d1
12690 //    vmul d3, d2, d2
12691 static SDValue PerformVMULCombine(SDNode *N,
12692                                   TargetLowering::DAGCombinerInfo &DCI,
12693                                   const ARMSubtarget *Subtarget) {
12694   if (!Subtarget->hasVMLxForwarding())
12695     return SDValue();
12696 
12697   SelectionDAG &DAG = DCI.DAG;
12698   SDValue N0 = N->getOperand(0);
12699   SDValue N1 = N->getOperand(1);
12700   unsigned Opcode = N0.getOpcode();
12701   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12702       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12703     Opcode = N1.getOpcode();
12704     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12705         Opcode != ISD::FADD && Opcode != ISD::FSUB)
12706       return SDValue();
12707     std::swap(N0, N1);
12708   }
12709 
12710   if (N0 == N1)
12711     return SDValue();
12712 
12713   EVT VT = N->getValueType(0);
12714   SDLoc DL(N);
12715   SDValue N00 = N0->getOperand(0);
12716   SDValue N01 = N0->getOperand(1);
12717   return DAG.getNode(Opcode, DL, VT,
12718                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12719                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12720 }
12721 
12722 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12723                                       const ARMSubtarget *Subtarget) {
12724   EVT VT = N->getValueType(0);
12725   if (VT != MVT::v2i64)
12726     return SDValue();
12727 
12728   SDValue N0 = N->getOperand(0);
12729   SDValue N1 = N->getOperand(1);
12730 
12731   auto IsSignExt = [&](SDValue Op) {
12732     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12733       return SDValue();
12734     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12735     if (VT.getScalarSizeInBits() == 32)
12736       return Op->getOperand(0);
12737     return SDValue();
12738   };
12739   auto IsZeroExt = [&](SDValue Op) {
12740     // Zero extends are a little more awkward. At the point we are matching
12741     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12742     // That might be before of after a bitcast depending on how the and is
12743     // placed. Because this has to look through bitcasts, it is currently only
12744     // supported on LE.
12745     if (!Subtarget->isLittle())
12746       return SDValue();
12747 
12748     SDValue And = Op;
12749     if (And->getOpcode() == ISD::BITCAST)
12750       And = And->getOperand(0);
12751     if (And->getOpcode() != ISD::AND)
12752       return SDValue();
12753     SDValue Mask = And->getOperand(1);
12754     if (Mask->getOpcode() == ISD::BITCAST)
12755       Mask = Mask->getOperand(0);
12756 
12757     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12758         Mask.getValueType() != MVT::v4i32)
12759       return SDValue();
12760     if (isAllOnesConstant(Mask->getOperand(0)) &&
12761         isNullConstant(Mask->getOperand(1)) &&
12762         isAllOnesConstant(Mask->getOperand(2)) &&
12763         isNullConstant(Mask->getOperand(3)))
12764       return And->getOperand(0);
12765     return SDValue();
12766   };
12767 
12768   SDLoc dl(N);
12769   if (SDValue Op0 = IsSignExt(N0)) {
12770     if (SDValue Op1 = IsSignExt(N1)) {
12771       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12772       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12773       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12774     }
12775   }
12776   if (SDValue Op0 = IsZeroExt(N0)) {
12777     if (SDValue Op1 = IsZeroExt(N1)) {
12778       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12779       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12780       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12781     }
12782   }
12783 
12784   return SDValue();
12785 }
12786 
12787 static SDValue PerformMULCombine(SDNode *N,
12788                                  TargetLowering::DAGCombinerInfo &DCI,
12789                                  const ARMSubtarget *Subtarget) {
12790   SelectionDAG &DAG = DCI.DAG;
12791 
12792   EVT VT = N->getValueType(0);
12793   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12794     return PerformMVEVMULLCombine(N, DAG, Subtarget);
12795 
12796   if (Subtarget->isThumb1Only())
12797     return SDValue();
12798 
12799   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12800     return SDValue();
12801 
12802   if (VT.is64BitVector() || VT.is128BitVector())
12803     return PerformVMULCombine(N, DCI, Subtarget);
12804   if (VT != MVT::i32)
12805     return SDValue();
12806 
12807   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12808   if (!C)
12809     return SDValue();
12810 
12811   int64_t MulAmt = C->getSExtValue();
12812   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12813 
12814   ShiftAmt = ShiftAmt & (32 - 1);
12815   SDValue V = N->getOperand(0);
12816   SDLoc DL(N);
12817 
12818   SDValue Res;
12819   MulAmt >>= ShiftAmt;
12820 
12821   if (MulAmt >= 0) {
12822     if (isPowerOf2_32(MulAmt - 1)) {
12823       // (mul x, 2^N + 1) => (add (shl x, N), x)
12824       Res = DAG.getNode(ISD::ADD, DL, VT,
12825                         V,
12826                         DAG.getNode(ISD::SHL, DL, VT,
12827                                     V,
12828                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
12829                                                     MVT::i32)));
12830     } else if (isPowerOf2_32(MulAmt + 1)) {
12831       // (mul x, 2^N - 1) => (sub (shl x, N), x)
12832       Res = DAG.getNode(ISD::SUB, DL, VT,
12833                         DAG.getNode(ISD::SHL, DL, VT,
12834                                     V,
12835                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
12836                                                     MVT::i32)),
12837                         V);
12838     } else
12839       return SDValue();
12840   } else {
12841     uint64_t MulAmtAbs = -MulAmt;
12842     if (isPowerOf2_32(MulAmtAbs + 1)) {
12843       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12844       Res = DAG.getNode(ISD::SUB, DL, VT,
12845                         V,
12846                         DAG.getNode(ISD::SHL, DL, VT,
12847                                     V,
12848                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12849                                                     MVT::i32)));
12850     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12851       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12852       Res = DAG.getNode(ISD::ADD, DL, VT,
12853                         V,
12854                         DAG.getNode(ISD::SHL, DL, VT,
12855                                     V,
12856                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12857                                                     MVT::i32)));
12858       Res = DAG.getNode(ISD::SUB, DL, VT,
12859                         DAG.getConstant(0, DL, MVT::i32), Res);
12860     } else
12861       return SDValue();
12862   }
12863 
12864   if (ShiftAmt != 0)
12865     Res = DAG.getNode(ISD::SHL, DL, VT,
12866                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12867 
12868   // Do not add new nodes to DAG combiner worklist.
12869   DCI.CombineTo(N, Res, false);
12870   return SDValue();
12871 }
12872 
12873 static SDValue CombineANDShift(SDNode *N,
12874                                TargetLowering::DAGCombinerInfo &DCI,
12875                                const ARMSubtarget *Subtarget) {
12876   // Allow DAGCombine to pattern-match before we touch the canonical form.
12877   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12878     return SDValue();
12879 
12880   if (N->getValueType(0) != MVT::i32)
12881     return SDValue();
12882 
12883   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12884   if (!N1C)
12885     return SDValue();
12886 
12887   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12888   // Don't transform uxtb/uxth.
12889   if (C1 == 255 || C1 == 65535)
12890     return SDValue();
12891 
12892   SDNode *N0 = N->getOperand(0).getNode();
12893   if (!N0->hasOneUse())
12894     return SDValue();
12895 
12896   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12897     return SDValue();
12898 
12899   bool LeftShift = N0->getOpcode() == ISD::SHL;
12900 
12901   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12902   if (!N01C)
12903     return SDValue();
12904 
12905   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12906   if (!C2 || C2 >= 32)
12907     return SDValue();
12908 
12909   // Clear irrelevant bits in the mask.
12910   if (LeftShift)
12911     C1 &= (-1U << C2);
12912   else
12913     C1 &= (-1U >> C2);
12914 
12915   SelectionDAG &DAG = DCI.DAG;
12916   SDLoc DL(N);
12917 
12918   // We have a pattern of the form "(and (shl x, c2) c1)" or
12919   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12920   // transform to a pair of shifts, to save materializing c1.
12921 
12922   // First pattern: right shift, then mask off leading bits.
12923   // FIXME: Use demanded bits?
12924   if (!LeftShift && isMask_32(C1)) {
12925     uint32_t C3 = countLeadingZeros(C1);
12926     if (C2 < C3) {
12927       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12928                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12929       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12930                          DAG.getConstant(C3, DL, MVT::i32));
12931     }
12932   }
12933 
12934   // First pattern, reversed: left shift, then mask off trailing bits.
12935   if (LeftShift && isMask_32(~C1)) {
12936     uint32_t C3 = countTrailingZeros(C1);
12937     if (C2 < C3) {
12938       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12939                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12940       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12941                          DAG.getConstant(C3, DL, MVT::i32));
12942     }
12943   }
12944 
12945   // Second pattern: left shift, then mask off leading bits.
12946   // FIXME: Use demanded bits?
12947   if (LeftShift && isShiftedMask_32(C1)) {
12948     uint32_t Trailing = countTrailingZeros(C1);
12949     uint32_t C3 = countLeadingZeros(C1);
12950     if (Trailing == C2 && C2 + C3 < 32) {
12951       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12952                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12953       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12954                         DAG.getConstant(C3, DL, MVT::i32));
12955     }
12956   }
12957 
12958   // Second pattern, reversed: right shift, then mask off trailing bits.
12959   // FIXME: Handle other patterns of known/demanded bits.
12960   if (!LeftShift && isShiftedMask_32(C1)) {
12961     uint32_t Leading = countLeadingZeros(C1);
12962     uint32_t C3 = countTrailingZeros(C1);
12963     if (Leading == C2 && C2 + C3 < 32) {
12964       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12965                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12966       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12967                          DAG.getConstant(C3, DL, MVT::i32));
12968     }
12969   }
12970 
12971   // FIXME: Transform "(and (shl x, c2) c1)" ->
12972   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12973   // c1.
12974   return SDValue();
12975 }
12976 
12977 static SDValue PerformANDCombine(SDNode *N,
12978                                  TargetLowering::DAGCombinerInfo &DCI,
12979                                  const ARMSubtarget *Subtarget) {
12980   // Attempt to use immediate-form VBIC
12981   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12982   SDLoc dl(N);
12983   EVT VT = N->getValueType(0);
12984   SelectionDAG &DAG = DCI.DAG;
12985 
12986   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
12987       VT == MVT::v8i1 || VT == MVT::v16i1)
12988     return SDValue();
12989 
12990   APInt SplatBits, SplatUndef;
12991   unsigned SplatBitSize;
12992   bool HasAnyUndefs;
12993   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12994       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12995     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
12996         SplatBitSize == 64) {
12997       EVT VbicVT;
12998       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
12999                                       SplatUndef.getZExtValue(), SplatBitSize,
13000                                       DAG, dl, VbicVT, VT, OtherModImm);
13001       if (Val.getNode()) {
13002         SDValue Input =
13003           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
13004         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
13005         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
13006       }
13007     }
13008   }
13009 
13010   if (!Subtarget->isThumb1Only()) {
13011     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
13012     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
13013       return Result;
13014 
13015     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13016       return Result;
13017   }
13018 
13019   if (Subtarget->isThumb1Only())
13020     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
13021       return Result;
13022 
13023   return SDValue();
13024 }
13025 
13026 // Try combining OR nodes to SMULWB, SMULWT.
13027 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
13028                                          TargetLowering::DAGCombinerInfo &DCI,
13029                                          const ARMSubtarget *Subtarget) {
13030   if (!Subtarget->hasV6Ops() ||
13031       (Subtarget->isThumb() &&
13032        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
13033     return SDValue();
13034 
13035   SDValue SRL = OR->getOperand(0);
13036   SDValue SHL = OR->getOperand(1);
13037 
13038   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
13039     SRL = OR->getOperand(1);
13040     SHL = OR->getOperand(0);
13041   }
13042   if (!isSRL16(SRL) || !isSHL16(SHL))
13043     return SDValue();
13044 
13045   // The first operands to the shifts need to be the two results from the
13046   // same smul_lohi node.
13047   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
13048        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
13049     return SDValue();
13050 
13051   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
13052   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
13053       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
13054     return SDValue();
13055 
13056   // Now we have:
13057   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
13058   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
13059   // For SMUWB the 16-bit value will signed extended somehow.
13060   // For SMULWT only the SRA is required.
13061   // Check both sides of SMUL_LOHI
13062   SDValue OpS16 = SMULLOHI->getOperand(0);
13063   SDValue OpS32 = SMULLOHI->getOperand(1);
13064 
13065   SelectionDAG &DAG = DCI.DAG;
13066   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
13067     OpS16 = OpS32;
13068     OpS32 = SMULLOHI->getOperand(0);
13069   }
13070 
13071   SDLoc dl(OR);
13072   unsigned Opcode = 0;
13073   if (isS16(OpS16, DAG))
13074     Opcode = ARMISD::SMULWB;
13075   else if (isSRA16(OpS16)) {
13076     Opcode = ARMISD::SMULWT;
13077     OpS16 = OpS16->getOperand(0);
13078   }
13079   else
13080     return SDValue();
13081 
13082   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
13083   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
13084   return SDValue(OR, 0);
13085 }
13086 
13087 static SDValue PerformORCombineToBFI(SDNode *N,
13088                                      TargetLowering::DAGCombinerInfo &DCI,
13089                                      const ARMSubtarget *Subtarget) {
13090   // BFI is only available on V6T2+
13091   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
13092     return SDValue();
13093 
13094   EVT VT = N->getValueType(0);
13095   SDValue N0 = N->getOperand(0);
13096   SDValue N1 = N->getOperand(1);
13097   SelectionDAG &DAG = DCI.DAG;
13098   SDLoc DL(N);
13099   // 1) or (and A, mask), val => ARMbfi A, val, mask
13100   //      iff (val & mask) == val
13101   //
13102   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13103   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
13104   //          && mask == ~mask2
13105   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
13106   //          && ~mask == mask2
13107   //  (i.e., copy a bitfield value into another bitfield of the same width)
13108 
13109   if (VT != MVT::i32)
13110     return SDValue();
13111 
13112   SDValue N00 = N0.getOperand(0);
13113 
13114   // The value and the mask need to be constants so we can verify this is
13115   // actually a bitfield set. If the mask is 0xffff, we can do better
13116   // via a movt instruction, so don't use BFI in that case.
13117   SDValue MaskOp = N0.getOperand(1);
13118   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
13119   if (!MaskC)
13120     return SDValue();
13121   unsigned Mask = MaskC->getZExtValue();
13122   if (Mask == 0xffff)
13123     return SDValue();
13124   SDValue Res;
13125   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
13126   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13127   if (N1C) {
13128     unsigned Val = N1C->getZExtValue();
13129     if ((Val & ~Mask) != Val)
13130       return SDValue();
13131 
13132     if (ARM::isBitFieldInvertedMask(Mask)) {
13133       Val >>= countTrailingZeros(~Mask);
13134 
13135       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
13136                         DAG.getConstant(Val, DL, MVT::i32),
13137                         DAG.getConstant(Mask, DL, MVT::i32));
13138 
13139       DCI.CombineTo(N, Res, false);
13140       // Return value from the original node to inform the combiner than N is
13141       // now dead.
13142       return SDValue(N, 0);
13143     }
13144   } else if (N1.getOpcode() == ISD::AND) {
13145     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
13146     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13147     if (!N11C)
13148       return SDValue();
13149     unsigned Mask2 = N11C->getZExtValue();
13150 
13151     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
13152     // as is to match.
13153     if (ARM::isBitFieldInvertedMask(Mask) &&
13154         (Mask == ~Mask2)) {
13155       // The pack halfword instruction works better for masks that fit it,
13156       // so use that when it's available.
13157       if (Subtarget->hasDSP() &&
13158           (Mask == 0xffff || Mask == 0xffff0000))
13159         return SDValue();
13160       // 2a
13161       unsigned amt = countTrailingZeros(Mask2);
13162       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
13163                         DAG.getConstant(amt, DL, MVT::i32));
13164       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
13165                         DAG.getConstant(Mask, DL, MVT::i32));
13166       DCI.CombineTo(N, Res, false);
13167       // Return value from the original node to inform the combiner than N is
13168       // now dead.
13169       return SDValue(N, 0);
13170     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
13171                (~Mask == Mask2)) {
13172       // The pack halfword instruction works better for masks that fit it,
13173       // so use that when it's available.
13174       if (Subtarget->hasDSP() &&
13175           (Mask2 == 0xffff || Mask2 == 0xffff0000))
13176         return SDValue();
13177       // 2b
13178       unsigned lsb = countTrailingZeros(Mask);
13179       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
13180                         DAG.getConstant(lsb, DL, MVT::i32));
13181       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
13182                         DAG.getConstant(Mask2, DL, MVT::i32));
13183       DCI.CombineTo(N, Res, false);
13184       // Return value from the original node to inform the combiner than N is
13185       // now dead.
13186       return SDValue(N, 0);
13187     }
13188   }
13189 
13190   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
13191       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
13192       ARM::isBitFieldInvertedMask(~Mask)) {
13193     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
13194     // where lsb(mask) == #shamt and masked bits of B are known zero.
13195     SDValue ShAmt = N00.getOperand(1);
13196     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
13197     unsigned LSB = countTrailingZeros(Mask);
13198     if (ShAmtC != LSB)
13199       return SDValue();
13200 
13201     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
13202                       DAG.getConstant(~Mask, DL, MVT::i32));
13203 
13204     DCI.CombineTo(N, Res, false);
13205     // Return value from the original node to inform the combiner than N is
13206     // now dead.
13207     return SDValue(N, 0);
13208   }
13209 
13210   return SDValue();
13211 }
13212 
13213 static bool isValidMVECond(unsigned CC, bool IsFloat) {
13214   switch (CC) {
13215   case ARMCC::EQ:
13216   case ARMCC::NE:
13217   case ARMCC::LE:
13218   case ARMCC::GT:
13219   case ARMCC::GE:
13220   case ARMCC::LT:
13221     return true;
13222   case ARMCC::HS:
13223   case ARMCC::HI:
13224     return !IsFloat;
13225   default:
13226     return false;
13227   };
13228 }
13229 
13230 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
13231   if (N->getOpcode() == ARMISD::VCMP)
13232     return (ARMCC::CondCodes)N->getConstantOperandVal(2);
13233   else if (N->getOpcode() == ARMISD::VCMPZ)
13234     return (ARMCC::CondCodes)N->getConstantOperandVal(1);
13235   else
13236     llvm_unreachable("Not a VCMP/VCMPZ!");
13237 }
13238 
13239 static bool CanInvertMVEVCMP(SDValue N) {
13240   ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
13241   return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
13242 }
13243 
13244 static SDValue PerformORCombine_i1(SDNode *N,
13245                                    TargetLowering::DAGCombinerInfo &DCI,
13246                                    const ARMSubtarget *Subtarget) {
13247   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
13248   // together with predicates
13249   EVT VT = N->getValueType(0);
13250   SDLoc DL(N);
13251   SDValue N0 = N->getOperand(0);
13252   SDValue N1 = N->getOperand(1);
13253 
13254   auto IsFreelyInvertable = [&](SDValue V) {
13255     if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
13256       return CanInvertMVEVCMP(V);
13257     return false;
13258   };
13259 
13260   // At least one operand must be freely invertable.
13261   if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
13262     return SDValue();
13263 
13264   SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT);
13265   SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT);
13266   SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
13267   return DCI.DAG.getLogicalNOT(DL, And, VT);
13268 }
13269 
13270 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
13271 static SDValue PerformORCombine(SDNode *N,
13272                                 TargetLowering::DAGCombinerInfo &DCI,
13273                                 const ARMSubtarget *Subtarget) {
13274   // Attempt to use immediate-form VORR
13275   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13276   SDLoc dl(N);
13277   EVT VT = N->getValueType(0);
13278   SelectionDAG &DAG = DCI.DAG;
13279 
13280   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13281     return SDValue();
13282 
13283   if (Subtarget->hasMVEIntegerOps() &&
13284       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
13285     return PerformORCombine_i1(N, DCI, Subtarget);
13286 
13287   APInt SplatBits, SplatUndef;
13288   unsigned SplatBitSize;
13289   bool HasAnyUndefs;
13290   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13291       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13292     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13293         SplatBitSize == 64) {
13294       EVT VorrVT;
13295       SDValue Val =
13296           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
13297                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
13298       if (Val.getNode()) {
13299         SDValue Input =
13300           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
13301         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
13302         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
13303       }
13304     }
13305   }
13306 
13307   if (!Subtarget->isThumb1Only()) {
13308     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
13309     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13310       return Result;
13311     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
13312       return Result;
13313   }
13314 
13315   SDValue N0 = N->getOperand(0);
13316   SDValue N1 = N->getOperand(1);
13317 
13318   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
13319   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
13320       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13321 
13322     // The code below optimizes (or (and X, Y), Z).
13323     // The AND operand needs to have a single user to make these optimizations
13324     // profitable.
13325     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
13326       return SDValue();
13327 
13328     APInt SplatUndef;
13329     unsigned SplatBitSize;
13330     bool HasAnyUndefs;
13331 
13332     APInt SplatBits0, SplatBits1;
13333     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
13334     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
13335     // Ensure that the second operand of both ands are constants
13336     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
13337                                       HasAnyUndefs) && !HasAnyUndefs) {
13338         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
13339                                           HasAnyUndefs) && !HasAnyUndefs) {
13340             // Ensure that the bit width of the constants are the same and that
13341             // the splat arguments are logical inverses as per the pattern we
13342             // are trying to simplify.
13343             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
13344                 SplatBits0 == ~SplatBits1) {
13345                 // Canonicalize the vector type to make instruction selection
13346                 // simpler.
13347                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
13348                 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
13349                                              N0->getOperand(1),
13350                                              N0->getOperand(0),
13351                                              N1->getOperand(0));
13352                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13353             }
13354         }
13355     }
13356   }
13357 
13358   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
13359   // reasonable.
13360   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
13361     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
13362       return Res;
13363   }
13364 
13365   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13366     return Result;
13367 
13368   return SDValue();
13369 }
13370 
13371 static SDValue PerformXORCombine(SDNode *N,
13372                                  TargetLowering::DAGCombinerInfo &DCI,
13373                                  const ARMSubtarget *Subtarget) {
13374   EVT VT = N->getValueType(0);
13375   SelectionDAG &DAG = DCI.DAG;
13376 
13377   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13378     return SDValue();
13379 
13380   if (!Subtarget->isThumb1Only()) {
13381     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
13382     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13383       return Result;
13384 
13385     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13386       return Result;
13387   }
13388 
13389   if (Subtarget->hasMVEIntegerOps()) {
13390     // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
13391     SDValue N0 = N->getOperand(0);
13392     SDValue N1 = N->getOperand(1);
13393     const TargetLowering *TLI = Subtarget->getTargetLowering();
13394     if (TLI->isConstTrueVal(N1.getNode()) &&
13395         (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
13396       if (CanInvertMVEVCMP(N0)) {
13397         SDLoc DL(N0);
13398         ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
13399 
13400         SmallVector<SDValue, 4> Ops;
13401         Ops.push_back(N0->getOperand(0));
13402         if (N0->getOpcode() == ARMISD::VCMP)
13403           Ops.push_back(N0->getOperand(1));
13404         Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32));
13405         return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
13406       }
13407     }
13408   }
13409 
13410   return SDValue();
13411 }
13412 
13413 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
13414 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
13415 // their position in "to" (Rd).
13416 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
13417   assert(N->getOpcode() == ARMISD::BFI);
13418 
13419   SDValue From = N->getOperand(1);
13420   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
13421   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
13422 
13423   // If the Base came from a SHR #C, we can deduce that it is really testing bit
13424   // #C in the base of the SHR.
13425   if (From->getOpcode() == ISD::SRL &&
13426       isa<ConstantSDNode>(From->getOperand(1))) {
13427     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
13428     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
13429     FromMask <<= Shift.getLimitedValue(31);
13430     From = From->getOperand(0);
13431   }
13432 
13433   return From;
13434 }
13435 
13436 // If A and B contain one contiguous set of bits, does A | B == A . B?
13437 //
13438 // Neither A nor B must be zero.
13439 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
13440   unsigned LastActiveBitInA =  A.countTrailingZeros();
13441   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
13442   return LastActiveBitInA - 1 == FirstActiveBitInB;
13443 }
13444 
13445 static SDValue FindBFIToCombineWith(SDNode *N) {
13446   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
13447   // if one exists.
13448   APInt ToMask, FromMask;
13449   SDValue From = ParseBFI(N, ToMask, FromMask);
13450   SDValue To = N->getOperand(0);
13451 
13452   // Now check for a compatible BFI to merge with. We can pass through BFIs that
13453   // aren't compatible, but not if they set the same bit in their destination as
13454   // we do (or that of any BFI we're going to combine with).
13455   SDValue V = To;
13456   APInt CombinedToMask = ToMask;
13457   while (V.getOpcode() == ARMISD::BFI) {
13458     APInt NewToMask, NewFromMask;
13459     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
13460     if (NewFrom != From) {
13461       // This BFI has a different base. Keep going.
13462       CombinedToMask |= NewToMask;
13463       V = V.getOperand(0);
13464       continue;
13465     }
13466 
13467     // Do the written bits conflict with any we've seen so far?
13468     if ((NewToMask & CombinedToMask).getBoolValue())
13469       // Conflicting bits - bail out because going further is unsafe.
13470       return SDValue();
13471 
13472     // Are the new bits contiguous when combined with the old bits?
13473     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
13474         BitsProperlyConcatenate(FromMask, NewFromMask))
13475       return V;
13476     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
13477         BitsProperlyConcatenate(NewFromMask, FromMask))
13478       return V;
13479 
13480     // We've seen a write to some bits, so track it.
13481     CombinedToMask |= NewToMask;
13482     // Keep going...
13483     V = V.getOperand(0);
13484   }
13485 
13486   return SDValue();
13487 }
13488 
13489 static SDValue PerformBFICombine(SDNode *N,
13490                                  TargetLowering::DAGCombinerInfo &DCI) {
13491   SDValue N1 = N->getOperand(1);
13492   if (N1.getOpcode() == ISD::AND) {
13493     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
13494     // the bits being cleared by the AND are not demanded by the BFI.
13495     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13496     if (!N11C)
13497       return SDValue();
13498     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13499     unsigned LSB = countTrailingZeros(~InvMask);
13500     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
13501     assert(Width <
13502                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
13503            "undefined behavior");
13504     unsigned Mask = (1u << Width) - 1;
13505     unsigned Mask2 = N11C->getZExtValue();
13506     if ((Mask & (~Mask2)) == 0)
13507       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
13508                              N->getOperand(0), N1.getOperand(0),
13509                              N->getOperand(2));
13510   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
13511     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
13512     // Keep track of any consecutive bits set that all come from the same base
13513     // value. We can combine these together into a single BFI.
13514     SDValue CombineBFI = FindBFIToCombineWith(N);
13515     if (CombineBFI == SDValue())
13516       return SDValue();
13517 
13518     // We've found a BFI.
13519     APInt ToMask1, FromMask1;
13520     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
13521 
13522     APInt ToMask2, FromMask2;
13523     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
13524     assert(From1 == From2);
13525     (void)From2;
13526 
13527     // First, unlink CombineBFI.
13528     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
13529     // Then create a new BFI, combining the two together.
13530     APInt NewFromMask = FromMask1 | FromMask2;
13531     APInt NewToMask = ToMask1 | ToMask2;
13532 
13533     EVT VT = N->getValueType(0);
13534     SDLoc dl(N);
13535 
13536     if (NewFromMask[0] == 0)
13537       From1 = DCI.DAG.getNode(
13538         ISD::SRL, dl, VT, From1,
13539         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
13540     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
13541                            DCI.DAG.getConstant(~NewToMask, dl, VT));
13542   }
13543   return SDValue();
13544 }
13545 
13546 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
13547 /// ARMISD::VMOVRRD.
13548 static SDValue PerformVMOVRRDCombine(SDNode *N,
13549                                      TargetLowering::DAGCombinerInfo &DCI,
13550                                      const ARMSubtarget *Subtarget) {
13551   // vmovrrd(vmovdrr x, y) -> x,y
13552   SDValue InDouble = N->getOperand(0);
13553   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
13554     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
13555 
13556   // vmovrrd(load f64) -> (load i32), (load i32)
13557   SDNode *InNode = InDouble.getNode();
13558   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
13559       InNode->getValueType(0) == MVT::f64 &&
13560       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
13561       !cast<LoadSDNode>(InNode)->isVolatile()) {
13562     // TODO: Should this be done for non-FrameIndex operands?
13563     LoadSDNode *LD = cast<LoadSDNode>(InNode);
13564 
13565     SelectionDAG &DAG = DCI.DAG;
13566     SDLoc DL(LD);
13567     SDValue BasePtr = LD->getBasePtr();
13568     SDValue NewLD1 =
13569         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
13570                     LD->getAlignment(), LD->getMemOperand()->getFlags());
13571 
13572     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13573                                     DAG.getConstant(4, DL, MVT::i32));
13574 
13575     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
13576                                  LD->getPointerInfo().getWithOffset(4),
13577                                  std::min(4U, LD->getAlignment()),
13578                                  LD->getMemOperand()->getFlags());
13579 
13580     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
13581     if (DCI.DAG.getDataLayout().isBigEndian())
13582       std::swap (NewLD1, NewLD2);
13583     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
13584     return Result;
13585   }
13586 
13587   return SDValue();
13588 }
13589 
13590 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
13591 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
13592 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
13593   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
13594   SDValue Op0 = N->getOperand(0);
13595   SDValue Op1 = N->getOperand(1);
13596   if (Op0.getOpcode() == ISD::BITCAST)
13597     Op0 = Op0.getOperand(0);
13598   if (Op1.getOpcode() == ISD::BITCAST)
13599     Op1 = Op1.getOperand(0);
13600   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
13601       Op0.getNode() == Op1.getNode() &&
13602       Op0.getResNo() == 0 && Op1.getResNo() == 1)
13603     return DAG.getNode(ISD::BITCAST, SDLoc(N),
13604                        N->getValueType(0), Op0.getOperand(0));
13605   return SDValue();
13606 }
13607 
13608 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13609   SDValue Op0 = N->getOperand(0);
13610 
13611   // VMOVhr (VMOVrh (X)) -> X
13612   if (Op0->getOpcode() == ARMISD::VMOVrh)
13613     return Op0->getOperand(0);
13614 
13615   // FullFP16: half values are passed in S-registers, and we don't
13616   // need any of the bitcast and moves:
13617   //
13618   //     t2: f32,ch = CopyFromReg t0, Register:f32 %0
13619   //   t5: i32 = bitcast t2
13620   // t18: f16 = ARMISD::VMOVhr t5
13621   if (Op0->getOpcode() == ISD::BITCAST) {
13622     SDValue Copy = Op0->getOperand(0);
13623     if (Copy.getValueType() == MVT::f32 &&
13624         Copy->getOpcode() == ISD::CopyFromReg) {
13625       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
13626       SDValue NewCopy =
13627           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
13628       return NewCopy;
13629     }
13630   }
13631 
13632   // fold (VMOVhr (load x)) -> (load (f16*)x)
13633   if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
13634     if (LN0->hasOneUse() && LN0->isUnindexed() &&
13635         LN0->getMemoryVT() == MVT::i16) {
13636       SDValue Load =
13637           DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
13638                           LN0->getBasePtr(), LN0->getMemOperand());
13639       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13640       DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
13641       return Load;
13642     }
13643   }
13644 
13645   // Only the bottom 16 bits of the source register are used.
13646   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13647   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13648   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13649     return SDValue(N, 0);
13650 
13651   return SDValue();
13652 }
13653 
13654 static SDValue PerformVMOVrhCombine(SDNode *N,
13655                                     TargetLowering::DAGCombinerInfo &DCI) {
13656   SDValue N0 = N->getOperand(0);
13657   EVT VT = N->getValueType(0);
13658 
13659   // fold (VMOVrh (fpconst x)) -> const x
13660   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
13661     APFloat V = C->getValueAPF();
13662     return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
13663   }
13664 
13665   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13666   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13667     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13668 
13669     SDValue Load =
13670         DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13671                            LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13672     DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13673     DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13674     return Load;
13675   }
13676 
13677   // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
13678   if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13679       isa<ConstantSDNode>(N0->getOperand(1)))
13680     return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
13681                            N0->getOperand(1));
13682 
13683   return SDValue();
13684 }
13685 
13686 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13687 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
13688 /// i64 vector to have f64 elements, since the value can then be loaded
13689 /// directly into a VFP register.
13690 static bool hasNormalLoadOperand(SDNode *N) {
13691   unsigned NumElts = N->getValueType(0).getVectorNumElements();
13692   for (unsigned i = 0; i < NumElts; ++i) {
13693     SDNode *Elt = N->getOperand(i).getNode();
13694     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13695       return true;
13696   }
13697   return false;
13698 }
13699 
13700 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13701 /// ISD::BUILD_VECTOR.
13702 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13703                                           TargetLowering::DAGCombinerInfo &DCI,
13704                                           const ARMSubtarget *Subtarget) {
13705   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13706   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
13707   // into a pair of GPRs, which is fine when the value is used as a scalar,
13708   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13709   SelectionDAG &DAG = DCI.DAG;
13710   if (N->getNumOperands() == 2)
13711     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13712       return RV;
13713 
13714   // Load i64 elements as f64 values so that type legalization does not split
13715   // them up into i32 values.
13716   EVT VT = N->getValueType(0);
13717   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13718     return SDValue();
13719   SDLoc dl(N);
13720   SmallVector<SDValue, 8> Ops;
13721   unsigned NumElts = VT.getVectorNumElements();
13722   for (unsigned i = 0; i < NumElts; ++i) {
13723     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13724     Ops.push_back(V);
13725     // Make the DAGCombiner fold the bitcast.
13726     DCI.AddToWorklist(V.getNode());
13727   }
13728   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13729   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13730   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13731 }
13732 
13733 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13734 static SDValue
13735 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13736   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13737   // At that time, we may have inserted bitcasts from integer to float.
13738   // If these bitcasts have survived DAGCombine, change the lowering of this
13739   // BUILD_VECTOR in something more vector friendly, i.e., that does not
13740   // force to use floating point types.
13741 
13742   // Make sure we can change the type of the vector.
13743   // This is possible iff:
13744   // 1. The vector is only used in a bitcast to a integer type. I.e.,
13745   //    1.1. Vector is used only once.
13746   //    1.2. Use is a bit convert to an integer type.
13747   // 2. The size of its operands are 32-bits (64-bits are not legal).
13748   EVT VT = N->getValueType(0);
13749   EVT EltVT = VT.getVectorElementType();
13750 
13751   // Check 1.1. and 2.
13752   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13753     return SDValue();
13754 
13755   // By construction, the input type must be float.
13756   assert(EltVT == MVT::f32 && "Unexpected type!");
13757 
13758   // Check 1.2.
13759   SDNode *Use = *N->use_begin();
13760   if (Use->getOpcode() != ISD::BITCAST ||
13761       Use->getValueType(0).isFloatingPoint())
13762     return SDValue();
13763 
13764   // Check profitability.
13765   // Model is, if more than half of the relevant operands are bitcast from
13766   // i32, turn the build_vector into a sequence of insert_vector_elt.
13767   // Relevant operands are everything that is not statically
13768   // (i.e., at compile time) bitcasted.
13769   unsigned NumOfBitCastedElts = 0;
13770   unsigned NumElts = VT.getVectorNumElements();
13771   unsigned NumOfRelevantElts = NumElts;
13772   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13773     SDValue Elt = N->getOperand(Idx);
13774     if (Elt->getOpcode() == ISD::BITCAST) {
13775       // Assume only bit cast to i32 will go away.
13776       if (Elt->getOperand(0).getValueType() == MVT::i32)
13777         ++NumOfBitCastedElts;
13778     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13779       // Constants are statically casted, thus do not count them as
13780       // relevant operands.
13781       --NumOfRelevantElts;
13782   }
13783 
13784   // Check if more than half of the elements require a non-free bitcast.
13785   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13786     return SDValue();
13787 
13788   SelectionDAG &DAG = DCI.DAG;
13789   // Create the new vector type.
13790   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13791   // Check if the type is legal.
13792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13793   if (!TLI.isTypeLegal(VecVT))
13794     return SDValue();
13795 
13796   // Combine:
13797   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13798   // => BITCAST INSERT_VECTOR_ELT
13799   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13800   //                      (BITCAST EN), N.
13801   SDValue Vec = DAG.getUNDEF(VecVT);
13802   SDLoc dl(N);
13803   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13804     SDValue V = N->getOperand(Idx);
13805     if (V.isUndef())
13806       continue;
13807     if (V.getOpcode() == ISD::BITCAST &&
13808         V->getOperand(0).getValueType() == MVT::i32)
13809       // Fold obvious case.
13810       V = V.getOperand(0);
13811     else {
13812       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13813       // Make the DAGCombiner fold the bitcasts.
13814       DCI.AddToWorklist(V.getNode());
13815     }
13816     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13817     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13818   }
13819   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13820   // Make the DAGCombiner fold the bitcasts.
13821   DCI.AddToWorklist(Vec.getNode());
13822   return Vec;
13823 }
13824 
13825 static SDValue
13826 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13827   EVT VT = N->getValueType(0);
13828   SDValue Op = N->getOperand(0);
13829   SDLoc dl(N);
13830 
13831   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13832   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13833     // If the valuetypes are the same, we can remove the cast entirely.
13834     if (Op->getOperand(0).getValueType() == VT)
13835       return Op->getOperand(0);
13836     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13837   }
13838 
13839   return SDValue();
13840 }
13841 
13842 static SDValue
13843 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13844                               const ARMSubtarget *ST) {
13845   EVT VT = N->getValueType(0);
13846   SDValue Op = N->getOperand(0);
13847   SDLoc dl(N);
13848 
13849   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13850   if (ST->isLittle())
13851     return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13852 
13853   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13854   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13855     // If the valuetypes are the same, we can remove the cast entirely.
13856     if (Op->getOperand(0).getValueType() == VT)
13857       return Op->getOperand(0);
13858     return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13859   }
13860 
13861   return SDValue();
13862 }
13863 
13864 static SDValue PerformVCMPCombine(SDNode *N,
13865                                   TargetLowering::DAGCombinerInfo &DCI,
13866                                   const ARMSubtarget *Subtarget) {
13867   if (!Subtarget->hasMVEIntegerOps())
13868     return SDValue();
13869 
13870   EVT VT = N->getValueType(0);
13871   SDValue Op0 = N->getOperand(0);
13872   SDValue Op1 = N->getOperand(1);
13873   ARMCC::CondCodes Cond =
13874       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13875   SDLoc dl(N);
13876 
13877   // vcmp X, 0, cc -> vcmpz X, cc
13878   if (isZeroVector(Op1))
13879     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13880                            N->getOperand(2));
13881 
13882   unsigned SwappedCond = getSwappedCondition(Cond);
13883   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13884     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13885     if (isZeroVector(Op0))
13886       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13887                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13888     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13889     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13890       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13891                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13892   }
13893 
13894   return SDValue();
13895 }
13896 
13897 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13898 /// ISD::INSERT_VECTOR_ELT.
13899 static SDValue PerformInsertEltCombine(SDNode *N,
13900                                        TargetLowering::DAGCombinerInfo &DCI) {
13901   // Bitcast an i64 load inserted into a vector to f64.
13902   // Otherwise, the i64 value will be legalized to a pair of i32 values.
13903   EVT VT = N->getValueType(0);
13904   SDNode *Elt = N->getOperand(1).getNode();
13905   if (VT.getVectorElementType() != MVT::i64 ||
13906       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13907     return SDValue();
13908 
13909   SelectionDAG &DAG = DCI.DAG;
13910   SDLoc dl(N);
13911   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13912                                  VT.getVectorNumElements());
13913   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13914   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13915   // Make the DAGCombiner fold the bitcasts.
13916   DCI.AddToWorklist(Vec.getNode());
13917   DCI.AddToWorklist(V.getNode());
13918   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13919                                Vec, V, N->getOperand(2));
13920   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13921 }
13922 
13923 static SDValue PerformExtractEltCombine(SDNode *N,
13924                                         TargetLowering::DAGCombinerInfo &DCI) {
13925   SDValue Op0 = N->getOperand(0);
13926   EVT VT = N->getValueType(0);
13927   SDLoc dl(N);
13928 
13929   // extract (vdup x) -> x
13930   if (Op0->getOpcode() == ARMISD::VDUP) {
13931     SDValue X = Op0->getOperand(0);
13932     if (VT == MVT::f16 && X.getValueType() == MVT::i32)
13933       return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
13934     if (VT == MVT::i32 && X.getValueType() == MVT::f16)
13935       return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
13936 
13937     while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
13938       X = X->getOperand(0);
13939     if (X.getValueType() == VT)
13940       return X;
13941   }
13942 
13943   return SDValue();
13944 }
13945 
13946 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13947 /// ISD::VECTOR_SHUFFLE.
13948 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13949   // The LLVM shufflevector instruction does not require the shuffle mask
13950   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
13951   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
13952   // operands do not match the mask length, they are extended by concatenating
13953   // them with undef vectors.  That is probably the right thing for other
13954   // targets, but for NEON it is better to concatenate two double-register
13955   // size vector operands into a single quad-register size vector.  Do that
13956   // transformation here:
13957   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
13958   //   shuffle(concat(v1, v2), undef)
13959   SDValue Op0 = N->getOperand(0);
13960   SDValue Op1 = N->getOperand(1);
13961   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
13962       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
13963       Op0.getNumOperands() != 2 ||
13964       Op1.getNumOperands() != 2)
13965     return SDValue();
13966   SDValue Concat0Op1 = Op0.getOperand(1);
13967   SDValue Concat1Op1 = Op1.getOperand(1);
13968   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
13969     return SDValue();
13970   // Skip the transformation if any of the types are illegal.
13971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13972   EVT VT = N->getValueType(0);
13973   if (!TLI.isTypeLegal(VT) ||
13974       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
13975       !TLI.isTypeLegal(Concat1Op1.getValueType()))
13976     return SDValue();
13977 
13978   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13979                                   Op0.getOperand(0), Op1.getOperand(0));
13980   // Translate the shuffle mask.
13981   SmallVector<int, 16> NewMask;
13982   unsigned NumElts = VT.getVectorNumElements();
13983   unsigned HalfElts = NumElts/2;
13984   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13985   for (unsigned n = 0; n < NumElts; ++n) {
13986     int MaskElt = SVN->getMaskElt(n);
13987     int NewElt = -1;
13988     if (MaskElt < (int)HalfElts)
13989       NewElt = MaskElt;
13990     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
13991       NewElt = HalfElts + MaskElt - NumElts;
13992     NewMask.push_back(NewElt);
13993   }
13994   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
13995                               DAG.getUNDEF(VT), NewMask);
13996 }
13997 
13998 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
13999 /// NEON load/store intrinsics, and generic vector load/stores, to merge
14000 /// base address updates.
14001 /// For generic load/stores, the memory type is assumed to be a vector.
14002 /// The caller is assumed to have checked legality.
14003 static SDValue CombineBaseUpdate(SDNode *N,
14004                                  TargetLowering::DAGCombinerInfo &DCI) {
14005   SelectionDAG &DAG = DCI.DAG;
14006   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
14007                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
14008   const bool isStore = N->getOpcode() == ISD::STORE;
14009   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
14010   SDValue Addr = N->getOperand(AddrOpIdx);
14011   MemSDNode *MemN = cast<MemSDNode>(N);
14012   SDLoc dl(N);
14013 
14014   // Search for a use of the address operand that is an increment.
14015   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14016          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
14017     SDNode *User = *UI;
14018     if (User->getOpcode() != ISD::ADD ||
14019         UI.getUse().getResNo() != Addr.getResNo())
14020       continue;
14021 
14022     // Check that the add is independent of the load/store.  Otherwise, folding
14023     // it would create a cycle. We can avoid searching through Addr as it's a
14024     // predecessor to both.
14025     SmallPtrSet<const SDNode *, 32> Visited;
14026     SmallVector<const SDNode *, 16> Worklist;
14027     Visited.insert(Addr.getNode());
14028     Worklist.push_back(N);
14029     Worklist.push_back(User);
14030     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14031         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14032       continue;
14033 
14034     // Find the new opcode for the updating load/store.
14035     bool isLoadOp = true;
14036     bool isLaneOp = false;
14037     unsigned NewOpc = 0;
14038     unsigned NumVecs = 0;
14039     if (isIntrinsic) {
14040       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14041       switch (IntNo) {
14042       default: llvm_unreachable("unexpected intrinsic for Neon base update");
14043       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
14044         NumVecs = 1; break;
14045       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
14046         NumVecs = 2; break;
14047       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
14048         NumVecs = 3; break;
14049       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
14050         NumVecs = 4; break;
14051       case Intrinsic::arm_neon_vld1x2:
14052       case Intrinsic::arm_neon_vld1x3:
14053       case Intrinsic::arm_neon_vld1x4:
14054       case Intrinsic::arm_neon_vld2dup:
14055       case Intrinsic::arm_neon_vld3dup:
14056       case Intrinsic::arm_neon_vld4dup:
14057         // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip
14058         // combining base updates for such intrinsics.
14059         continue;
14060       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
14061         NumVecs = 2; isLaneOp = true; break;
14062       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
14063         NumVecs = 3; isLaneOp = true; break;
14064       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
14065         NumVecs = 4; isLaneOp = true; break;
14066       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
14067         NumVecs = 1; isLoadOp = false; break;
14068       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
14069         NumVecs = 2; isLoadOp = false; break;
14070       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
14071         NumVecs = 3; isLoadOp = false; break;
14072       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
14073         NumVecs = 4; isLoadOp = false; break;
14074       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
14075         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
14076       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
14077         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
14078       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
14079         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
14080       }
14081     } else {
14082       isLaneOp = true;
14083       switch (N->getOpcode()) {
14084       default: llvm_unreachable("unexpected opcode for Neon base update");
14085       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
14086       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
14087       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
14088       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
14089       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
14090         NumVecs = 1; isLaneOp = false; break;
14091       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
14092         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
14093       }
14094     }
14095 
14096     // Find the size of memory referenced by the load/store.
14097     EVT VecTy;
14098     if (isLoadOp) {
14099       VecTy = N->getValueType(0);
14100     } else if (isIntrinsic) {
14101       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
14102     } else {
14103       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
14104       VecTy = N->getOperand(1).getValueType();
14105     }
14106 
14107     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14108     if (isLaneOp)
14109       NumBytes /= VecTy.getVectorNumElements();
14110 
14111     // If the increment is a constant, it must match the memory ref size.
14112     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14113     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14114     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
14115       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
14116       // separate instructions that make it harder to use a non-constant update.
14117       continue;
14118     }
14119 
14120     // OK, we found an ADD we can fold into the base update.
14121     // Now, create a _UPD node, taking care of not breaking alignment.
14122 
14123     EVT AlignedVecTy = VecTy;
14124     unsigned Alignment = MemN->getAlignment();
14125 
14126     // If this is a less-than-standard-aligned load/store, change the type to
14127     // match the standard alignment.
14128     // The alignment is overlooked when selecting _UPD variants; and it's
14129     // easier to introduce bitcasts here than fix that.
14130     // There are 3 ways to get to this base-update combine:
14131     // - intrinsics: they are assumed to be properly aligned (to the standard
14132     //   alignment of the memory type), so we don't need to do anything.
14133     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
14134     //   intrinsics, so, likewise, there's nothing to do.
14135     // - generic load/store instructions: the alignment is specified as an
14136     //   explicit operand, rather than implicitly as the standard alignment
14137     //   of the memory type (like the intrisics).  We need to change the
14138     //   memory type to match the explicit alignment.  That way, we don't
14139     //   generate non-standard-aligned ARMISD::VLDx nodes.
14140     if (isa<LSBaseSDNode>(N)) {
14141       if (Alignment == 0)
14142         Alignment = 1;
14143       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
14144         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
14145         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
14146         assert(!isLaneOp && "Unexpected generic load/store lane.");
14147         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
14148         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
14149       }
14150       // Don't set an explicit alignment on regular load/stores that we want
14151       // to transform to VLD/VST 1_UPD nodes.
14152       // This matches the behavior of regular load/stores, which only get an
14153       // explicit alignment if the MMO alignment is larger than the standard
14154       // alignment of the memory type.
14155       // Intrinsics, however, always get an explicit alignment, set to the
14156       // alignment of the MMO.
14157       Alignment = 1;
14158     }
14159 
14160     // Create the new updating load/store node.
14161     // First, create an SDVTList for the new updating node's results.
14162     EVT Tys[6];
14163     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14164     unsigned n;
14165     for (n = 0; n < NumResultVecs; ++n)
14166       Tys[n] = AlignedVecTy;
14167     Tys[n++] = MVT::i32;
14168     Tys[n] = MVT::Other;
14169     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
14170 
14171     // Then, gather the new node's operands.
14172     SmallVector<SDValue, 8> Ops;
14173     Ops.push_back(N->getOperand(0)); // incoming chain
14174     Ops.push_back(N->getOperand(AddrOpIdx));
14175     Ops.push_back(Inc);
14176 
14177     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
14178       // Try to match the intrinsic's signature
14179       Ops.push_back(StN->getValue());
14180     } else {
14181       // Loads (and of course intrinsics) match the intrinsics' signature,
14182       // so just add all but the alignment operand.
14183       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
14184         Ops.push_back(N->getOperand(i));
14185     }
14186 
14187     // For all node types, the alignment operand is always the last one.
14188     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
14189 
14190     // If this is a non-standard-aligned STORE, the penultimate operand is the
14191     // stored value.  Bitcast it to the aligned type.
14192     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
14193       SDValue &StVal = Ops[Ops.size()-2];
14194       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
14195     }
14196 
14197     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
14198     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
14199                                            MemN->getMemOperand());
14200 
14201     // Update the uses.
14202     SmallVector<SDValue, 5> NewResults;
14203     for (unsigned i = 0; i < NumResultVecs; ++i)
14204       NewResults.push_back(SDValue(UpdN.getNode(), i));
14205 
14206     // If this is an non-standard-aligned LOAD, the first result is the loaded
14207     // value.  Bitcast it to the expected result type.
14208     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
14209       SDValue &LdVal = NewResults[0];
14210       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
14211     }
14212 
14213     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
14214     DCI.CombineTo(N, NewResults);
14215     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14216 
14217     break;
14218   }
14219   return SDValue();
14220 }
14221 
14222 static SDValue PerformVLDCombine(SDNode *N,
14223                                  TargetLowering::DAGCombinerInfo &DCI) {
14224   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14225     return SDValue();
14226 
14227   return CombineBaseUpdate(N, DCI);
14228 }
14229 
14230 static SDValue PerformMVEVLDCombine(SDNode *N,
14231                                     TargetLowering::DAGCombinerInfo &DCI) {
14232   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14233     return SDValue();
14234 
14235   SelectionDAG &DAG = DCI.DAG;
14236   SDValue Addr = N->getOperand(2);
14237   MemSDNode *MemN = cast<MemSDNode>(N);
14238   SDLoc dl(N);
14239 
14240   // For the stores, where there are multiple intrinsics we only actually want
14241   // to post-inc the last of the them.
14242   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14243   if (IntNo == Intrinsic::arm_mve_vst2q &&
14244       cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
14245     return SDValue();
14246   if (IntNo == Intrinsic::arm_mve_vst4q &&
14247       cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
14248     return SDValue();
14249 
14250   // Search for a use of the address operand that is an increment.
14251   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14252                             UE = Addr.getNode()->use_end();
14253        UI != UE; ++UI) {
14254     SDNode *User = *UI;
14255     if (User->getOpcode() != ISD::ADD ||
14256         UI.getUse().getResNo() != Addr.getResNo())
14257       continue;
14258 
14259     // Check that the add is independent of the load/store.  Otherwise, folding
14260     // it would create a cycle. We can avoid searching through Addr as it's a
14261     // predecessor to both.
14262     SmallPtrSet<const SDNode *, 32> Visited;
14263     SmallVector<const SDNode *, 16> Worklist;
14264     Visited.insert(Addr.getNode());
14265     Worklist.push_back(N);
14266     Worklist.push_back(User);
14267     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14268         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14269       continue;
14270 
14271     // Find the new opcode for the updating load/store.
14272     bool isLoadOp = true;
14273     unsigned NewOpc = 0;
14274     unsigned NumVecs = 0;
14275     switch (IntNo) {
14276     default:
14277       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
14278     case Intrinsic::arm_mve_vld2q:
14279       NewOpc = ARMISD::VLD2_UPD;
14280       NumVecs = 2;
14281       break;
14282     case Intrinsic::arm_mve_vld4q:
14283       NewOpc = ARMISD::VLD4_UPD;
14284       NumVecs = 4;
14285       break;
14286     case Intrinsic::arm_mve_vst2q:
14287       NewOpc = ARMISD::VST2_UPD;
14288       NumVecs = 2;
14289       isLoadOp = false;
14290       break;
14291     case Intrinsic::arm_mve_vst4q:
14292       NewOpc = ARMISD::VST4_UPD;
14293       NumVecs = 4;
14294       isLoadOp = false;
14295       break;
14296     }
14297 
14298     // Find the size of memory referenced by the load/store.
14299     EVT VecTy;
14300     if (isLoadOp) {
14301       VecTy = N->getValueType(0);
14302     } else {
14303       VecTy = N->getOperand(3).getValueType();
14304     }
14305 
14306     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14307 
14308     // If the increment is a constant, it must match the memory ref size.
14309     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14310     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14311     if (!CInc || CInc->getZExtValue() != NumBytes)
14312       continue;
14313 
14314     // Create the new updating load/store node.
14315     // First, create an SDVTList for the new updating node's results.
14316     EVT Tys[6];
14317     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14318     unsigned n;
14319     for (n = 0; n < NumResultVecs; ++n)
14320       Tys[n] = VecTy;
14321     Tys[n++] = MVT::i32;
14322     Tys[n] = MVT::Other;
14323     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
14324 
14325     // Then, gather the new node's operands.
14326     SmallVector<SDValue, 8> Ops;
14327     Ops.push_back(N->getOperand(0)); // incoming chain
14328     Ops.push_back(N->getOperand(2)); // ptr
14329     Ops.push_back(Inc);
14330 
14331     for (unsigned i = 3; i < N->getNumOperands(); ++i)
14332       Ops.push_back(N->getOperand(i));
14333 
14334     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
14335                                            MemN->getMemOperand());
14336 
14337     // Update the uses.
14338     SmallVector<SDValue, 5> NewResults;
14339     for (unsigned i = 0; i < NumResultVecs; ++i)
14340       NewResults.push_back(SDValue(UpdN.getNode(), i));
14341 
14342     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
14343     DCI.CombineTo(N, NewResults);
14344     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14345 
14346     break;
14347   }
14348 
14349   return SDValue();
14350 }
14351 
14352 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
14353 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
14354 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
14355 /// return true.
14356 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14357   SelectionDAG &DAG = DCI.DAG;
14358   EVT VT = N->getValueType(0);
14359   // vldN-dup instructions only support 64-bit vectors for N > 1.
14360   if (!VT.is64BitVector())
14361     return false;
14362 
14363   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
14364   SDNode *VLD = N->getOperand(0).getNode();
14365   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
14366     return false;
14367   unsigned NumVecs = 0;
14368   unsigned NewOpc = 0;
14369   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
14370   if (IntNo == Intrinsic::arm_neon_vld2lane) {
14371     NumVecs = 2;
14372     NewOpc = ARMISD::VLD2DUP;
14373   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
14374     NumVecs = 3;
14375     NewOpc = ARMISD::VLD3DUP;
14376   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
14377     NumVecs = 4;
14378     NewOpc = ARMISD::VLD4DUP;
14379   } else {
14380     return false;
14381   }
14382 
14383   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
14384   // numbers match the load.
14385   unsigned VLDLaneNo =
14386     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
14387   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14388        UI != UE; ++UI) {
14389     // Ignore uses of the chain result.
14390     if (UI.getUse().getResNo() == NumVecs)
14391       continue;
14392     SDNode *User = *UI;
14393     if (User->getOpcode() != ARMISD::VDUPLANE ||
14394         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
14395       return false;
14396   }
14397 
14398   // Create the vldN-dup node.
14399   EVT Tys[5];
14400   unsigned n;
14401   for (n = 0; n < NumVecs; ++n)
14402     Tys[n] = VT;
14403   Tys[n] = MVT::Other;
14404   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
14405   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
14406   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
14407   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
14408                                            Ops, VLDMemInt->getMemoryVT(),
14409                                            VLDMemInt->getMemOperand());
14410 
14411   // Update the uses.
14412   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14413        UI != UE; ++UI) {
14414     unsigned ResNo = UI.getUse().getResNo();
14415     // Ignore uses of the chain result.
14416     if (ResNo == NumVecs)
14417       continue;
14418     SDNode *User = *UI;
14419     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
14420   }
14421 
14422   // Now the vldN-lane intrinsic is dead except for its chain result.
14423   // Update uses of the chain.
14424   std::vector<SDValue> VLDDupResults;
14425   for (unsigned n = 0; n < NumVecs; ++n)
14426     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
14427   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
14428   DCI.CombineTo(VLD, VLDDupResults);
14429 
14430   return true;
14431 }
14432 
14433 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
14434 /// ARMISD::VDUPLANE.
14435 static SDValue PerformVDUPLANECombine(SDNode *N,
14436                                       TargetLowering::DAGCombinerInfo &DCI,
14437                                       const ARMSubtarget *Subtarget) {
14438   SDValue Op = N->getOperand(0);
14439   EVT VT = N->getValueType(0);
14440 
14441   // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
14442   if (Subtarget->hasMVEIntegerOps()) {
14443     EVT ExtractVT = VT.getVectorElementType();
14444     // We need to ensure we are creating a legal type.
14445     if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
14446       ExtractVT = MVT::i32;
14447     SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
14448                               N->getOperand(0), N->getOperand(1));
14449     return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
14450   }
14451 
14452   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
14453   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
14454   if (CombineVLDDUP(N, DCI))
14455     return SDValue(N, 0);
14456 
14457   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
14458   // redundant.  Ignore bit_converts for now; element sizes are checked below.
14459   while (Op.getOpcode() == ISD::BITCAST)
14460     Op = Op.getOperand(0);
14461   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
14462     return SDValue();
14463 
14464   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
14465   unsigned EltSize = Op.getScalarValueSizeInBits();
14466   // The canonical VMOV for a zero vector uses a 32-bit element size.
14467   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14468   unsigned EltBits;
14469   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
14470     EltSize = 8;
14471   if (EltSize > VT.getScalarSizeInBits())
14472     return SDValue();
14473 
14474   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
14475 }
14476 
14477 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
14478 static SDValue PerformVDUPCombine(SDNode *N,
14479                                   TargetLowering::DAGCombinerInfo &DCI,
14480                                   const ARMSubtarget *Subtarget) {
14481   SelectionDAG &DAG = DCI.DAG;
14482   SDValue Op = N->getOperand(0);
14483   SDLoc dl(N);
14484 
14485   if (Subtarget->hasMVEIntegerOps()) {
14486     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
14487     // need to come from a GPR.
14488     if (Op.getValueType() == MVT::f32)
14489       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14490                              DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
14491     else if (Op.getValueType() == MVT::f16)
14492       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14493                              DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
14494   }
14495 
14496   if (!Subtarget->hasNEON())
14497     return SDValue();
14498 
14499   // Match VDUP(LOAD) -> VLD1DUP.
14500   // We match this pattern here rather than waiting for isel because the
14501   // transform is only legal for unindexed loads.
14502   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
14503   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
14504       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
14505     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
14506                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
14507     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
14508     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
14509                                              Ops, LD->getMemoryVT(),
14510                                              LD->getMemOperand());
14511     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
14512     return VLDDup;
14513   }
14514 
14515   return SDValue();
14516 }
14517 
14518 static SDValue PerformLOADCombine(SDNode *N,
14519                                   TargetLowering::DAGCombinerInfo &DCI) {
14520   EVT VT = N->getValueType(0);
14521 
14522   // If this is a legal vector load, try to combine it into a VLD1_UPD.
14523   if (ISD::isNormalLoad(N) && VT.isVector() &&
14524       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14525     return CombineBaseUpdate(N, DCI);
14526 
14527   return SDValue();
14528 }
14529 
14530 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
14531 // pack all of the elements in one place.  Next, store to memory in fewer
14532 // chunks.
14533 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
14534                                              SelectionDAG &DAG) {
14535   SDValue StVal = St->getValue();
14536   EVT VT = StVal.getValueType();
14537   if (!St->isTruncatingStore() || !VT.isVector())
14538     return SDValue();
14539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14540   EVT StVT = St->getMemoryVT();
14541   unsigned NumElems = VT.getVectorNumElements();
14542   assert(StVT != VT && "Cannot truncate to the same type");
14543   unsigned FromEltSz = VT.getScalarSizeInBits();
14544   unsigned ToEltSz = StVT.getScalarSizeInBits();
14545 
14546   // From, To sizes and ElemCount must be pow of two
14547   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
14548     return SDValue();
14549 
14550   // We are going to use the original vector elt for storing.
14551   // Accumulated smaller vector elements must be a multiple of the store size.
14552   if (0 != (NumElems * FromEltSz) % ToEltSz)
14553     return SDValue();
14554 
14555   unsigned SizeRatio = FromEltSz / ToEltSz;
14556   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
14557 
14558   // Create a type on which we perform the shuffle.
14559   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
14560                                    NumElems * SizeRatio);
14561   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14562 
14563   SDLoc DL(St);
14564   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
14565   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14566   for (unsigned i = 0; i < NumElems; ++i)
14567     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
14568                                                       : i * SizeRatio;
14569 
14570   // Can't shuffle using an illegal type.
14571   if (!TLI.isTypeLegal(WideVecVT))
14572     return SDValue();
14573 
14574   SDValue Shuff = DAG.getVectorShuffle(
14575       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
14576   // At this point all of the data is stored at the bottom of the
14577   // register. We now need to save it to mem.
14578 
14579   // Find the largest store unit
14580   MVT StoreType = MVT::i8;
14581   for (MVT Tp : MVT::integer_valuetypes()) {
14582     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
14583       StoreType = Tp;
14584   }
14585   // Didn't find a legal store type.
14586   if (!TLI.isTypeLegal(StoreType))
14587     return SDValue();
14588 
14589   // Bitcast the original vector into a vector of store-size units
14590   EVT StoreVecVT =
14591       EVT::getVectorVT(*DAG.getContext(), StoreType,
14592                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
14593   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14594   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
14595   SmallVector<SDValue, 8> Chains;
14596   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
14597                                       TLI.getPointerTy(DAG.getDataLayout()));
14598   SDValue BasePtr = St->getBasePtr();
14599 
14600   // Perform one or more big stores into memory.
14601   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
14602   for (unsigned I = 0; I < E; I++) {
14603     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
14604                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
14605     SDValue Ch =
14606         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
14607                      St->getAlignment(), St->getMemOperand()->getFlags());
14608     BasePtr =
14609         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
14610     Chains.push_back(Ch);
14611   }
14612   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14613 }
14614 
14615 // Try taking a single vector store from an truncate (which would otherwise turn
14616 // into an expensive buildvector) and splitting it into a series of narrowing
14617 // stores.
14618 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
14619                                                  SelectionDAG &DAG) {
14620   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
14621     return SDValue();
14622   SDValue Trunc = St->getValue();
14623   if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND)
14624     return SDValue();
14625   EVT FromVT = Trunc->getOperand(0).getValueType();
14626   EVT ToVT = Trunc.getValueType();
14627   if (!ToVT.isVector())
14628     return SDValue();
14629   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14630   EVT ToEltVT = ToVT.getVectorElementType();
14631   EVT FromEltVT = FromVT.getVectorElementType();
14632 
14633   unsigned NumElements = 0;
14634   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
14635     NumElements = 4;
14636   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
14637     NumElements = 8;
14638   if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16)
14639     NumElements = 4;
14640   if (NumElements == 0 ||
14641       (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) ||
14642       FromVT.getVectorNumElements() % NumElements != 0)
14643     return SDValue();
14644 
14645   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
14646   // use the VMOVN over splitting the store. We are looking for patterns of:
14647   // !rev: 0 N 1 N+1 2 N+2 ...
14648   //  rev: N 0 N+1 1 N+2 2 ...
14649   auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) {
14650     unsigned NumElts = ToVT.getVectorNumElements();
14651     if (NumElts != M.size())
14652       return false;
14653 
14654     unsigned Off0 = rev ? NumElts : 0;
14655     unsigned Off1 = rev ? 0 : NumElts;
14656 
14657     for (unsigned i = 0; i < NumElts; i += 2) {
14658       if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
14659         return false;
14660       if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
14661         return false;
14662     }
14663 
14664     return true;
14665   };
14666 
14667   // It may be preferable to keep the store unsplit as the trunc may end up
14668   // being removed. Check that here.
14669   if (Trunc.getOperand(0).getOpcode() == ISD::SMIN) {
14670     if (SDValue U = PerformVQDMULHCombine(Trunc.getOperand(0).getNode(), DAG)) {
14671       DAG.ReplaceAllUsesWith(Trunc.getOperand(0), U);
14672       return SDValue();
14673     }
14674   }
14675   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0)))
14676     if (isVMOVNOriginalMask(Shuffle->getMask(), false) ||
14677         isVMOVNOriginalMask(Shuffle->getMask(), true))
14678       return SDValue();
14679 
14680   LLVMContext &C = *DAG.getContext();
14681   SDLoc DL(St);
14682   // Details about the old store
14683   SDValue Ch = St->getChain();
14684   SDValue BasePtr = St->getBasePtr();
14685   Align Alignment = St->getOriginalAlign();
14686   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
14687   AAMDNodes AAInfo = St->getAAInfo();
14688 
14689   // We split the store into slices of NumElements. fp16 trunc stores are vcvt
14690   // and then stored as truncating integer stores.
14691   EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
14692   EVT NewToVT = EVT::getVectorVT(
14693       C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
14694 
14695   SmallVector<SDValue, 4> Stores;
14696   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
14697     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
14698     SDValue NewPtr =
14699         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
14700 
14701     SDValue Extract =
14702         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
14703                     DAG.getConstant(i * NumElements, DL, MVT::i32));
14704 
14705     if (ToEltVT == MVT::f16) {
14706       SDValue FPTrunc =
14707           DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
14708                       Extract, DAG.getConstant(0, DL, MVT::i32));
14709       Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
14710     }
14711 
14712     SDValue Store = DAG.getTruncStore(
14713         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
14714         NewToVT, Alignment.value(), MMOFlags, AAInfo);
14715     Stores.push_back(Store);
14716   }
14717   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14718 }
14719 
14720 /// PerformSTORECombine - Target-specific dag combine xforms for
14721 /// ISD::STORE.
14722 static SDValue PerformSTORECombine(SDNode *N,
14723                                    TargetLowering::DAGCombinerInfo &DCI,
14724                                    const ARMSubtarget *Subtarget) {
14725   StoreSDNode *St = cast<StoreSDNode>(N);
14726   if (St->isVolatile())
14727     return SDValue();
14728   SDValue StVal = St->getValue();
14729   EVT VT = StVal.getValueType();
14730 
14731   if (Subtarget->hasNEON())
14732     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14733       return Store;
14734 
14735   if (Subtarget->hasMVEIntegerOps())
14736     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14737       return NewToken;
14738 
14739   if (!ISD::isNormalStore(St))
14740     return SDValue();
14741 
14742   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14743   // ARM stores of arguments in the same cache line.
14744   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14745       StVal.getNode()->hasOneUse()) {
14746     SelectionDAG  &DAG = DCI.DAG;
14747     bool isBigEndian = DAG.getDataLayout().isBigEndian();
14748     SDLoc DL(St);
14749     SDValue BasePtr = St->getBasePtr();
14750     SDValue NewST1 = DAG.getStore(
14751         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14752         BasePtr, St->getPointerInfo(), St->getOriginalAlign(),
14753         St->getMemOperand()->getFlags());
14754 
14755     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14756                                     DAG.getConstant(4, DL, MVT::i32));
14757     return DAG.getStore(NewST1.getValue(0), DL,
14758                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14759                         OffsetPtr, St->getPointerInfo().getWithOffset(4),
14760                         St->getOriginalAlign(),
14761                         St->getMemOperand()->getFlags());
14762   }
14763 
14764   if (StVal.getValueType() == MVT::i64 &&
14765       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14766 
14767     // Bitcast an i64 store extracted from a vector to f64.
14768     // Otherwise, the i64 value will be legalized to a pair of i32 values.
14769     SelectionDAG &DAG = DCI.DAG;
14770     SDLoc dl(StVal);
14771     SDValue IntVec = StVal.getOperand(0);
14772     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14773                                    IntVec.getValueType().getVectorNumElements());
14774     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14775     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14776                                  Vec, StVal.getOperand(1));
14777     dl = SDLoc(N);
14778     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14779     // Make the DAGCombiner fold the bitcasts.
14780     DCI.AddToWorklist(Vec.getNode());
14781     DCI.AddToWorklist(ExtElt.getNode());
14782     DCI.AddToWorklist(V.getNode());
14783     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14784                         St->getPointerInfo(), St->getAlignment(),
14785                         St->getMemOperand()->getFlags(), St->getAAInfo());
14786   }
14787 
14788   // If this is a legal vector store, try to combine it into a VST1_UPD.
14789   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14790       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14791     return CombineBaseUpdate(N, DCI);
14792 
14793   return SDValue();
14794 }
14795 
14796 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14797 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14798 /// when the VMUL has a constant operand that is a power of 2.
14799 ///
14800 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14801 ///  vmul.f32        d16, d17, d16
14802 ///  vcvt.s32.f32    d16, d16
14803 /// becomes:
14804 ///  vcvt.s32.f32    d16, d16, #3
14805 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14806                                   const ARMSubtarget *Subtarget) {
14807   if (!Subtarget->hasNEON())
14808     return SDValue();
14809 
14810   SDValue Op = N->getOperand(0);
14811   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14812       Op.getOpcode() != ISD::FMUL)
14813     return SDValue();
14814 
14815   SDValue ConstVec = Op->getOperand(1);
14816   if (!isa<BuildVectorSDNode>(ConstVec))
14817     return SDValue();
14818 
14819   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14820   uint32_t FloatBits = FloatTy.getSizeInBits();
14821   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14822   uint32_t IntBits = IntTy.getSizeInBits();
14823   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14824   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14825     // These instructions only exist converting from f32 to i32. We can handle
14826     // smaller integers by generating an extra truncate, but larger ones would
14827     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14828     // these intructions only support v2i32/v4i32 types.
14829     return SDValue();
14830   }
14831 
14832   BitVector UndefElements;
14833   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14834   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14835   if (C == -1 || C == 0 || C > 32)
14836     return SDValue();
14837 
14838   SDLoc dl(N);
14839   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14840   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14841     Intrinsic::arm_neon_vcvtfp2fxu;
14842   SDValue FixConv = DAG.getNode(
14843       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14844       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14845       DAG.getConstant(C, dl, MVT::i32));
14846 
14847   if (IntBits < FloatBits)
14848     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14849 
14850   return FixConv;
14851 }
14852 
14853 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14854 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14855 /// when the VDIV has a constant operand that is a power of 2.
14856 ///
14857 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14858 ///  vcvt.f32.s32    d16, d16
14859 ///  vdiv.f32        d16, d17, d16
14860 /// becomes:
14861 ///  vcvt.f32.s32    d16, d16, #3
14862 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14863                                   const ARMSubtarget *Subtarget) {
14864   if (!Subtarget->hasNEON())
14865     return SDValue();
14866 
14867   SDValue Op = N->getOperand(0);
14868   unsigned OpOpcode = Op.getNode()->getOpcode();
14869   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14870       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14871     return SDValue();
14872 
14873   SDValue ConstVec = N->getOperand(1);
14874   if (!isa<BuildVectorSDNode>(ConstVec))
14875     return SDValue();
14876 
14877   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14878   uint32_t FloatBits = FloatTy.getSizeInBits();
14879   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14880   uint32_t IntBits = IntTy.getSizeInBits();
14881   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14882   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14883     // These instructions only exist converting from i32 to f32. We can handle
14884     // smaller integers by generating an extra extend, but larger ones would
14885     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14886     // these intructions only support v2i32/v4i32 types.
14887     return SDValue();
14888   }
14889 
14890   BitVector UndefElements;
14891   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14892   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14893   if (C == -1 || C == 0 || C > 32)
14894     return SDValue();
14895 
14896   SDLoc dl(N);
14897   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14898   SDValue ConvInput = Op.getOperand(0);
14899   if (IntBits < FloatBits)
14900     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14901                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14902                             ConvInput);
14903 
14904   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14905     Intrinsic::arm_neon_vcvtfxu2fp;
14906   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14907                      Op.getValueType(),
14908                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14909                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
14910 }
14911 
14912 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14913                                            const ARMSubtarget *ST) {
14914   if (!ST->hasMVEIntegerOps())
14915     return SDValue();
14916 
14917   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14918   EVT ResVT = N->getValueType(0);
14919   SDValue N0 = N->getOperand(0);
14920   SDLoc dl(N);
14921 
14922   // We are looking for something that will have illegal types if left alone,
14923   // but that we can convert to a single instruction undef MVE. For example
14924   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14925   // or
14926   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14927 
14928   // Cases:
14929   //   VADDV u/s 8/16/32
14930   //   VMLAV u/s 8/16/32
14931   //   VADDLV u/s 32
14932   //   VMLALV u/s 16/32
14933 
14934   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14935     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14936       return SDValue();
14937     SDValue A = N0->getOperand(0);
14938     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14939       return A;
14940     return SDValue();
14941   };
14942   auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
14943                          ArrayRef<MVT> ExtTypes, SDValue &Mask) {
14944     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
14945         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
14946       return SDValue();
14947     Mask = N0->getOperand(0);
14948     SDValue Ext = N0->getOperand(1);
14949     if (Ext->getOpcode() != ExtendCode)
14950       return SDValue();
14951     SDValue A = Ext->getOperand(0);
14952     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14953       return A;
14954     return SDValue();
14955   };
14956   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14957                      SDValue &A, SDValue &B) {
14958     // For a vmla we are trying to match a larger pattern:
14959     // ExtA = sext/zext A
14960     // ExtB = sext/zext B
14961     // Mul = mul ExtA, ExtB
14962     // vecreduce.add Mul
14963     // There might also be en extra extend between the mul and the addreduce, so
14964     // long as the bitwidth is high enough to make them equivalent (for example
14965     // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
14966     if (ResVT != RetTy)
14967       return false;
14968     SDValue Mul = N0;
14969     if (Mul->getOpcode() == ExtendCode &&
14970         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
14971             ResVT.getScalarSizeInBits())
14972       Mul = Mul->getOperand(0);
14973     if (Mul->getOpcode() != ISD::MUL)
14974       return false;
14975     SDValue ExtA = Mul->getOperand(0);
14976     SDValue ExtB = Mul->getOperand(1);
14977     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
14978       return false;
14979     A = ExtA->getOperand(0);
14980     B = ExtB->getOperand(0);
14981     if (A.getValueType() == B.getValueType() &&
14982         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14983       return true;
14984     return false;
14985   };
14986   auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14987                      SDValue &A, SDValue &B, SDValue &Mask) {
14988     // Same as the pattern above with a select for the zero predicated lanes
14989     // ExtA = sext/zext A
14990     // ExtB = sext/zext B
14991     // Mul = mul ExtA, ExtB
14992     // N0 = select Mask, Mul, 0
14993     // vecreduce.add N0
14994     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
14995         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
14996       return false;
14997     Mask = N0->getOperand(0);
14998     SDValue Mul = N0->getOperand(1);
14999     if (Mul->getOpcode() == ExtendCode &&
15000         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
15001             ResVT.getScalarSizeInBits())
15002       Mul = Mul->getOperand(0);
15003     if (Mul->getOpcode() != ISD::MUL)
15004       return false;
15005     SDValue ExtA = Mul->getOperand(0);
15006     SDValue ExtB = Mul->getOperand(1);
15007     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
15008       return false;
15009     A = ExtA->getOperand(0);
15010     B = ExtB->getOperand(0);
15011     if (A.getValueType() == B.getValueType() &&
15012         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
15013       return true;
15014     return false;
15015   };
15016   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
15017     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
15018     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
15019                        SDValue(Node.getNode(), 1));
15020   };
15021 
15022   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
15023     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
15024   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
15025     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
15026   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
15027     return Create64bitNode(ARMISD::VADDLVs, {A});
15028   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
15029     return Create64bitNode(ARMISD::VADDLVu, {A});
15030   if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
15031     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15032                        DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
15033   if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
15034     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15035                        DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
15036 
15037   SDValue Mask;
15038   if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
15039     return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
15040   if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
15041     return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
15042   if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
15043     return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
15044   if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
15045     return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
15046   if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
15047     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15048                        DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
15049   if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
15050     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15051                        DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
15052 
15053   SDValue A, B;
15054   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
15055     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
15056   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
15057     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
15058   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
15059     return Create64bitNode(ARMISD::VMLALVs, {A, B});
15060   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
15061     return Create64bitNode(ARMISD::VMLALVu, {A, B});
15062   if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
15063     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15064                        DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
15065   if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
15066     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15067                        DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
15068 
15069   if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
15070     return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
15071   if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
15072     return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
15073   if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask))
15074     return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
15075   if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask))
15076     return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
15077   if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
15078     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15079                        DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
15080   if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
15081     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
15082                        DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
15083 
15084   // Some complications. We can get a case where the two inputs of the mul are
15085   // the same, then the output sext will have been helpfully converted to a
15086   // zext. Turn it back.
15087   SDValue Op = N0;
15088   if (Op->getOpcode() == ISD::VSELECT)
15089     Op = Op->getOperand(1);
15090   if (Op->getOpcode() == ISD::ZERO_EXTEND &&
15091       Op->getOperand(0)->getOpcode() == ISD::MUL) {
15092     SDValue Mul = Op->getOperand(0);
15093     if (Mul->getOperand(0) == Mul->getOperand(1) &&
15094         Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
15095       SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
15096       if (Op != N0)
15097         Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
15098                           N0->getOperand(0), Ext, N0->getOperand(2));
15099       return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
15100     }
15101   }
15102 
15103   return SDValue();
15104 }
15105 
15106 static SDValue PerformVMOVNCombine(SDNode *N,
15107                                    TargetLowering::DAGCombinerInfo &DCI) {
15108   SDValue Op0 = N->getOperand(0);
15109   SDValue Op1 = N->getOperand(1);
15110   unsigned IsTop = N->getConstantOperandVal(2);
15111 
15112   // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
15113   // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
15114   if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
15115        Op1->getOpcode() == ARMISD::VQMOVNu) &&
15116       Op1->getConstantOperandVal(2) == 0)
15117     return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
15118                            Op0, Op1->getOperand(1), N->getOperand(2));
15119 
15120   // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
15121   // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
15122   // into the top or bottom lanes.
15123   unsigned NumElts = N->getValueType(0).getVectorNumElements();
15124   APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
15125   APInt Op0DemandedElts =
15126       IsTop ? Op1DemandedElts
15127             : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
15128 
15129   APInt KnownUndef, KnownZero;
15130   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15131   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
15132                                      KnownZero, DCI))
15133     return SDValue(N, 0);
15134   if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
15135                                      KnownZero, DCI))
15136     return SDValue(N, 0);
15137 
15138   return SDValue();
15139 }
15140 
15141 static SDValue PerformVQMOVNCombine(SDNode *N,
15142                                     TargetLowering::DAGCombinerInfo &DCI) {
15143   SDValue Op0 = N->getOperand(0);
15144   unsigned IsTop = N->getConstantOperandVal(2);
15145 
15146   unsigned NumElts = N->getValueType(0).getVectorNumElements();
15147   APInt Op0DemandedElts =
15148       APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
15149                                      : APInt::getHighBitsSet(2, 1));
15150 
15151   APInt KnownUndef, KnownZero;
15152   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
15153   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
15154                                      KnownZero, DCI))
15155     return SDValue(N, 0);
15156   return SDValue();
15157 }
15158 
15159 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
15160   SDLoc DL(N);
15161   SDValue Op0 = N->getOperand(0);
15162   SDValue Op1 = N->getOperand(1);
15163 
15164   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
15165   // uses of the intrinsics.
15166   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
15167     int ShiftAmt = C->getSExtValue();
15168     if (ShiftAmt == 0) {
15169       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
15170       DAG.ReplaceAllUsesWith(N, Merge.getNode());
15171       return SDValue();
15172     }
15173 
15174     if (ShiftAmt >= -32 && ShiftAmt < 0) {
15175       unsigned NewOpcode =
15176           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
15177       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
15178                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
15179       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
15180       return NewShift;
15181     }
15182   }
15183 
15184   return SDValue();
15185 }
15186 
15187 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
15188 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
15189                                                    DAGCombinerInfo &DCI) const {
15190   SelectionDAG &DAG = DCI.DAG;
15191   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15192   switch (IntNo) {
15193   default:
15194     // Don't do anything for most intrinsics.
15195     break;
15196 
15197   // Vector shifts: check for immediate versions and lower them.
15198   // Note: This is done during DAG combining instead of DAG legalizing because
15199   // the build_vectors for 64-bit vector element shift counts are generally
15200   // not legal, and it is hard to see their values after they get legalized to
15201   // loads from a constant pool.
15202   case Intrinsic::arm_neon_vshifts:
15203   case Intrinsic::arm_neon_vshiftu:
15204   case Intrinsic::arm_neon_vrshifts:
15205   case Intrinsic::arm_neon_vrshiftu:
15206   case Intrinsic::arm_neon_vrshiftn:
15207   case Intrinsic::arm_neon_vqshifts:
15208   case Intrinsic::arm_neon_vqshiftu:
15209   case Intrinsic::arm_neon_vqshiftsu:
15210   case Intrinsic::arm_neon_vqshiftns:
15211   case Intrinsic::arm_neon_vqshiftnu:
15212   case Intrinsic::arm_neon_vqshiftnsu:
15213   case Intrinsic::arm_neon_vqrshiftns:
15214   case Intrinsic::arm_neon_vqrshiftnu:
15215   case Intrinsic::arm_neon_vqrshiftnsu: {
15216     EVT VT = N->getOperand(1).getValueType();
15217     int64_t Cnt;
15218     unsigned VShiftOpc = 0;
15219 
15220     switch (IntNo) {
15221     case Intrinsic::arm_neon_vshifts:
15222     case Intrinsic::arm_neon_vshiftu:
15223       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
15224         VShiftOpc = ARMISD::VSHLIMM;
15225         break;
15226       }
15227       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
15228         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
15229                                                           : ARMISD::VSHRuIMM);
15230         break;
15231       }
15232       return SDValue();
15233 
15234     case Intrinsic::arm_neon_vrshifts:
15235     case Intrinsic::arm_neon_vrshiftu:
15236       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
15237         break;
15238       return SDValue();
15239 
15240     case Intrinsic::arm_neon_vqshifts:
15241     case Intrinsic::arm_neon_vqshiftu:
15242       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15243         break;
15244       return SDValue();
15245 
15246     case Intrinsic::arm_neon_vqshiftsu:
15247       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15248         break;
15249       llvm_unreachable("invalid shift count for vqshlu intrinsic");
15250 
15251     case Intrinsic::arm_neon_vrshiftn:
15252     case Intrinsic::arm_neon_vqshiftns:
15253     case Intrinsic::arm_neon_vqshiftnu:
15254     case Intrinsic::arm_neon_vqshiftnsu:
15255     case Intrinsic::arm_neon_vqrshiftns:
15256     case Intrinsic::arm_neon_vqrshiftnu:
15257     case Intrinsic::arm_neon_vqrshiftnsu:
15258       // Narrowing shifts require an immediate right shift.
15259       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
15260         break;
15261       llvm_unreachable("invalid shift count for narrowing vector shift "
15262                        "intrinsic");
15263 
15264     default:
15265       llvm_unreachable("unhandled vector shift");
15266     }
15267 
15268     switch (IntNo) {
15269     case Intrinsic::arm_neon_vshifts:
15270     case Intrinsic::arm_neon_vshiftu:
15271       // Opcode already set above.
15272       break;
15273     case Intrinsic::arm_neon_vrshifts:
15274       VShiftOpc = ARMISD::VRSHRsIMM;
15275       break;
15276     case Intrinsic::arm_neon_vrshiftu:
15277       VShiftOpc = ARMISD::VRSHRuIMM;
15278       break;
15279     case Intrinsic::arm_neon_vrshiftn:
15280       VShiftOpc = ARMISD::VRSHRNIMM;
15281       break;
15282     case Intrinsic::arm_neon_vqshifts:
15283       VShiftOpc = ARMISD::VQSHLsIMM;
15284       break;
15285     case Intrinsic::arm_neon_vqshiftu:
15286       VShiftOpc = ARMISD::VQSHLuIMM;
15287       break;
15288     case Intrinsic::arm_neon_vqshiftsu:
15289       VShiftOpc = ARMISD::VQSHLsuIMM;
15290       break;
15291     case Intrinsic::arm_neon_vqshiftns:
15292       VShiftOpc = ARMISD::VQSHRNsIMM;
15293       break;
15294     case Intrinsic::arm_neon_vqshiftnu:
15295       VShiftOpc = ARMISD::VQSHRNuIMM;
15296       break;
15297     case Intrinsic::arm_neon_vqshiftnsu:
15298       VShiftOpc = ARMISD::VQSHRNsuIMM;
15299       break;
15300     case Intrinsic::arm_neon_vqrshiftns:
15301       VShiftOpc = ARMISD::VQRSHRNsIMM;
15302       break;
15303     case Intrinsic::arm_neon_vqrshiftnu:
15304       VShiftOpc = ARMISD::VQRSHRNuIMM;
15305       break;
15306     case Intrinsic::arm_neon_vqrshiftnsu:
15307       VShiftOpc = ARMISD::VQRSHRNsuIMM;
15308       break;
15309     }
15310 
15311     SDLoc dl(N);
15312     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15313                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
15314   }
15315 
15316   case Intrinsic::arm_neon_vshiftins: {
15317     EVT VT = N->getOperand(1).getValueType();
15318     int64_t Cnt;
15319     unsigned VShiftOpc = 0;
15320 
15321     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
15322       VShiftOpc = ARMISD::VSLIIMM;
15323     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
15324       VShiftOpc = ARMISD::VSRIIMM;
15325     else {
15326       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
15327     }
15328 
15329     SDLoc dl(N);
15330     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15331                        N->getOperand(1), N->getOperand(2),
15332                        DAG.getConstant(Cnt, dl, MVT::i32));
15333   }
15334 
15335   case Intrinsic::arm_neon_vqrshifts:
15336   case Intrinsic::arm_neon_vqrshiftu:
15337     // No immediate versions of these to check for.
15338     break;
15339 
15340   case Intrinsic::arm_mve_vqdmlah:
15341   case Intrinsic::arm_mve_vqdmlash:
15342   case Intrinsic::arm_mve_vqrdmlah:
15343   case Intrinsic::arm_mve_vqrdmlash:
15344   case Intrinsic::arm_mve_vmla_n_predicated:
15345   case Intrinsic::arm_mve_vmlas_n_predicated:
15346   case Intrinsic::arm_mve_vqdmlah_predicated:
15347   case Intrinsic::arm_mve_vqdmlash_predicated:
15348   case Intrinsic::arm_mve_vqrdmlah_predicated:
15349   case Intrinsic::arm_mve_vqrdmlash_predicated: {
15350     // These intrinsics all take an i32 scalar operand which is narrowed to the
15351     // size of a single lane of the vector type they return. So we don't need
15352     // any bits of that operand above that point, which allows us to eliminate
15353     // uxth/sxth.
15354     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
15355     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15356     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
15357       return SDValue();
15358     break;
15359   }
15360 
15361   case Intrinsic::arm_mve_minv:
15362   case Intrinsic::arm_mve_maxv:
15363   case Intrinsic::arm_mve_minav:
15364   case Intrinsic::arm_mve_maxav:
15365   case Intrinsic::arm_mve_minv_predicated:
15366   case Intrinsic::arm_mve_maxv_predicated:
15367   case Intrinsic::arm_mve_minav_predicated:
15368   case Intrinsic::arm_mve_maxav_predicated: {
15369     // These intrinsics all take an i32 scalar operand which is narrowed to the
15370     // size of a single lane of the vector type they take as the other input.
15371     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
15372     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15373     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15374       return SDValue();
15375     break;
15376   }
15377 
15378   case Intrinsic::arm_mve_addv: {
15379     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
15380     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
15381     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15382     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
15383     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
15384   }
15385 
15386   case Intrinsic::arm_mve_addlv:
15387   case Intrinsic::arm_mve_addlv_predicated: {
15388     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
15389     // which recombines the two outputs into an i64
15390     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15391     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
15392                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
15393                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
15394 
15395     SmallVector<SDValue, 4> Ops;
15396     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
15397       if (i != 2)                      // skip the unsigned flag
15398         Ops.push_back(N->getOperand(i));
15399 
15400     SDLoc dl(N);
15401     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
15402     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
15403                        val.getValue(1));
15404   }
15405   }
15406 
15407   return SDValue();
15408 }
15409 
15410 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
15411 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
15412 /// combining instead of DAG legalizing because the build_vectors for 64-bit
15413 /// vector element shift counts are generally not legal, and it is hard to see
15414 /// their values after they get legalized to loads from a constant pool.
15415 static SDValue PerformShiftCombine(SDNode *N,
15416                                    TargetLowering::DAGCombinerInfo &DCI,
15417                                    const ARMSubtarget *ST) {
15418   SelectionDAG &DAG = DCI.DAG;
15419   EVT VT = N->getValueType(0);
15420   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
15421     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
15422     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
15423     SDValue N1 = N->getOperand(1);
15424     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
15425       SDValue N0 = N->getOperand(0);
15426       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
15427           DAG.MaskedValueIsZero(N0.getOperand(0),
15428                                 APInt::getHighBitsSet(32, 16)))
15429         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
15430     }
15431   }
15432 
15433   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
15434       N->getOperand(0)->getOpcode() == ISD::AND &&
15435       N->getOperand(0)->hasOneUse()) {
15436     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15437       return SDValue();
15438     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
15439     // usually show up because instcombine prefers to canonicalize it to
15440     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
15441     // out of GEP lowering in some cases.
15442     SDValue N0 = N->getOperand(0);
15443     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
15444     if (!ShiftAmtNode)
15445       return SDValue();
15446     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
15447     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15448     if (!AndMaskNode)
15449       return SDValue();
15450     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
15451     // Don't transform uxtb/uxth.
15452     if (AndMask == 255 || AndMask == 65535)
15453       return SDValue();
15454     if (isMask_32(AndMask)) {
15455       uint32_t MaskedBits = countLeadingZeros(AndMask);
15456       if (MaskedBits > ShiftAmt) {
15457         SDLoc DL(N);
15458         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
15459                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
15460         return DAG.getNode(
15461             ISD::SRL, DL, MVT::i32, SHL,
15462             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
15463       }
15464     }
15465   }
15466 
15467   // Nothing to be done for scalar shifts.
15468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15469   if (!VT.isVector() || !TLI.isTypeLegal(VT))
15470     return SDValue();
15471   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
15472     return SDValue();
15473 
15474   int64_t Cnt;
15475 
15476   switch (N->getOpcode()) {
15477   default: llvm_unreachable("unexpected shift opcode");
15478 
15479   case ISD::SHL:
15480     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
15481       SDLoc dl(N);
15482       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
15483                          DAG.getConstant(Cnt, dl, MVT::i32));
15484     }
15485     break;
15486 
15487   case ISD::SRA:
15488   case ISD::SRL:
15489     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
15490       unsigned VShiftOpc =
15491           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
15492       SDLoc dl(N);
15493       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
15494                          DAG.getConstant(Cnt, dl, MVT::i32));
15495     }
15496   }
15497   return SDValue();
15498 }
15499 
15500 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be
15501 // split into multiple extending loads, which are simpler to deal with than an
15502 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL
15503 // to convert the type to an f32.
15504 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
15505   SDValue N0 = N->getOperand(0);
15506   if (N0.getOpcode() != ISD::LOAD)
15507     return SDValue();
15508   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
15509   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
15510       LD->getExtensionType() != ISD::NON_EXTLOAD)
15511     return SDValue();
15512   EVT FromVT = LD->getValueType(0);
15513   EVT ToVT = N->getValueType(0);
15514   if (!ToVT.isVector())
15515     return SDValue();
15516   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
15517   EVT ToEltVT = ToVT.getVectorElementType();
15518   EVT FromEltVT = FromVT.getVectorElementType();
15519 
15520   unsigned NumElements = 0;
15521   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
15522     NumElements = 4;
15523   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
15524     NumElements = 8;
15525   if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
15526     NumElements = 4;
15527   if (NumElements == 0 ||
15528       (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
15529       FromVT.getVectorNumElements() % NumElements != 0 ||
15530       !isPowerOf2_32(NumElements))
15531     return SDValue();
15532 
15533   LLVMContext &C = *DAG.getContext();
15534   SDLoc DL(LD);
15535   // Details about the old load
15536   SDValue Ch = LD->getChain();
15537   SDValue BasePtr = LD->getBasePtr();
15538   Align Alignment = LD->getOriginalAlign();
15539   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
15540   AAMDNodes AAInfo = LD->getAAInfo();
15541 
15542   ISD::LoadExtType NewExtType =
15543       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15544   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
15545   EVT NewFromVT = EVT::getVectorVT(
15546       C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
15547   EVT NewToVT = EVT::getVectorVT(
15548       C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
15549 
15550   SmallVector<SDValue, 4> Loads;
15551   SmallVector<SDValue, 4> Chains;
15552   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
15553     unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
15554     SDValue NewPtr =
15555         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
15556 
15557     SDValue NewLoad =
15558         DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
15559                     LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
15560                     Alignment, MMOFlags, AAInfo);
15561     Loads.push_back(NewLoad);
15562     Chains.push_back(SDValue(NewLoad.getNode(), 1));
15563   }
15564 
15565   // Float truncs need to extended with VCVTB's into their floating point types.
15566   if (FromEltVT == MVT::f16) {
15567     SmallVector<SDValue, 4> Extends;
15568 
15569     for (unsigned i = 0; i < Loads.size(); i++) {
15570       SDValue LoadBC =
15571           DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
15572       SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
15573                                   DAG.getConstant(0, DL, MVT::i32));
15574       Extends.push_back(FPExt);
15575     }
15576 
15577     Loads = Extends;
15578   }
15579 
15580   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15581   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
15582   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
15583 }
15584 
15585 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
15586 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
15587 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
15588                                     const ARMSubtarget *ST) {
15589   SDValue N0 = N->getOperand(0);
15590 
15591   // Check for sign- and zero-extensions of vector extract operations of 8- and
15592   // 16-bit vector elements. NEON and MVE support these directly. They are
15593   // handled during DAG combining because type legalization will promote them
15594   // to 32-bit types and it is messy to recognize the operations after that.
15595   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
15596       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15597     SDValue Vec = N0.getOperand(0);
15598     SDValue Lane = N0.getOperand(1);
15599     EVT VT = N->getValueType(0);
15600     EVT EltVT = N0.getValueType();
15601     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15602 
15603     if (VT == MVT::i32 &&
15604         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
15605         TLI.isTypeLegal(Vec.getValueType()) &&
15606         isa<ConstantSDNode>(Lane)) {
15607 
15608       unsigned Opc = 0;
15609       switch (N->getOpcode()) {
15610       default: llvm_unreachable("unexpected opcode");
15611       case ISD::SIGN_EXTEND:
15612         Opc = ARMISD::VGETLANEs;
15613         break;
15614       case ISD::ZERO_EXTEND:
15615       case ISD::ANY_EXTEND:
15616         Opc = ARMISD::VGETLANEu;
15617         break;
15618       }
15619       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
15620     }
15621   }
15622 
15623   if (ST->hasMVEIntegerOps())
15624     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15625       return NewLoad;
15626 
15627   return SDValue();
15628 }
15629 
15630 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
15631                                       const ARMSubtarget *ST) {
15632   if (ST->hasMVEFloatOps())
15633     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15634       return NewLoad;
15635 
15636   return SDValue();
15637 }
15638 
15639 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
15640 /// saturates.
15641 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
15642                                     const ARMSubtarget *ST) {
15643   EVT VT = N->getValueType(0);
15644   SDValue N0 = N->getOperand(0);
15645   if (!ST->hasMVEIntegerOps())
15646     return SDValue();
15647 
15648   if (SDValue V = PerformVQDMULHCombine(N, DAG))
15649     return V;
15650 
15651   if (VT != MVT::v4i32 && VT != MVT::v8i16)
15652     return SDValue();
15653 
15654   auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
15655     // Check one is a smin and the other is a smax
15656     if (Min->getOpcode() != ISD::SMIN)
15657       std::swap(Min, Max);
15658     if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
15659       return false;
15660 
15661     APInt SaturateC;
15662     if (VT == MVT::v4i32)
15663       SaturateC = APInt(32, (1 << 15) - 1, true);
15664     else //if (VT == MVT::v8i16)
15665       SaturateC = APInt(16, (1 << 7) - 1, true);
15666 
15667     APInt MinC, MaxC;
15668     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15669         MinC != SaturateC)
15670       return false;
15671     if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
15672         MaxC != ~SaturateC)
15673       return false;
15674     return true;
15675   };
15676 
15677   if (IsSignedSaturate(N, N0.getNode())) {
15678     SDLoc DL(N);
15679     MVT ExtVT, HalfVT;
15680     if (VT == MVT::v4i32) {
15681       HalfVT = MVT::v8i16;
15682       ExtVT = MVT::v4i16;
15683     } else { // if (VT == MVT::v8i16)
15684       HalfVT = MVT::v16i8;
15685       ExtVT = MVT::v8i8;
15686     }
15687 
15688     // Create a VQMOVNB with undef top lanes, then signed extended into the top
15689     // half. That extend will hopefully be removed if only the bottom bits are
15690     // demanded (though a truncating store, for example).
15691     SDValue VQMOVN =
15692         DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
15693                     N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
15694     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15695     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
15696                        DAG.getValueType(ExtVT));
15697   }
15698 
15699   auto IsUnsignedSaturate = [&](SDNode *Min) {
15700     // For unsigned, we just need to check for <= 0xffff
15701     if (Min->getOpcode() != ISD::UMIN)
15702       return false;
15703 
15704     APInt SaturateC;
15705     if (VT == MVT::v4i32)
15706       SaturateC = APInt(32, (1 << 16) - 1, true);
15707     else //if (VT == MVT::v8i16)
15708       SaturateC = APInt(16, (1 << 8) - 1, true);
15709 
15710     APInt MinC;
15711     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15712         MinC != SaturateC)
15713       return false;
15714     return true;
15715   };
15716 
15717   if (IsUnsignedSaturate(N)) {
15718     SDLoc DL(N);
15719     MVT HalfVT;
15720     unsigned ExtConst;
15721     if (VT == MVT::v4i32) {
15722       HalfVT = MVT::v8i16;
15723       ExtConst = 0x0000FFFF;
15724     } else { //if (VT == MVT::v8i16)
15725       HalfVT = MVT::v16i8;
15726       ExtConst = 0x00FF;
15727     }
15728 
15729     // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
15730     // an AND. That extend will hopefully be removed if only the bottom bits are
15731     // demanded (though a truncating store, for example).
15732     SDValue VQMOVN =
15733         DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
15734                     DAG.getConstant(0, DL, MVT::i32));
15735     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15736     return DAG.getNode(ISD::AND, DL, VT, Bitcast,
15737                        DAG.getConstant(ExtConst, DL, VT));
15738   }
15739 
15740   return SDValue();
15741 }
15742 
15743 static const APInt *isPowerOf2Constant(SDValue V) {
15744   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15745   if (!C)
15746     return nullptr;
15747   const APInt *CV = &C->getAPIntValue();
15748   return CV->isPowerOf2() ? CV : nullptr;
15749 }
15750 
15751 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
15752   // If we have a CMOV, OR and AND combination such as:
15753   //   if (x & CN)
15754   //     y |= CM;
15755   //
15756   // And:
15757   //   * CN is a single bit;
15758   //   * All bits covered by CM are known zero in y
15759   //
15760   // Then we can convert this into a sequence of BFI instructions. This will
15761   // always be a win if CM is a single bit, will always be no worse than the
15762   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
15763   // three bits (due to the extra IT instruction).
15764 
15765   SDValue Op0 = CMOV->getOperand(0);
15766   SDValue Op1 = CMOV->getOperand(1);
15767   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
15768   auto CC = CCNode->getAPIntValue().getLimitedValue();
15769   SDValue CmpZ = CMOV->getOperand(4);
15770 
15771   // The compare must be against zero.
15772   if (!isNullConstant(CmpZ->getOperand(1)))
15773     return SDValue();
15774 
15775   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
15776   SDValue And = CmpZ->getOperand(0);
15777   if (And->getOpcode() != ISD::AND)
15778     return SDValue();
15779   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
15780   if (!AndC)
15781     return SDValue();
15782   SDValue X = And->getOperand(0);
15783 
15784   if (CC == ARMCC::EQ) {
15785     // We're performing an "equal to zero" compare. Swap the operands so we
15786     // canonicalize on a "not equal to zero" compare.
15787     std::swap(Op0, Op1);
15788   } else {
15789     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
15790   }
15791 
15792   if (Op1->getOpcode() != ISD::OR)
15793     return SDValue();
15794 
15795   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
15796   if (!OrC)
15797     return SDValue();
15798   SDValue Y = Op1->getOperand(0);
15799 
15800   if (Op0 != Y)
15801     return SDValue();
15802 
15803   // Now, is it profitable to continue?
15804   APInt OrCI = OrC->getAPIntValue();
15805   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
15806   if (OrCI.countPopulation() > Heuristic)
15807     return SDValue();
15808 
15809   // Lastly, can we determine that the bits defined by OrCI
15810   // are zero in Y?
15811   KnownBits Known = DAG.computeKnownBits(Y);
15812   if ((OrCI & Known.Zero) != OrCI)
15813     return SDValue();
15814 
15815   // OK, we can do the combine.
15816   SDValue V = Y;
15817   SDLoc dl(X);
15818   EVT VT = X.getValueType();
15819   unsigned BitInX = AndC->logBase2();
15820 
15821   if (BitInX != 0) {
15822     // We must shift X first.
15823     X = DAG.getNode(ISD::SRL, dl, VT, X,
15824                     DAG.getConstant(BitInX, dl, VT));
15825   }
15826 
15827   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
15828        BitInY < NumActiveBits; ++BitInY) {
15829     if (OrCI[BitInY] == 0)
15830       continue;
15831     APInt Mask(VT.getSizeInBits(), 0);
15832     Mask.setBit(BitInY);
15833     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
15834                     // Confusingly, the operand is an *inverted* mask.
15835                     DAG.getConstant(~Mask, dl, VT));
15836   }
15837 
15838   return V;
15839 }
15840 
15841 // Given N, the value controlling the conditional branch, search for the loop
15842 // intrinsic, returning it, along with how the value is used. We need to handle
15843 // patterns such as the following:
15844 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
15845 // (brcond (setcc (loop.decrement), 0, eq), exit)
15846 // (brcond (setcc (loop.decrement), 0, ne), header)
15847 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
15848                                    bool &Negate) {
15849   switch (N->getOpcode()) {
15850   default:
15851     break;
15852   case ISD::XOR: {
15853     if (!isa<ConstantSDNode>(N.getOperand(1)))
15854       return SDValue();
15855     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
15856       return SDValue();
15857     Negate = !Negate;
15858     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
15859   }
15860   case ISD::SETCC: {
15861     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
15862     if (!Const)
15863       return SDValue();
15864     if (Const->isNullValue())
15865       Imm = 0;
15866     else if (Const->isOne())
15867       Imm = 1;
15868     else
15869       return SDValue();
15870     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
15871     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
15872   }
15873   case ISD::INTRINSIC_W_CHAIN: {
15874     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
15875     if (IntOp != Intrinsic::test_set_loop_iterations &&
15876         IntOp != Intrinsic::loop_decrement_reg)
15877       return SDValue();
15878     return N;
15879   }
15880   }
15881   return SDValue();
15882 }
15883 
15884 static SDValue PerformHWLoopCombine(SDNode *N,
15885                                     TargetLowering::DAGCombinerInfo &DCI,
15886                                     const ARMSubtarget *ST) {
15887 
15888   // The hwloop intrinsics that we're interested are used for control-flow,
15889   // either for entering or exiting the loop:
15890   // - test.set.loop.iterations will test whether its operand is zero. If it
15891   //   is zero, the proceeding branch should not enter the loop.
15892   // - loop.decrement.reg also tests whether its operand is zero. If it is
15893   //   zero, the proceeding branch should not branch back to the beginning of
15894   //   the loop.
15895   // So here, we need to check that how the brcond is using the result of each
15896   // of the intrinsics to ensure that we're branching to the right place at the
15897   // right time.
15898 
15899   ISD::CondCode CC;
15900   SDValue Cond;
15901   int Imm = 1;
15902   bool Negate = false;
15903   SDValue Chain = N->getOperand(0);
15904   SDValue Dest;
15905 
15906   if (N->getOpcode() == ISD::BRCOND) {
15907     CC = ISD::SETEQ;
15908     Cond = N->getOperand(1);
15909     Dest = N->getOperand(2);
15910   } else {
15911     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
15912     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15913     Cond = N->getOperand(2);
15914     Dest = N->getOperand(4);
15915     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
15916       if (!Const->isOne() && !Const->isNullValue())
15917         return SDValue();
15918       Imm = Const->getZExtValue();
15919     } else
15920       return SDValue();
15921   }
15922 
15923   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
15924   if (!Int)
15925     return SDValue();
15926 
15927   if (Negate)
15928     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
15929 
15930   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
15931     return (CC == ISD::SETEQ && Imm == 0) ||
15932            (CC == ISD::SETNE && Imm == 1) ||
15933            (CC == ISD::SETLT && Imm == 1) ||
15934            (CC == ISD::SETULT && Imm == 1);
15935   };
15936 
15937   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
15938     return (CC == ISD::SETEQ && Imm == 1) ||
15939            (CC == ISD::SETNE && Imm == 0) ||
15940            (CC == ISD::SETGT && Imm == 0) ||
15941            (CC == ISD::SETUGT && Imm == 0) ||
15942            (CC == ISD::SETGE && Imm == 1) ||
15943            (CC == ISD::SETUGE && Imm == 1);
15944   };
15945 
15946   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
15947          "unsupported condition");
15948 
15949   SDLoc dl(Int);
15950   SelectionDAG &DAG = DCI.DAG;
15951   SDValue Elements = Int.getOperand(2);
15952   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
15953   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
15954           && "expected single br user");
15955   SDNode *Br = *N->use_begin();
15956   SDValue OtherTarget = Br->getOperand(1);
15957 
15958   // Update the unconditional branch to branch to the given Dest.
15959   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
15960     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
15961     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
15962     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
15963   };
15964 
15965   if (IntOp == Intrinsic::test_set_loop_iterations) {
15966     SDValue Res;
15967     // We expect this 'instruction' to branch when the counter is zero.
15968     if (IsTrueIfZero(CC, Imm)) {
15969       SDValue Ops[] = { Chain, Elements, Dest };
15970       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15971     } else {
15972       // The logic is the reverse of what we need for WLS, so find the other
15973       // basic block target: the target of the proceeding br.
15974       UpdateUncondBr(Br, Dest, DAG);
15975 
15976       SDValue Ops[] = { Chain, Elements, OtherTarget };
15977       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15978     }
15979     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
15980     return Res;
15981   } else {
15982     SDValue Size = DAG.getTargetConstant(
15983       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
15984     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
15985     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
15986                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
15987     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
15988 
15989     // We expect this instruction to branch when the count is not zero.
15990     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
15991 
15992     // Update the unconditional branch to target the loop preheader if we've
15993     // found the condition has been reversed.
15994     if (Target == OtherTarget)
15995       UpdateUncondBr(Br, Dest, DAG);
15996 
15997     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15998                         SDValue(LoopDec.getNode(), 1), Chain);
15999 
16000     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
16001     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
16002   }
16003   return SDValue();
16004 }
16005 
16006 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
16007 SDValue
16008 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
16009   SDValue Cmp = N->getOperand(4);
16010   if (Cmp.getOpcode() != ARMISD::CMPZ)
16011     // Only looking at NE cases.
16012     return SDValue();
16013 
16014   EVT VT = N->getValueType(0);
16015   SDLoc dl(N);
16016   SDValue LHS = Cmp.getOperand(0);
16017   SDValue RHS = Cmp.getOperand(1);
16018   SDValue Chain = N->getOperand(0);
16019   SDValue BB = N->getOperand(1);
16020   SDValue ARMcc = N->getOperand(2);
16021   ARMCC::CondCodes CC =
16022     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
16023 
16024   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
16025   // -> (brcond Chain BB CC CPSR Cmp)
16026   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
16027       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
16028       LHS->getOperand(0)->hasOneUse()) {
16029     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
16030     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
16031     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16032     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
16033     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
16034         (LHS01C && LHS01C->getZExtValue() == 1) &&
16035         (LHS1C && LHS1C->getZExtValue() == 1) &&
16036         (RHSC && RHSC->getZExtValue() == 0)) {
16037       return DAG.getNode(
16038           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
16039           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
16040     }
16041   }
16042 
16043   return SDValue();
16044 }
16045 
16046 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
16047 SDValue
16048 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
16049   SDValue Cmp = N->getOperand(4);
16050   if (Cmp.getOpcode() != ARMISD::CMPZ)
16051     // Only looking at EQ and NE cases.
16052     return SDValue();
16053 
16054   EVT VT = N->getValueType(0);
16055   SDLoc dl(N);
16056   SDValue LHS = Cmp.getOperand(0);
16057   SDValue RHS = Cmp.getOperand(1);
16058   SDValue FalseVal = N->getOperand(0);
16059   SDValue TrueVal = N->getOperand(1);
16060   SDValue ARMcc = N->getOperand(2);
16061   ARMCC::CondCodes CC =
16062     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
16063 
16064   // BFI is only available on V6T2+.
16065   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
16066     SDValue R = PerformCMOVToBFICombine(N, DAG);
16067     if (R)
16068       return R;
16069   }
16070 
16071   // Simplify
16072   //   mov     r1, r0
16073   //   cmp     r1, x
16074   //   mov     r0, y
16075   //   moveq   r0, x
16076   // to
16077   //   cmp     r0, x
16078   //   movne   r0, y
16079   //
16080   //   mov     r1, r0
16081   //   cmp     r1, x
16082   //   mov     r0, x
16083   //   movne   r0, y
16084   // to
16085   //   cmp     r0, x
16086   //   movne   r0, y
16087   /// FIXME: Turn this into a target neutral optimization?
16088   SDValue Res;
16089   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
16090     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
16091                       N->getOperand(3), Cmp);
16092   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
16093     SDValue ARMcc;
16094     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
16095     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
16096                       N->getOperand(3), NewCmp);
16097   }
16098 
16099   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
16100   // -> (cmov F T CC CPSR Cmp)
16101   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
16102     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
16103     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
16104     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
16105     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
16106         (LHS1C && LHS1C->getZExtValue() == 1) &&
16107         (RHSC && RHSC->getZExtValue() == 0)) {
16108       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
16109                          LHS->getOperand(2), LHS->getOperand(3),
16110                          LHS->getOperand(4));
16111     }
16112   }
16113 
16114   if (!VT.isInteger())
16115       return SDValue();
16116 
16117   // Materialize a boolean comparison for integers so we can avoid branching.
16118   if (isNullConstant(FalseVal)) {
16119     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
16120       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
16121         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
16122         // right 5 bits will make that 32 be 1, otherwise it will be 0.
16123         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
16124         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
16125         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
16126                           DAG.getConstant(5, dl, MVT::i32));
16127       } else {
16128         // CMOV 0, 1, ==, (CMPZ x, y) ->
16129         //     (ADDCARRY (SUB x, y), t:0, t:1)
16130         // where t = (SUBCARRY 0, (SUB x, y), 0)
16131         //
16132         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
16133         // x != y. In other words, a carry C == 1 when x == y, C == 0
16134         // otherwise.
16135         // The final ADDCARRY computes
16136         //     x - y + (0 - (x - y)) + C == C
16137         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
16138         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16139         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
16140         // ISD::SUBCARRY returns a borrow but we want the carry here
16141         // actually.
16142         SDValue Carry =
16143             DAG.getNode(ISD::SUB, dl, MVT::i32,
16144                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
16145         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
16146       }
16147     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
16148                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
16149       // This seems pointless but will allow us to combine it further below.
16150       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
16151       SDValue Sub =
16152           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
16153       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
16154                                           Sub.getValue(1), SDValue());
16155       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
16156                         N->getOperand(3), CPSRGlue.getValue(1));
16157       FalseVal = Sub;
16158     }
16159   } else if (isNullConstant(TrueVal)) {
16160     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
16161         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
16162       // This seems pointless but will allow us to combine it further below
16163       // Note that we change == for != as this is the dual for the case above.
16164       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
16165       SDValue Sub =
16166           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
16167       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
16168                                           Sub.getValue(1), SDValue());
16169       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
16170                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
16171                         N->getOperand(3), CPSRGlue.getValue(1));
16172       FalseVal = Sub;
16173     }
16174   }
16175 
16176   // On Thumb1, the DAG above may be further combined if z is a power of 2
16177   // (z == 2 ^ K).
16178   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
16179   // t1 = (USUBO (SUB x, y), 1)
16180   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
16181   // Result = if K != 0 then (SHL t2:0, K) else t2:0
16182   //
16183   // This also handles the special case of comparing against zero; it's
16184   // essentially, the same pattern, except there's no SUBS:
16185   // CMOV x, z, !=, (CMPZ x, 0) ->
16186   // t1 = (USUBO x, 1)
16187   // t2 = (SUBCARRY x, t1:0, t1:1)
16188   // Result = if K != 0 then (SHL t2:0, K) else t2:0
16189   const APInt *TrueConst;
16190   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
16191       ((FalseVal.getOpcode() == ARMISD::SUBS &&
16192         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
16193        (FalseVal == LHS && isNullConstant(RHS))) &&
16194       (TrueConst = isPowerOf2Constant(TrueVal))) {
16195     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16196     unsigned ShiftAmount = TrueConst->logBase2();
16197     if (ShiftAmount)
16198       TrueVal = DAG.getConstant(1, dl, VT);
16199     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
16200     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
16201 
16202     if (ShiftAmount)
16203       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
16204                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
16205   }
16206 
16207   if (Res.getNode()) {
16208     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
16209     // Capture demanded bits information that would be otherwise lost.
16210     if (Known.Zero == 0xfffffffe)
16211       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16212                         DAG.getValueType(MVT::i1));
16213     else if (Known.Zero == 0xffffff00)
16214       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16215                         DAG.getValueType(MVT::i8));
16216     else if (Known.Zero == 0xffff0000)
16217       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16218                         DAG.getValueType(MVT::i16));
16219   }
16220 
16221   return Res;
16222 }
16223 
16224 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
16225                                     const ARMSubtarget *ST) {
16226   SDValue Src = N->getOperand(0);
16227   EVT DstVT = N->getValueType(0);
16228 
16229   // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
16230   if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
16231     EVT SrcVT = Src.getValueType();
16232     if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
16233       return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
16234   }
16235 
16236   // We may have a bitcast of something that has already had this bitcast
16237   // combine performed on it, so skip past any VECTOR_REG_CASTs.
16238   while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
16239     Src = Src.getOperand(0);
16240 
16241   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
16242   // would be generated is at least the width of the element type.
16243   EVT SrcVT = Src.getValueType();
16244   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
16245        Src.getOpcode() == ARMISD::VMVNIMM ||
16246        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
16247       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
16248       DAG.getDataLayout().isBigEndian())
16249     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
16250 
16251   return SDValue();
16252 }
16253 
16254 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
16255                                              DAGCombinerInfo &DCI) const {
16256   switch (N->getOpcode()) {
16257   default: break;
16258   case ISD::SELECT_CC:
16259   case ISD::SELECT:     return PerformSELECTCombine(N, DCI, Subtarget);
16260   case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
16261   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
16262   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
16263   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
16264   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
16265   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
16266   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
16267   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
16268   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
16269   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
16270   case ISD::BRCOND:
16271   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
16272   case ARMISD::ADDC:
16273   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
16274   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
16275   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
16276   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
16277   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
16278   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
16279   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI);
16280   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
16281   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
16282   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
16283   case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI);
16284   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
16285   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
16286   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
16287   case ISD::FP_TO_SINT:
16288   case ISD::FP_TO_UINT:
16289     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
16290   case ISD::FDIV:
16291     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
16292   case ISD::INTRINSIC_WO_CHAIN:
16293     return PerformIntrinsicCombine(N, DCI);
16294   case ISD::SHL:
16295   case ISD::SRA:
16296   case ISD::SRL:
16297     return PerformShiftCombine(N, DCI, Subtarget);
16298   case ISD::SIGN_EXTEND:
16299   case ISD::ZERO_EXTEND:
16300   case ISD::ANY_EXTEND:
16301     return PerformExtendCombine(N, DCI.DAG, Subtarget);
16302   case ISD::FP_EXTEND:
16303     return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
16304   case ISD::SMIN:
16305   case ISD::UMIN:
16306   case ISD::SMAX:
16307   case ISD::UMAX:
16308     return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
16309   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
16310   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
16311   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
16312   case ARMISD::VLD1DUP:
16313   case ARMISD::VLD2DUP:
16314   case ARMISD::VLD3DUP:
16315   case ARMISD::VLD4DUP:
16316     return PerformVLDCombine(N, DCI);
16317   case ARMISD::BUILD_VECTOR:
16318     return PerformARMBUILD_VECTORCombine(N, DCI);
16319   case ISD::BITCAST:
16320     return PerformBITCASTCombine(N, DCI.DAG, Subtarget);
16321   case ARMISD::PREDICATE_CAST:
16322     return PerformPREDICATE_CASTCombine(N, DCI);
16323   case ARMISD::VECTOR_REG_CAST:
16324     return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
16325   case ARMISD::VCMP:
16326     return PerformVCMPCombine(N, DCI, Subtarget);
16327   case ISD::VECREDUCE_ADD:
16328     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
16329   case ARMISD::VMOVN:
16330     return PerformVMOVNCombine(N, DCI);
16331   case ARMISD::VQMOVNs:
16332   case ARMISD::VQMOVNu:
16333     return PerformVQMOVNCombine(N, DCI);
16334   case ARMISD::ASRL:
16335   case ARMISD::LSRL:
16336   case ARMISD::LSLL:
16337     return PerformLongShiftCombine(N, DCI.DAG);
16338   case ARMISD::SMULWB: {
16339     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16340     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16341     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16342       return SDValue();
16343     break;
16344   }
16345   case ARMISD::SMULWT: {
16346     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16347     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16348     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16349       return SDValue();
16350     break;
16351   }
16352   case ARMISD::SMLALBB:
16353   case ARMISD::QADD16b:
16354   case ARMISD::QSUB16b: {
16355     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16356     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16357     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16358         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16359       return SDValue();
16360     break;
16361   }
16362   case ARMISD::SMLALBT: {
16363     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
16364     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16365     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
16366     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16367     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
16368         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
16369       return SDValue();
16370     break;
16371   }
16372   case ARMISD::SMLALTB: {
16373     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
16374     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16375     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
16376     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16377     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
16378         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
16379       return SDValue();
16380     break;
16381   }
16382   case ARMISD::SMLALTT: {
16383     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16384     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16385     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16386         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16387       return SDValue();
16388     break;
16389   }
16390   case ARMISD::QADD8b:
16391   case ARMISD::QSUB8b: {
16392     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16393     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
16394     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16395         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16396       return SDValue();
16397     break;
16398   }
16399   case ISD::INTRINSIC_VOID:
16400   case ISD::INTRINSIC_W_CHAIN:
16401     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
16402     case Intrinsic::arm_neon_vld1:
16403     case Intrinsic::arm_neon_vld1x2:
16404     case Intrinsic::arm_neon_vld1x3:
16405     case Intrinsic::arm_neon_vld1x4:
16406     case Intrinsic::arm_neon_vld2:
16407     case Intrinsic::arm_neon_vld3:
16408     case Intrinsic::arm_neon_vld4:
16409     case Intrinsic::arm_neon_vld2lane:
16410     case Intrinsic::arm_neon_vld3lane:
16411     case Intrinsic::arm_neon_vld4lane:
16412     case Intrinsic::arm_neon_vld2dup:
16413     case Intrinsic::arm_neon_vld3dup:
16414     case Intrinsic::arm_neon_vld4dup:
16415     case Intrinsic::arm_neon_vst1:
16416     case Intrinsic::arm_neon_vst1x2:
16417     case Intrinsic::arm_neon_vst1x3:
16418     case Intrinsic::arm_neon_vst1x4:
16419     case Intrinsic::arm_neon_vst2:
16420     case Intrinsic::arm_neon_vst3:
16421     case Intrinsic::arm_neon_vst4:
16422     case Intrinsic::arm_neon_vst2lane:
16423     case Intrinsic::arm_neon_vst3lane:
16424     case Intrinsic::arm_neon_vst4lane:
16425       return PerformVLDCombine(N, DCI);
16426     case Intrinsic::arm_mve_vld2q:
16427     case Intrinsic::arm_mve_vld4q:
16428     case Intrinsic::arm_mve_vst2q:
16429     case Intrinsic::arm_mve_vst4q:
16430       return PerformMVEVLDCombine(N, DCI);
16431     default: break;
16432     }
16433     break;
16434   }
16435   return SDValue();
16436 }
16437 
16438 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
16439                                                           EVT VT) const {
16440   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
16441 }
16442 
16443 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
16444                                                        unsigned Alignment,
16445                                                        MachineMemOperand::Flags,
16446                                                        bool *Fast) const {
16447   // Depends what it gets converted into if the type is weird.
16448   if (!VT.isSimple())
16449     return false;
16450 
16451   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
16452   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
16453   auto Ty = VT.getSimpleVT().SimpleTy;
16454 
16455   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
16456     // Unaligned access can use (for example) LRDB, LRDH, LDR
16457     if (AllowsUnaligned) {
16458       if (Fast)
16459         *Fast = Subtarget->hasV7Ops();
16460       return true;
16461     }
16462   }
16463 
16464   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
16465     // For any little-endian targets with neon, we can support unaligned ld/st
16466     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
16467     // A big-endian target may also explicitly support unaligned accesses
16468     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
16469       if (Fast)
16470         *Fast = true;
16471       return true;
16472     }
16473   }
16474 
16475   if (!Subtarget->hasMVEIntegerOps())
16476     return false;
16477 
16478   // These are for predicates
16479   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
16480     if (Fast)
16481       *Fast = true;
16482     return true;
16483   }
16484 
16485   // These are for truncated stores/narrowing loads. They are fine so long as
16486   // the alignment is at least the size of the item being loaded
16487   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
16488       Alignment >= VT.getScalarSizeInBits() / 8) {
16489     if (Fast)
16490       *Fast = true;
16491     return true;
16492   }
16493 
16494   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
16495   // VSTRW.U32 all store the vector register in exactly the same format, and
16496   // differ only in the range of their immediate offset field and the required
16497   // alignment. So there is always a store that can be used, regardless of
16498   // actual type.
16499   //
16500   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
16501   // VREV64.8) pair and get the same effect. This will likely be better than
16502   // aligning the vector through the stack.
16503   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
16504       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
16505       Ty == MVT::v2f64) {
16506     if (Fast)
16507       *Fast = true;
16508     return true;
16509   }
16510 
16511   return false;
16512 }
16513 
16514 
16515 EVT ARMTargetLowering::getOptimalMemOpType(
16516     const MemOp &Op, const AttributeList &FuncAttributes) const {
16517   // See if we can use NEON instructions for this...
16518   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
16519       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
16520     bool Fast;
16521     if (Op.size() >= 16 &&
16522         (Op.isAligned(Align(16)) ||
16523          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
16524                                          MachineMemOperand::MONone, &Fast) &&
16525           Fast))) {
16526       return MVT::v2f64;
16527     } else if (Op.size() >= 8 &&
16528                (Op.isAligned(Align(8)) ||
16529                 (allowsMisalignedMemoryAccesses(
16530                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
16531                  Fast))) {
16532       return MVT::f64;
16533     }
16534   }
16535 
16536   // Let the target-independent logic figure it out.
16537   return MVT::Other;
16538 }
16539 
16540 // 64-bit integers are split into their high and low parts and held in two
16541 // different registers, so the trunc is free since the low register can just
16542 // be used.
16543 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
16544   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
16545     return false;
16546   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
16547   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
16548   return (SrcBits == 64 && DestBits == 32);
16549 }
16550 
16551 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
16552   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
16553       !DstVT.isInteger())
16554     return false;
16555   unsigned SrcBits = SrcVT.getSizeInBits();
16556   unsigned DestBits = DstVT.getSizeInBits();
16557   return (SrcBits == 64 && DestBits == 32);
16558 }
16559 
16560 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16561   if (Val.getOpcode() != ISD::LOAD)
16562     return false;
16563 
16564   EVT VT1 = Val.getValueType();
16565   if (!VT1.isSimple() || !VT1.isInteger() ||
16566       !VT2.isSimple() || !VT2.isInteger())
16567     return false;
16568 
16569   switch (VT1.getSimpleVT().SimpleTy) {
16570   default: break;
16571   case MVT::i1:
16572   case MVT::i8:
16573   case MVT::i16:
16574     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
16575     return true;
16576   }
16577 
16578   return false;
16579 }
16580 
16581 bool ARMTargetLowering::isFNegFree(EVT VT) const {
16582   if (!VT.isSimple())
16583     return false;
16584 
16585   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
16586   // negate values directly (fneg is free). So, we don't want to let the DAG
16587   // combiner rewrite fneg into xors and some other instructions.  For f16 and
16588   // FullFP16 argument passing, some bitcast nodes may be introduced,
16589   // triggering this DAG combine rewrite, so we are avoiding that with this.
16590   switch (VT.getSimpleVT().SimpleTy) {
16591   default: break;
16592   case MVT::f16:
16593     return Subtarget->hasFullFP16();
16594   }
16595 
16596   return false;
16597 }
16598 
16599 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
16600 /// of the vector elements.
16601 static bool areExtractExts(Value *Ext1, Value *Ext2) {
16602   auto areExtDoubled = [](Instruction *Ext) {
16603     return Ext->getType()->getScalarSizeInBits() ==
16604            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
16605   };
16606 
16607   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
16608       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
16609       !areExtDoubled(cast<Instruction>(Ext1)) ||
16610       !areExtDoubled(cast<Instruction>(Ext2)))
16611     return false;
16612 
16613   return true;
16614 }
16615 
16616 /// Check if sinking \p I's operands to I's basic block is profitable, because
16617 /// the operands can be folded into a target instruction, e.g.
16618 /// sext/zext can be folded into vsubl.
16619 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
16620                                            SmallVectorImpl<Use *> &Ops) const {
16621   if (!I->getType()->isVectorTy())
16622     return false;
16623 
16624   if (Subtarget->hasNEON()) {
16625     switch (I->getOpcode()) {
16626     case Instruction::Sub:
16627     case Instruction::Add: {
16628       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
16629         return false;
16630       Ops.push_back(&I->getOperandUse(0));
16631       Ops.push_back(&I->getOperandUse(1));
16632       return true;
16633     }
16634     default:
16635       return false;
16636     }
16637   }
16638 
16639   if (!Subtarget->hasMVEIntegerOps())
16640     return false;
16641 
16642   auto IsFMSMul = [&](Instruction *I) {
16643     if (!I->hasOneUse())
16644       return false;
16645     auto *Sub = cast<Instruction>(*I->users().begin());
16646     return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
16647   };
16648   auto IsFMS = [&](Instruction *I) {
16649     if (match(I->getOperand(0), m_FNeg(m_Value())) ||
16650         match(I->getOperand(1), m_FNeg(m_Value())))
16651       return true;
16652     return false;
16653   };
16654 
16655   auto IsSinker = [&](Instruction *I, int Operand) {
16656     switch (I->getOpcode()) {
16657     case Instruction::Add:
16658     case Instruction::Mul:
16659     case Instruction::FAdd:
16660     case Instruction::ICmp:
16661     case Instruction::FCmp:
16662       return true;
16663     case Instruction::FMul:
16664       return !IsFMSMul(I);
16665     case Instruction::Sub:
16666     case Instruction::FSub:
16667     case Instruction::Shl:
16668     case Instruction::LShr:
16669     case Instruction::AShr:
16670       return Operand == 1;
16671     case Instruction::Call:
16672       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
16673         switch (II->getIntrinsicID()) {
16674         case Intrinsic::fma:
16675           return !IsFMS(I);
16676         case Intrinsic::arm_mve_add_predicated:
16677         case Intrinsic::arm_mve_mul_predicated:
16678         case Intrinsic::arm_mve_qadd_predicated:
16679         case Intrinsic::arm_mve_hadd_predicated:
16680         case Intrinsic::arm_mve_vqdmull_predicated:
16681         case Intrinsic::arm_mve_qdmulh_predicated:
16682         case Intrinsic::arm_mve_qrdmulh_predicated:
16683         case Intrinsic::arm_mve_fma_predicated:
16684           return true;
16685         case Intrinsic::arm_mve_sub_predicated:
16686         case Intrinsic::arm_mve_qsub_predicated:
16687         case Intrinsic::arm_mve_hsub_predicated:
16688           return Operand == 1;
16689         default:
16690           return false;
16691         }
16692       }
16693       return false;
16694     default:
16695       return false;
16696     }
16697   };
16698 
16699   for (auto OpIdx : enumerate(I->operands())) {
16700     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
16701     // Make sure we are not already sinking this operand
16702     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
16703       continue;
16704 
16705     Instruction *Shuffle = Op;
16706     if (Shuffle->getOpcode() == Instruction::BitCast)
16707       Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
16708     // We are looking for a splat that can be sunk.
16709     if (!Shuffle ||
16710         !match(Shuffle, m_Shuffle(
16711                             m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
16712                             m_Undef(), m_ZeroMask())))
16713       continue;
16714     if (!IsSinker(I, OpIdx.index()))
16715       continue;
16716 
16717     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
16718     // and vector registers
16719     for (Use &U : Op->uses()) {
16720       Instruction *Insn = cast<Instruction>(U.getUser());
16721       if (!IsSinker(Insn, U.getOperandNo()))
16722         return false;
16723     }
16724 
16725     Ops.push_back(&Shuffle->getOperandUse(0));
16726     if (Shuffle != Op)
16727       Ops.push_back(&Op->getOperandUse(0));
16728     Ops.push_back(&OpIdx.value());
16729   }
16730   return true;
16731 }
16732 
16733 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
16734   if (!Subtarget->hasMVEIntegerOps())
16735     return nullptr;
16736   Type *SVIType = SVI->getType();
16737   Type *ScalarType = SVIType->getScalarType();
16738 
16739   if (ScalarType->isFloatTy())
16740     return Type::getInt32Ty(SVIType->getContext());
16741   if (ScalarType->isHalfTy())
16742     return Type::getInt16Ty(SVIType->getContext());
16743   return nullptr;
16744 }
16745 
16746 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
16747   EVT VT = ExtVal.getValueType();
16748 
16749   if (!isTypeLegal(VT))
16750     return false;
16751 
16752   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
16753     if (Ld->isExpandingLoad())
16754       return false;
16755   }
16756 
16757   if (Subtarget->hasMVEIntegerOps())
16758     return true;
16759 
16760   // Don't create a loadext if we can fold the extension into a wide/long
16761   // instruction.
16762   // If there's more than one user instruction, the loadext is desirable no
16763   // matter what.  There can be two uses by the same instruction.
16764   if (ExtVal->use_empty() ||
16765       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
16766     return true;
16767 
16768   SDNode *U = *ExtVal->use_begin();
16769   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
16770        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
16771     return false;
16772 
16773   return true;
16774 }
16775 
16776 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16777   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16778     return false;
16779 
16780   if (!isTypeLegal(EVT::getEVT(Ty1)))
16781     return false;
16782 
16783   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16784 
16785   // Assuming the caller doesn't have a zeroext or signext return parameter,
16786   // truncation all the way down to i1 is valid.
16787   return true;
16788 }
16789 
16790 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
16791                                                 const AddrMode &AM, Type *Ty,
16792                                                 unsigned AS) const {
16793   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
16794     if (Subtarget->hasFPAO())
16795       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
16796     return 0;
16797   }
16798   return -1;
16799 }
16800 
16801 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
16802 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
16803 /// expanded to FMAs when this method returns true, otherwise fmuladd is
16804 /// expanded to fmul + fadd.
16805 ///
16806 /// ARM supports both fused and unfused multiply-add operations; we already
16807 /// lower a pair of fmul and fadd to the latter so it's not clear that there
16808 /// would be a gain or that the gain would be worthwhile enough to risk
16809 /// correctness bugs.
16810 ///
16811 /// For MVE, we set this to true as it helps simplify the need for some
16812 /// patterns (and we don't have the non-fused floating point instruction).
16813 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16814                                                    EVT VT) const {
16815   if (!VT.isSimple())
16816     return false;
16817 
16818   switch (VT.getSimpleVT().SimpleTy) {
16819   case MVT::v4f32:
16820   case MVT::v8f16:
16821     return Subtarget->hasMVEFloatOps();
16822   case MVT::f16:
16823     return Subtarget->useFPVFMx16();
16824   case MVT::f32:
16825     return Subtarget->useFPVFMx();
16826   case MVT::f64:
16827     return Subtarget->useFPVFMx64();
16828   default:
16829     break;
16830   }
16831 
16832   return false;
16833 }
16834 
16835 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
16836   if (V < 0)
16837     return false;
16838 
16839   unsigned Scale = 1;
16840   switch (VT.getSimpleVT().SimpleTy) {
16841   case MVT::i1:
16842   case MVT::i8:
16843     // Scale == 1;
16844     break;
16845   case MVT::i16:
16846     // Scale == 2;
16847     Scale = 2;
16848     break;
16849   default:
16850     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
16851     // Scale == 4;
16852     Scale = 4;
16853     break;
16854   }
16855 
16856   if ((V & (Scale - 1)) != 0)
16857     return false;
16858   return isUInt<5>(V / Scale);
16859 }
16860 
16861 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
16862                                       const ARMSubtarget *Subtarget) {
16863   if (!VT.isInteger() && !VT.isFloatingPoint())
16864     return false;
16865   if (VT.isVector() && Subtarget->hasNEON())
16866     return false;
16867   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
16868       !Subtarget->hasMVEFloatOps())
16869     return false;
16870 
16871   bool IsNeg = false;
16872   if (V < 0) {
16873     IsNeg = true;
16874     V = -V;
16875   }
16876 
16877   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
16878 
16879   // MVE: size * imm7
16880   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
16881     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
16882     case MVT::i32:
16883     case MVT::f32:
16884       return isShiftedUInt<7,2>(V);
16885     case MVT::i16:
16886     case MVT::f16:
16887       return isShiftedUInt<7,1>(V);
16888     case MVT::i8:
16889       return isUInt<7>(V);
16890     default:
16891       return false;
16892     }
16893   }
16894 
16895   // half VLDR: 2 * imm8
16896   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
16897     return isShiftedUInt<8, 1>(V);
16898   // VLDR and LDRD: 4 * imm8
16899   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
16900     return isShiftedUInt<8, 2>(V);
16901 
16902   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
16903     // + imm12 or - imm8
16904     if (IsNeg)
16905       return isUInt<8>(V);
16906     return isUInt<12>(V);
16907   }
16908 
16909   return false;
16910 }
16911 
16912 /// isLegalAddressImmediate - Return true if the integer value can be used
16913 /// as the offset of the target addressing mode for load / store of the
16914 /// given type.
16915 static bool isLegalAddressImmediate(int64_t V, EVT VT,
16916                                     const ARMSubtarget *Subtarget) {
16917   if (V == 0)
16918     return true;
16919 
16920   if (!VT.isSimple())
16921     return false;
16922 
16923   if (Subtarget->isThumb1Only())
16924     return isLegalT1AddressImmediate(V, VT);
16925   else if (Subtarget->isThumb2())
16926     return isLegalT2AddressImmediate(V, VT, Subtarget);
16927 
16928   // ARM mode.
16929   if (V < 0)
16930     V = - V;
16931   switch (VT.getSimpleVT().SimpleTy) {
16932   default: return false;
16933   case MVT::i1:
16934   case MVT::i8:
16935   case MVT::i32:
16936     // +- imm12
16937     return isUInt<12>(V);
16938   case MVT::i16:
16939     // +- imm8
16940     return isUInt<8>(V);
16941   case MVT::f32:
16942   case MVT::f64:
16943     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
16944       return false;
16945     return isShiftedUInt<8, 2>(V);
16946   }
16947 }
16948 
16949 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
16950                                                       EVT VT) const {
16951   int Scale = AM.Scale;
16952   if (Scale < 0)
16953     return false;
16954 
16955   switch (VT.getSimpleVT().SimpleTy) {
16956   default: return false;
16957   case MVT::i1:
16958   case MVT::i8:
16959   case MVT::i16:
16960   case MVT::i32:
16961     if (Scale == 1)
16962       return true;
16963     // r + r << imm
16964     Scale = Scale & ~1;
16965     return Scale == 2 || Scale == 4 || Scale == 8;
16966   case MVT::i64:
16967     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
16968     // version in Thumb mode.
16969     // r + r
16970     if (Scale == 1)
16971       return true;
16972     // r * 2 (this can be lowered to r + r).
16973     if (!AM.HasBaseReg && Scale == 2)
16974       return true;
16975     return false;
16976   case MVT::isVoid:
16977     // Note, we allow "void" uses (basically, uses that aren't loads or
16978     // stores), because arm allows folding a scale into many arithmetic
16979     // operations.  This should be made more precise and revisited later.
16980 
16981     // Allow r << imm, but the imm has to be a multiple of two.
16982     if (Scale & 1) return false;
16983     return isPowerOf2_32(Scale);
16984   }
16985 }
16986 
16987 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
16988                                                       EVT VT) const {
16989   const int Scale = AM.Scale;
16990 
16991   // Negative scales are not supported in Thumb1.
16992   if (Scale < 0)
16993     return false;
16994 
16995   // Thumb1 addressing modes do not support register scaling excepting the
16996   // following cases:
16997   // 1. Scale == 1 means no scaling.
16998   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
16999   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
17000 }
17001 
17002 /// isLegalAddressingMode - Return true if the addressing mode represented
17003 /// by AM is legal for this target, for a load/store of the specified type.
17004 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
17005                                               const AddrMode &AM, Type *Ty,
17006                                               unsigned AS, Instruction *I) const {
17007   EVT VT = getValueType(DL, Ty, true);
17008   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
17009     return false;
17010 
17011   // Can never fold addr of global into load/store.
17012   if (AM.BaseGV)
17013     return false;
17014 
17015   switch (AM.Scale) {
17016   case 0:  // no scale reg, must be "r+i" or "r", or "i".
17017     break;
17018   default:
17019     // ARM doesn't support any R+R*scale+imm addr modes.
17020     if (AM.BaseOffs)
17021       return false;
17022 
17023     if (!VT.isSimple())
17024       return false;
17025 
17026     if (Subtarget->isThumb1Only())
17027       return isLegalT1ScaledAddressingMode(AM, VT);
17028 
17029     if (Subtarget->isThumb2())
17030       return isLegalT2ScaledAddressingMode(AM, VT);
17031 
17032     int Scale = AM.Scale;
17033     switch (VT.getSimpleVT().SimpleTy) {
17034     default: return false;
17035     case MVT::i1:
17036     case MVT::i8:
17037     case MVT::i32:
17038       if (Scale < 0) Scale = -Scale;
17039       if (Scale == 1)
17040         return true;
17041       // r + r << imm
17042       return isPowerOf2_32(Scale & ~1);
17043     case MVT::i16:
17044     case MVT::i64:
17045       // r +/- r
17046       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
17047         return true;
17048       // r * 2 (this can be lowered to r + r).
17049       if (!AM.HasBaseReg && Scale == 2)
17050         return true;
17051       return false;
17052 
17053     case MVT::isVoid:
17054       // Note, we allow "void" uses (basically, uses that aren't loads or
17055       // stores), because arm allows folding a scale into many arithmetic
17056       // operations.  This should be made more precise and revisited later.
17057 
17058       // Allow r << imm, but the imm has to be a multiple of two.
17059       if (Scale & 1) return false;
17060       return isPowerOf2_32(Scale);
17061     }
17062   }
17063   return true;
17064 }
17065 
17066 /// isLegalICmpImmediate - Return true if the specified immediate is legal
17067 /// icmp immediate, that is the target has icmp instructions which can compare
17068 /// a register against the immediate without having to materialize the
17069 /// immediate into a register.
17070 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17071   // Thumb2 and ARM modes can use cmn for negative immediates.
17072   if (!Subtarget->isThumb())
17073     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
17074            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
17075   if (Subtarget->isThumb2())
17076     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
17077            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
17078   // Thumb1 doesn't have cmn, and only 8-bit immediates.
17079   return Imm >= 0 && Imm <= 255;
17080 }
17081 
17082 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
17083 /// *or sub* immediate, that is the target has add or sub instructions which can
17084 /// add a register with the immediate without having to materialize the
17085 /// immediate into a register.
17086 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
17087   // Same encoding for add/sub, just flip the sign.
17088   int64_t AbsImm = std::abs(Imm);
17089   if (!Subtarget->isThumb())
17090     return ARM_AM::getSOImmVal(AbsImm) != -1;
17091   if (Subtarget->isThumb2())
17092     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
17093   // Thumb1 only has 8-bit unsigned immediate.
17094   return AbsImm >= 0 && AbsImm <= 255;
17095 }
17096 
17097 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
17098                                       bool isSEXTLoad, SDValue &Base,
17099                                       SDValue &Offset, bool &isInc,
17100                                       SelectionDAG &DAG) {
17101   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17102     return false;
17103 
17104   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
17105     // AddressingMode 3
17106     Base = Ptr->getOperand(0);
17107     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17108       int RHSC = (int)RHS->getZExtValue();
17109       if (RHSC < 0 && RHSC > -256) {
17110         assert(Ptr->getOpcode() == ISD::ADD);
17111         isInc = false;
17112         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17113         return true;
17114       }
17115     }
17116     isInc = (Ptr->getOpcode() == ISD::ADD);
17117     Offset = Ptr->getOperand(1);
17118     return true;
17119   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
17120     // AddressingMode 2
17121     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17122       int RHSC = (int)RHS->getZExtValue();
17123       if (RHSC < 0 && RHSC > -0x1000) {
17124         assert(Ptr->getOpcode() == ISD::ADD);
17125         isInc = false;
17126         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17127         Base = Ptr->getOperand(0);
17128         return true;
17129       }
17130     }
17131 
17132     if (Ptr->getOpcode() == ISD::ADD) {
17133       isInc = true;
17134       ARM_AM::ShiftOpc ShOpcVal=
17135         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
17136       if (ShOpcVal != ARM_AM::no_shift) {
17137         Base = Ptr->getOperand(1);
17138         Offset = Ptr->getOperand(0);
17139       } else {
17140         Base = Ptr->getOperand(0);
17141         Offset = Ptr->getOperand(1);
17142       }
17143       return true;
17144     }
17145 
17146     isInc = (Ptr->getOpcode() == ISD::ADD);
17147     Base = Ptr->getOperand(0);
17148     Offset = Ptr->getOperand(1);
17149     return true;
17150   }
17151 
17152   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
17153   return false;
17154 }
17155 
17156 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
17157                                      bool isSEXTLoad, SDValue &Base,
17158                                      SDValue &Offset, bool &isInc,
17159                                      SelectionDAG &DAG) {
17160   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17161     return false;
17162 
17163   Base = Ptr->getOperand(0);
17164   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
17165     int RHSC = (int)RHS->getZExtValue();
17166     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
17167       assert(Ptr->getOpcode() == ISD::ADD);
17168       isInc = false;
17169       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17170       return true;
17171     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
17172       isInc = Ptr->getOpcode() == ISD::ADD;
17173       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
17174       return true;
17175     }
17176   }
17177 
17178   return false;
17179 }
17180 
17181 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
17182                                       bool isSEXTLoad, bool IsMasked, bool isLE,
17183                                       SDValue &Base, SDValue &Offset,
17184                                       bool &isInc, SelectionDAG &DAG) {
17185   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
17186     return false;
17187   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
17188     return false;
17189 
17190   // We allow LE non-masked loads to change the type (for example use a vldrb.8
17191   // as opposed to a vldrw.32). This can allow extra addressing modes or
17192   // alignments for what is otherwise an equivalent instruction.
17193   bool CanChangeType = isLE && !IsMasked;
17194 
17195   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
17196   int RHSC = (int)RHS->getZExtValue();
17197 
17198   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
17199     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
17200       assert(Ptr->getOpcode() == ISD::ADD);
17201       isInc = false;
17202       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
17203       return true;
17204     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
17205       isInc = Ptr->getOpcode() == ISD::ADD;
17206       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
17207       return true;
17208     }
17209     return false;
17210   };
17211 
17212   // Try to find a matching instruction based on s/zext, Alignment, Offset and
17213   // (in BE/masked) type.
17214   Base = Ptr->getOperand(0);
17215   if (VT == MVT::v4i16) {
17216     if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
17217       return true;
17218   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
17219     if (IsInRange(RHSC, 0x80, 1))
17220       return true;
17221   } else if (Alignment >= 4 &&
17222              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
17223              IsInRange(RHSC, 0x80, 4))
17224     return true;
17225   else if (Alignment >= 2 &&
17226            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
17227            IsInRange(RHSC, 0x80, 2))
17228     return true;
17229   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
17230     return true;
17231   return false;
17232 }
17233 
17234 /// getPreIndexedAddressParts - returns true by value, base pointer and
17235 /// offset pointer and addressing mode by reference if the node's address
17236 /// can be legally represented as pre-indexed load / store address.
17237 bool
17238 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
17239                                              SDValue &Offset,
17240                                              ISD::MemIndexedMode &AM,
17241                                              SelectionDAG &DAG) const {
17242   if (Subtarget->isThumb1Only())
17243     return false;
17244 
17245   EVT VT;
17246   SDValue Ptr;
17247   Align Alignment;
17248   bool isSEXTLoad = false;
17249   bool IsMasked = false;
17250   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17251     Ptr = LD->getBasePtr();
17252     VT = LD->getMemoryVT();
17253     Alignment = LD->getAlign();
17254     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17255   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17256     Ptr = ST->getBasePtr();
17257     VT = ST->getMemoryVT();
17258     Alignment = ST->getAlign();
17259   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17260     Ptr = LD->getBasePtr();
17261     VT = LD->getMemoryVT();
17262     Alignment = LD->getAlign();
17263     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17264     IsMasked = true;
17265   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17266     Ptr = ST->getBasePtr();
17267     VT = ST->getMemoryVT();
17268     Alignment = ST->getAlign();
17269     IsMasked = true;
17270   } else
17271     return false;
17272 
17273   bool isInc;
17274   bool isLegal = false;
17275   if (VT.isVector())
17276     isLegal = Subtarget->hasMVEIntegerOps() &&
17277               getMVEIndexedAddressParts(
17278                   Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
17279                   Subtarget->isLittle(), Base, Offset, isInc, DAG);
17280   else {
17281     if (Subtarget->isThumb2())
17282       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17283                                          Offset, isInc, DAG);
17284     else
17285       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17286                                           Offset, isInc, DAG);
17287   }
17288   if (!isLegal)
17289     return false;
17290 
17291   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
17292   return true;
17293 }
17294 
17295 /// getPostIndexedAddressParts - returns true by value, base pointer and
17296 /// offset pointer and addressing mode by reference if this node can be
17297 /// combined with a load / store to form a post-indexed load / store.
17298 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
17299                                                    SDValue &Base,
17300                                                    SDValue &Offset,
17301                                                    ISD::MemIndexedMode &AM,
17302                                                    SelectionDAG &DAG) const {
17303   EVT VT;
17304   SDValue Ptr;
17305   Align Alignment;
17306   bool isSEXTLoad = false, isNonExt;
17307   bool IsMasked = false;
17308   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17309     VT = LD->getMemoryVT();
17310     Ptr = LD->getBasePtr();
17311     Alignment = LD->getAlign();
17312     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17313     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17314   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17315     VT = ST->getMemoryVT();
17316     Ptr = ST->getBasePtr();
17317     Alignment = ST->getAlign();
17318     isNonExt = !ST->isTruncatingStore();
17319   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17320     VT = LD->getMemoryVT();
17321     Ptr = LD->getBasePtr();
17322     Alignment = LD->getAlign();
17323     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17324     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17325     IsMasked = true;
17326   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17327     VT = ST->getMemoryVT();
17328     Ptr = ST->getBasePtr();
17329     Alignment = ST->getAlign();
17330     isNonExt = !ST->isTruncatingStore();
17331     IsMasked = true;
17332   } else
17333     return false;
17334 
17335   if (Subtarget->isThumb1Only()) {
17336     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
17337     // must be non-extending/truncating, i32, with an offset of 4.
17338     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
17339     if (Op->getOpcode() != ISD::ADD || !isNonExt)
17340       return false;
17341     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
17342     if (!RHS || RHS->getZExtValue() != 4)
17343       return false;
17344 
17345     Offset = Op->getOperand(1);
17346     Base = Op->getOperand(0);
17347     AM = ISD::POST_INC;
17348     return true;
17349   }
17350 
17351   bool isInc;
17352   bool isLegal = false;
17353   if (VT.isVector())
17354     isLegal = Subtarget->hasMVEIntegerOps() &&
17355               getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
17356                                         Subtarget->isLittle(), Base, Offset,
17357                                         isInc, DAG);
17358   else {
17359     if (Subtarget->isThumb2())
17360       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17361                                          isInc, DAG);
17362     else
17363       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17364                                           isInc, DAG);
17365   }
17366   if (!isLegal)
17367     return false;
17368 
17369   if (Ptr != Base) {
17370     // Swap base ptr and offset to catch more post-index load / store when
17371     // it's legal. In Thumb2 mode, offset must be an immediate.
17372     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
17373         !Subtarget->isThumb2())
17374       std::swap(Base, Offset);
17375 
17376     // Post-indexed load / store update the base pointer.
17377     if (Ptr != Base)
17378       return false;
17379   }
17380 
17381   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
17382   return true;
17383 }
17384 
17385 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17386                                                       KnownBits &Known,
17387                                                       const APInt &DemandedElts,
17388                                                       const SelectionDAG &DAG,
17389                                                       unsigned Depth) const {
17390   unsigned BitWidth = Known.getBitWidth();
17391   Known.resetAll();
17392   switch (Op.getOpcode()) {
17393   default: break;
17394   case ARMISD::ADDC:
17395   case ARMISD::ADDE:
17396   case ARMISD::SUBC:
17397   case ARMISD::SUBE:
17398     // Special cases when we convert a carry to a boolean.
17399     if (Op.getResNo() == 0) {
17400       SDValue LHS = Op.getOperand(0);
17401       SDValue RHS = Op.getOperand(1);
17402       // (ADDE 0, 0, C) will give us a single bit.
17403       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
17404           isNullConstant(RHS)) {
17405         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17406         return;
17407       }
17408     }
17409     break;
17410   case ARMISD::CMOV: {
17411     // Bits are known zero/one if known on the LHS and RHS.
17412     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
17413     if (Known.isUnknown())
17414       return;
17415 
17416     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
17417     Known.Zero &= KnownRHS.Zero;
17418     Known.One  &= KnownRHS.One;
17419     return;
17420   }
17421   case ISD::INTRINSIC_W_CHAIN: {
17422     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
17423     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
17424     switch (IntID) {
17425     default: return;
17426     case Intrinsic::arm_ldaex:
17427     case Intrinsic::arm_ldrex: {
17428       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
17429       unsigned MemBits = VT.getScalarSizeInBits();
17430       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
17431       return;
17432     }
17433     }
17434   }
17435   case ARMISD::BFI: {
17436     // Conservatively, we can recurse down the first operand
17437     // and just mask out all affected bits.
17438     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
17439 
17440     // The operand to BFI is already a mask suitable for removing the bits it
17441     // sets.
17442     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
17443     const APInt &Mask = CI->getAPIntValue();
17444     Known.Zero &= Mask;
17445     Known.One &= Mask;
17446     return;
17447   }
17448   case ARMISD::VGETLANEs:
17449   case ARMISD::VGETLANEu: {
17450     const SDValue &SrcSV = Op.getOperand(0);
17451     EVT VecVT = SrcSV.getValueType();
17452     assert(VecVT.isVector() && "VGETLANE expected a vector type");
17453     const unsigned NumSrcElts = VecVT.getVectorNumElements();
17454     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
17455     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
17456            "VGETLANE index out of bounds");
17457     unsigned Idx = Pos->getZExtValue();
17458     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
17459     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
17460 
17461     EVT VT = Op.getValueType();
17462     const unsigned DstSz = VT.getScalarSizeInBits();
17463     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
17464     (void)SrcSz;
17465     assert(SrcSz == Known.getBitWidth());
17466     assert(DstSz > SrcSz);
17467     if (Op.getOpcode() == ARMISD::VGETLANEs)
17468       Known = Known.sext(DstSz);
17469     else {
17470       Known = Known.zext(DstSz);
17471     }
17472     assert(DstSz == Known.getBitWidth());
17473     break;
17474   }
17475   case ARMISD::VMOVrh: {
17476     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
17477     assert(KnownOp.getBitWidth() == 16);
17478     Known = KnownOp.zext(32);
17479     break;
17480   }
17481   }
17482 }
17483 
17484 bool ARMTargetLowering::targetShrinkDemandedConstant(
17485     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
17486     TargetLoweringOpt &TLO) const {
17487   // Delay optimization, so we don't have to deal with illegal types, or block
17488   // optimizations.
17489   if (!TLO.LegalOps)
17490     return false;
17491 
17492   // Only optimize AND for now.
17493   if (Op.getOpcode() != ISD::AND)
17494     return false;
17495 
17496   EVT VT = Op.getValueType();
17497 
17498   // Ignore vectors.
17499   if (VT.isVector())
17500     return false;
17501 
17502   assert(VT == MVT::i32 && "Unexpected integer type");
17503 
17504   // Make sure the RHS really is a constant.
17505   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
17506   if (!C)
17507     return false;
17508 
17509   unsigned Mask = C->getZExtValue();
17510 
17511   unsigned Demanded = DemandedBits.getZExtValue();
17512   unsigned ShrunkMask = Mask & Demanded;
17513   unsigned ExpandedMask = Mask | ~Demanded;
17514 
17515   // If the mask is all zeros, let the target-independent code replace the
17516   // result with zero.
17517   if (ShrunkMask == 0)
17518     return false;
17519 
17520   // If the mask is all ones, erase the AND. (Currently, the target-independent
17521   // code won't do this, so we have to do it explicitly to avoid an infinite
17522   // loop in obscure cases.)
17523   if (ExpandedMask == ~0U)
17524     return TLO.CombineTo(Op, Op.getOperand(0));
17525 
17526   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
17527     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
17528   };
17529   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
17530     if (NewMask == Mask)
17531       return true;
17532     SDLoc DL(Op);
17533     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
17534     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
17535     return TLO.CombineTo(Op, NewOp);
17536   };
17537 
17538   // Prefer uxtb mask.
17539   if (IsLegalMask(0xFF))
17540     return UseMask(0xFF);
17541 
17542   // Prefer uxth mask.
17543   if (IsLegalMask(0xFFFF))
17544     return UseMask(0xFFFF);
17545 
17546   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
17547   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17548   if (ShrunkMask < 256)
17549     return UseMask(ShrunkMask);
17550 
17551   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
17552   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17553   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
17554     return UseMask(ExpandedMask);
17555 
17556   // Potential improvements:
17557   //
17558   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
17559   // We could try to prefer Thumb1 immediates which can be lowered to a
17560   // two-instruction sequence.
17561   // We could try to recognize more legal ARM/Thumb2 immediates here.
17562 
17563   return false;
17564 }
17565 
17566 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
17567     SDValue Op, const APInt &OriginalDemandedBits,
17568     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
17569     unsigned Depth) const {
17570   unsigned Opc = Op.getOpcode();
17571 
17572   switch (Opc) {
17573   case ARMISD::ASRL:
17574   case ARMISD::LSRL: {
17575     // If this is result 0 and the other result is unused, see if the demand
17576     // bits allow us to shrink this long shift into a standard small shift in
17577     // the opposite direction.
17578     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
17579         isa<ConstantSDNode>(Op->getOperand(2))) {
17580       unsigned ShAmt = Op->getConstantOperandVal(2);
17581       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
17582                             APInt::getAllOnesValue(32) << (32 - ShAmt)))
17583         return TLO.CombineTo(
17584             Op, TLO.DAG.getNode(
17585                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
17586                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
17587     }
17588     break;
17589   }
17590   }
17591 
17592   return TargetLowering::SimplifyDemandedBitsForTargetNode(
17593       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
17594 }
17595 
17596 //===----------------------------------------------------------------------===//
17597 //                           ARM Inline Assembly Support
17598 //===----------------------------------------------------------------------===//
17599 
17600 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
17601   // Looking for "rev" which is V6+.
17602   if (!Subtarget->hasV6Ops())
17603     return false;
17604 
17605   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
17606   std::string AsmStr = IA->getAsmString();
17607   SmallVector<StringRef, 4> AsmPieces;
17608   SplitString(AsmStr, AsmPieces, ";\n");
17609 
17610   switch (AsmPieces.size()) {
17611   default: return false;
17612   case 1:
17613     AsmStr = std::string(AsmPieces[0]);
17614     AsmPieces.clear();
17615     SplitString(AsmStr, AsmPieces, " \t,");
17616 
17617     // rev $0, $1
17618     if (AsmPieces.size() == 3 &&
17619         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
17620         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
17621       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17622       if (Ty && Ty->getBitWidth() == 32)
17623         return IntrinsicLowering::LowerToByteSwap(CI);
17624     }
17625     break;
17626   }
17627 
17628   return false;
17629 }
17630 
17631 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
17632   // At this point, we have to lower this constraint to something else, so we
17633   // lower it to an "r" or "w". However, by doing this we will force the result
17634   // to be in register, while the X constraint is much more permissive.
17635   //
17636   // Although we are correct (we are free to emit anything, without
17637   // constraints), we might break use cases that would expect us to be more
17638   // efficient and emit something else.
17639   if (!Subtarget->hasVFP2Base())
17640     return "r";
17641   if (ConstraintVT.isFloatingPoint())
17642     return "w";
17643   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
17644      (ConstraintVT.getSizeInBits() == 64 ||
17645       ConstraintVT.getSizeInBits() == 128))
17646     return "w";
17647 
17648   return "r";
17649 }
17650 
17651 /// getConstraintType - Given a constraint letter, return the type of
17652 /// constraint it is for this target.
17653 ARMTargetLowering::ConstraintType
17654 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
17655   unsigned S = Constraint.size();
17656   if (S == 1) {
17657     switch (Constraint[0]) {
17658     default:  break;
17659     case 'l': return C_RegisterClass;
17660     case 'w': return C_RegisterClass;
17661     case 'h': return C_RegisterClass;
17662     case 'x': return C_RegisterClass;
17663     case 't': return C_RegisterClass;
17664     case 'j': return C_Immediate; // Constant for movw.
17665     // An address with a single base register. Due to the way we
17666     // currently handle addresses it is the same as an 'r' memory constraint.
17667     case 'Q': return C_Memory;
17668     }
17669   } else if (S == 2) {
17670     switch (Constraint[0]) {
17671     default: break;
17672     case 'T': return C_RegisterClass;
17673     // All 'U+' constraints are addresses.
17674     case 'U': return C_Memory;
17675     }
17676   }
17677   return TargetLowering::getConstraintType(Constraint);
17678 }
17679 
17680 /// Examine constraint type and operand type and determine a weight value.
17681 /// This object must already have been set up with the operand type
17682 /// and the current alternative constraint selected.
17683 TargetLowering::ConstraintWeight
17684 ARMTargetLowering::getSingleConstraintMatchWeight(
17685     AsmOperandInfo &info, const char *constraint) const {
17686   ConstraintWeight weight = CW_Invalid;
17687   Value *CallOperandVal = info.CallOperandVal;
17688     // If we don't have a value, we can't do a match,
17689     // but allow it at the lowest weight.
17690   if (!CallOperandVal)
17691     return CW_Default;
17692   Type *type = CallOperandVal->getType();
17693   // Look at the constraint type.
17694   switch (*constraint) {
17695   default:
17696     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17697     break;
17698   case 'l':
17699     if (type->isIntegerTy()) {
17700       if (Subtarget->isThumb())
17701         weight = CW_SpecificReg;
17702       else
17703         weight = CW_Register;
17704     }
17705     break;
17706   case 'w':
17707     if (type->isFloatingPointTy())
17708       weight = CW_Register;
17709     break;
17710   }
17711   return weight;
17712 }
17713 
17714 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
17715 
17716 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
17717     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
17718   switch (Constraint.size()) {
17719   case 1:
17720     // GCC ARM Constraint Letters
17721     switch (Constraint[0]) {
17722     case 'l': // Low regs or general regs.
17723       if (Subtarget->isThumb())
17724         return RCPair(0U, &ARM::tGPRRegClass);
17725       return RCPair(0U, &ARM::GPRRegClass);
17726     case 'h': // High regs or no regs.
17727       if (Subtarget->isThumb())
17728         return RCPair(0U, &ARM::hGPRRegClass);
17729       break;
17730     case 'r':
17731       if (Subtarget->isThumb1Only())
17732         return RCPair(0U, &ARM::tGPRRegClass);
17733       return RCPair(0U, &ARM::GPRRegClass);
17734     case 'w':
17735       if (VT == MVT::Other)
17736         break;
17737       if (VT == MVT::f32)
17738         return RCPair(0U, &ARM::SPRRegClass);
17739       if (VT.getSizeInBits() == 64)
17740         return RCPair(0U, &ARM::DPRRegClass);
17741       if (VT.getSizeInBits() == 128)
17742         return RCPair(0U, &ARM::QPRRegClass);
17743       break;
17744     case 'x':
17745       if (VT == MVT::Other)
17746         break;
17747       if (VT == MVT::f32)
17748         return RCPair(0U, &ARM::SPR_8RegClass);
17749       if (VT.getSizeInBits() == 64)
17750         return RCPair(0U, &ARM::DPR_8RegClass);
17751       if (VT.getSizeInBits() == 128)
17752         return RCPair(0U, &ARM::QPR_8RegClass);
17753       break;
17754     case 't':
17755       if (VT == MVT::Other)
17756         break;
17757       if (VT == MVT::f32 || VT == MVT::i32)
17758         return RCPair(0U, &ARM::SPRRegClass);
17759       if (VT.getSizeInBits() == 64)
17760         return RCPair(0U, &ARM::DPR_VFP2RegClass);
17761       if (VT.getSizeInBits() == 128)
17762         return RCPair(0U, &ARM::QPR_VFP2RegClass);
17763       break;
17764     }
17765     break;
17766 
17767   case 2:
17768     if (Constraint[0] == 'T') {
17769       switch (Constraint[1]) {
17770       default:
17771         break;
17772       case 'e':
17773         return RCPair(0U, &ARM::tGPREvenRegClass);
17774       case 'o':
17775         return RCPair(0U, &ARM::tGPROddRegClass);
17776       }
17777     }
17778     break;
17779 
17780   default:
17781     break;
17782   }
17783 
17784   if (StringRef("{cc}").equals_lower(Constraint))
17785     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
17786 
17787   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
17788 }
17789 
17790 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17791 /// vector.  If it is invalid, don't add anything to Ops.
17792 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17793                                                      std::string &Constraint,
17794                                                      std::vector<SDValue>&Ops,
17795                                                      SelectionDAG &DAG) const {
17796   SDValue Result;
17797 
17798   // Currently only support length 1 constraints.
17799   if (Constraint.length() != 1) return;
17800 
17801   char ConstraintLetter = Constraint[0];
17802   switch (ConstraintLetter) {
17803   default: break;
17804   case 'j':
17805   case 'I': case 'J': case 'K': case 'L':
17806   case 'M': case 'N': case 'O':
17807     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
17808     if (!C)
17809       return;
17810 
17811     int64_t CVal64 = C->getSExtValue();
17812     int CVal = (int) CVal64;
17813     // None of these constraints allow values larger than 32 bits.  Check
17814     // that the value fits in an int.
17815     if (CVal != CVal64)
17816       return;
17817 
17818     switch (ConstraintLetter) {
17819       case 'j':
17820         // Constant suitable for movw, must be between 0 and
17821         // 65535.
17822         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
17823           if (CVal >= 0 && CVal <= 65535)
17824             break;
17825         return;
17826       case 'I':
17827         if (Subtarget->isThumb1Only()) {
17828           // This must be a constant between 0 and 255, for ADD
17829           // immediates.
17830           if (CVal >= 0 && CVal <= 255)
17831             break;
17832         } else if (Subtarget->isThumb2()) {
17833           // A constant that can be used as an immediate value in a
17834           // data-processing instruction.
17835           if (ARM_AM::getT2SOImmVal(CVal) != -1)
17836             break;
17837         } else {
17838           // A constant that can be used as an immediate value in a
17839           // data-processing instruction.
17840           if (ARM_AM::getSOImmVal(CVal) != -1)
17841             break;
17842         }
17843         return;
17844 
17845       case 'J':
17846         if (Subtarget->isThumb1Only()) {
17847           // This must be a constant between -255 and -1, for negated ADD
17848           // immediates. This can be used in GCC with an "n" modifier that
17849           // prints the negated value, for use with SUB instructions. It is
17850           // not useful otherwise but is implemented for compatibility.
17851           if (CVal >= -255 && CVal <= -1)
17852             break;
17853         } else {
17854           // This must be a constant between -4095 and 4095. It is not clear
17855           // what this constraint is intended for. Implemented for
17856           // compatibility with GCC.
17857           if (CVal >= -4095 && CVal <= 4095)
17858             break;
17859         }
17860         return;
17861 
17862       case 'K':
17863         if (Subtarget->isThumb1Only()) {
17864           // A 32-bit value where only one byte has a nonzero value. Exclude
17865           // zero to match GCC. This constraint is used by GCC internally for
17866           // constants that can be loaded with a move/shift combination.
17867           // It is not useful otherwise but is implemented for compatibility.
17868           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
17869             break;
17870         } else if (Subtarget->isThumb2()) {
17871           // A constant whose bitwise inverse can be used as an immediate
17872           // value in a data-processing instruction. This can be used in GCC
17873           // with a "B" modifier that prints the inverted value, for use with
17874           // BIC and MVN instructions. It is not useful otherwise but is
17875           // implemented for compatibility.
17876           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
17877             break;
17878         } else {
17879           // A constant whose bitwise inverse can be used as an immediate
17880           // value in a data-processing instruction. This can be used in GCC
17881           // with a "B" modifier that prints the inverted value, for use with
17882           // BIC and MVN instructions. It is not useful otherwise but is
17883           // implemented for compatibility.
17884           if (ARM_AM::getSOImmVal(~CVal) != -1)
17885             break;
17886         }
17887         return;
17888 
17889       case 'L':
17890         if (Subtarget->isThumb1Only()) {
17891           // This must be a constant between -7 and 7,
17892           // for 3-operand ADD/SUB immediate instructions.
17893           if (CVal >= -7 && CVal < 7)
17894             break;
17895         } else if (Subtarget->isThumb2()) {
17896           // A constant whose negation can be used as an immediate value in a
17897           // data-processing instruction. This can be used in GCC with an "n"
17898           // modifier that prints the negated value, for use with SUB
17899           // instructions. It is not useful otherwise but is implemented for
17900           // compatibility.
17901           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
17902             break;
17903         } else {
17904           // A constant whose negation can be used as an immediate value in a
17905           // data-processing instruction. This can be used in GCC with an "n"
17906           // modifier that prints the negated value, for use with SUB
17907           // instructions. It is not useful otherwise but is implemented for
17908           // compatibility.
17909           if (ARM_AM::getSOImmVal(-CVal) != -1)
17910             break;
17911         }
17912         return;
17913 
17914       case 'M':
17915         if (Subtarget->isThumb1Only()) {
17916           // This must be a multiple of 4 between 0 and 1020, for
17917           // ADD sp + immediate.
17918           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
17919             break;
17920         } else {
17921           // A power of two or a constant between 0 and 32.  This is used in
17922           // GCC for the shift amount on shifted register operands, but it is
17923           // useful in general for any shift amounts.
17924           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
17925             break;
17926         }
17927         return;
17928 
17929       case 'N':
17930         if (Subtarget->isThumb1Only()) {
17931           // This must be a constant between 0 and 31, for shift amounts.
17932           if (CVal >= 0 && CVal <= 31)
17933             break;
17934         }
17935         return;
17936 
17937       case 'O':
17938         if (Subtarget->isThumb1Only()) {
17939           // This must be a multiple of 4 between -508 and 508, for
17940           // ADD/SUB sp = sp + immediate.
17941           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
17942             break;
17943         }
17944         return;
17945     }
17946     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
17947     break;
17948   }
17949 
17950   if (Result.getNode()) {
17951     Ops.push_back(Result);
17952     return;
17953   }
17954   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17955 }
17956 
17957 static RTLIB::Libcall getDivRemLibcall(
17958     const SDNode *N, MVT::SimpleValueType SVT) {
17959   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17960           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
17961          "Unhandled Opcode in getDivRemLibcall");
17962   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17963                   N->getOpcode() == ISD::SREM;
17964   RTLIB::Libcall LC;
17965   switch (SVT) {
17966   default: llvm_unreachable("Unexpected request for libcall!");
17967   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
17968   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
17969   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
17970   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
17971   }
17972   return LC;
17973 }
17974 
17975 static TargetLowering::ArgListTy getDivRemArgList(
17976     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
17977   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17978           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
17979          "Unhandled Opcode in getDivRemArgList");
17980   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17981                   N->getOpcode() == ISD::SREM;
17982   TargetLowering::ArgListTy Args;
17983   TargetLowering::ArgListEntry Entry;
17984   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
17985     EVT ArgVT = N->getOperand(i).getValueType();
17986     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
17987     Entry.Node = N->getOperand(i);
17988     Entry.Ty = ArgTy;
17989     Entry.IsSExt = isSigned;
17990     Entry.IsZExt = !isSigned;
17991     Args.push_back(Entry);
17992   }
17993   if (Subtarget->isTargetWindows() && Args.size() >= 2)
17994     std::swap(Args[0], Args[1]);
17995   return Args;
17996 }
17997 
17998 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
17999   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
18000           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
18001           Subtarget->isTargetWindows()) &&
18002          "Register-based DivRem lowering only");
18003   unsigned Opcode = Op->getOpcode();
18004   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
18005          "Invalid opcode for Div/Rem lowering");
18006   bool isSigned = (Opcode == ISD::SDIVREM);
18007   EVT VT = Op->getValueType(0);
18008   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
18009   SDLoc dl(Op);
18010 
18011   // If the target has hardware divide, use divide + multiply + subtract:
18012   //     div = a / b
18013   //     rem = a - b * div
18014   //     return {div, rem}
18015   // This should be lowered into UDIV/SDIV + MLS later on.
18016   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
18017                                         : Subtarget->hasDivideInARMMode();
18018   if (hasDivide && Op->getValueType(0).isSimple() &&
18019       Op->getSimpleValueType(0) == MVT::i32) {
18020     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
18021     const SDValue Dividend = Op->getOperand(0);
18022     const SDValue Divisor = Op->getOperand(1);
18023     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
18024     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
18025     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
18026 
18027     SDValue Values[2] = {Div, Rem};
18028     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
18029   }
18030 
18031   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
18032                                        VT.getSimpleVT().SimpleTy);
18033   SDValue InChain = DAG.getEntryNode();
18034 
18035   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
18036                                                     DAG.getContext(),
18037                                                     Subtarget);
18038 
18039   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18040                                          getPointerTy(DAG.getDataLayout()));
18041 
18042   Type *RetTy = StructType::get(Ty, Ty);
18043 
18044   if (Subtarget->isTargetWindows())
18045     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
18046 
18047   TargetLowering::CallLoweringInfo CLI(DAG);
18048   CLI.setDebugLoc(dl).setChain(InChain)
18049     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
18050     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18051 
18052   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18053   return CallInfo.first;
18054 }
18055 
18056 // Lowers REM using divmod helpers
18057 // see RTABI section 4.2/4.3
18058 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
18059   // Build return types (div and rem)
18060   std::vector<Type*> RetTyParams;
18061   Type *RetTyElement;
18062 
18063   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
18064   default: llvm_unreachable("Unexpected request for libcall!");
18065   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
18066   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
18067   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
18068   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
18069   }
18070 
18071   RetTyParams.push_back(RetTyElement);
18072   RetTyParams.push_back(RetTyElement);
18073   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
18074   Type *RetTy = StructType::get(*DAG.getContext(), ret);
18075 
18076   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
18077                                                              SimpleTy);
18078   SDValue InChain = DAG.getEntryNode();
18079   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
18080                                                     Subtarget);
18081   bool isSigned = N->getOpcode() == ISD::SREM;
18082   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18083                                          getPointerTy(DAG.getDataLayout()));
18084 
18085   if (Subtarget->isTargetWindows())
18086     InChain = WinDBZCheckDenominator(DAG, N, InChain);
18087 
18088   // Lower call
18089   CallLoweringInfo CLI(DAG);
18090   CLI.setChain(InChain)
18091      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
18092      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
18093   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
18094 
18095   // Return second (rem) result operand (first contains div)
18096   SDNode *ResNode = CallResult.first.getNode();
18097   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
18098   return ResNode->getOperand(1);
18099 }
18100 
18101 SDValue
18102 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
18103   assert(Subtarget->isTargetWindows() && "unsupported target platform");
18104   SDLoc DL(Op);
18105 
18106   // Get the inputs.
18107   SDValue Chain = Op.getOperand(0);
18108   SDValue Size  = Op.getOperand(1);
18109 
18110   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
18111           "no-stack-arg-probe")) {
18112     MaybeAlign Align =
18113         cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
18114     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
18115     Chain = SP.getValue(1);
18116     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
18117     if (Align)
18118       SP =
18119           DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
18120                       DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
18121     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
18122     SDValue Ops[2] = { SP, Chain };
18123     return DAG.getMergeValues(Ops, DL);
18124   }
18125 
18126   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
18127                               DAG.getConstant(2, DL, MVT::i32));
18128 
18129   SDValue Flag;
18130   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
18131   Flag = Chain.getValue(1);
18132 
18133   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18134   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
18135 
18136   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
18137   Chain = NewSP.getValue(1);
18138 
18139   SDValue Ops[2] = { NewSP, Chain };
18140   return DAG.getMergeValues(Ops, DL);
18141 }
18142 
18143 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
18144   bool IsStrict = Op->isStrictFPOpcode();
18145   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
18146   const unsigned DstSz = Op.getValueType().getSizeInBits();
18147   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
18148   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
18149          "Unexpected type for custom-lowering FP_EXTEND");
18150 
18151   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18152          "With both FP DP and 16, any FP conversion is legal!");
18153 
18154   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
18155          "With FP16, 16 to 32 conversion is legal!");
18156 
18157   // Converting from 32 -> 64 is valid if we have FP64.
18158   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
18159     // FIXME: Remove this when we have strict fp instruction selection patterns
18160     if (IsStrict) {
18161       SDLoc Loc(Op);
18162       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
18163                                    Loc, Op.getValueType(), SrcVal);
18164       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
18165     }
18166     return Op;
18167   }
18168 
18169   // Either we are converting from 16 -> 64, without FP16 and/or
18170   // FP.double-precision or without Armv8-fp. So we must do it in two
18171   // steps.
18172   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
18173   // without FP16. So we must do a function call.
18174   SDLoc Loc(Op);
18175   RTLIB::Libcall LC;
18176   MakeLibCallOptions CallOptions;
18177   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18178   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
18179     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
18180     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
18181     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
18182     if (Supported) {
18183       if (IsStrict) {
18184         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
18185                              {DstVT, MVT::Other}, {Chain, SrcVal});
18186         Chain = SrcVal.getValue(1);
18187       } else {
18188         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
18189       }
18190     } else {
18191       LC = RTLIB::getFPEXT(SrcVT, DstVT);
18192       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18193              "Unexpected type for custom-lowering FP_EXTEND");
18194       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18195                                             Loc, Chain);
18196     }
18197   }
18198 
18199   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
18200 }
18201 
18202 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
18203   bool IsStrict = Op->isStrictFPOpcode();
18204 
18205   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
18206   EVT SrcVT = SrcVal.getValueType();
18207   EVT DstVT = Op.getValueType();
18208   const unsigned DstSz = Op.getValueType().getSizeInBits();
18209   const unsigned SrcSz = SrcVT.getSizeInBits();
18210   (void)DstSz;
18211   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
18212          "Unexpected type for custom-lowering FP_ROUND");
18213 
18214   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18215          "With both FP DP and 16, any FP conversion is legal!");
18216 
18217   SDLoc Loc(Op);
18218 
18219   // Instruction from 32 -> 16 if hasFP16 is valid
18220   if (SrcSz == 32 && Subtarget->hasFP16())
18221     return Op;
18222 
18223   // Lib call from 32 -> 16 / 64 -> [32, 16]
18224   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
18225   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18226          "Unexpected type for custom-lowering FP_ROUND");
18227   MakeLibCallOptions CallOptions;
18228   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18229   SDValue Result;
18230   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18231                                         Loc, Chain);
18232   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
18233 }
18234 
18235 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
18236                                  SelectionDAG &DAG) const {
18237   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
18238   MVT HalfT = MVT::i32;
18239   SDLoc dl(N);
18240   SDValue Hi, Lo, Tmp;
18241 
18242   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
18243       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
18244     return ;
18245 
18246   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
18247   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
18248 
18249   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18250                    DAG.getConstant(0, dl, HalfT));
18251   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18252                    DAG.getConstant(1, dl, HalfT));
18253 
18254   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
18255                     DAG.getConstant(OpTypeBits - 1, dl,
18256                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
18257   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
18258   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
18259                    SDValue(Lo.getNode(), 1));
18260   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
18261   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
18262 
18263   Results.push_back(Lo);
18264   Results.push_back(Hi);
18265 }
18266 
18267 bool
18268 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
18269   // The ARM target isn't yet aware of offsets.
18270   return false;
18271 }
18272 
18273 bool ARM::isBitFieldInvertedMask(unsigned v) {
18274   if (v == 0xffffffff)
18275     return false;
18276 
18277   // there can be 1's on either or both "outsides", all the "inside"
18278   // bits must be 0's
18279   return isShiftedMask_32(~v);
18280 }
18281 
18282 /// isFPImmLegal - Returns true if the target can instruction select the
18283 /// specified FP immediate natively. If false, the legalizer will
18284 /// materialize the FP immediate as a load from a constant pool.
18285 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
18286                                      bool ForCodeSize) const {
18287   if (!Subtarget->hasVFP3Base())
18288     return false;
18289   if (VT == MVT::f16 && Subtarget->hasFullFP16())
18290     return ARM_AM::getFP16Imm(Imm) != -1;
18291   if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
18292       ARM_AM::getFP32FP16Imm(Imm) != -1)
18293     return true;
18294   if (VT == MVT::f32)
18295     return ARM_AM::getFP32Imm(Imm) != -1;
18296   if (VT == MVT::f64 && Subtarget->hasFP64())
18297     return ARM_AM::getFP64Imm(Imm) != -1;
18298   return false;
18299 }
18300 
18301 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
18302 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
18303 /// specified in the intrinsic calls.
18304 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
18305                                            const CallInst &I,
18306                                            MachineFunction &MF,
18307                                            unsigned Intrinsic) const {
18308   switch (Intrinsic) {
18309   case Intrinsic::arm_neon_vld1:
18310   case Intrinsic::arm_neon_vld2:
18311   case Intrinsic::arm_neon_vld3:
18312   case Intrinsic::arm_neon_vld4:
18313   case Intrinsic::arm_neon_vld2lane:
18314   case Intrinsic::arm_neon_vld3lane:
18315   case Intrinsic::arm_neon_vld4lane:
18316   case Intrinsic::arm_neon_vld2dup:
18317   case Intrinsic::arm_neon_vld3dup:
18318   case Intrinsic::arm_neon_vld4dup: {
18319     Info.opc = ISD::INTRINSIC_W_CHAIN;
18320     // Conservatively set memVT to the entire set of vectors loaded.
18321     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18322     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18323     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18324     Info.ptrVal = I.getArgOperand(0);
18325     Info.offset = 0;
18326     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18327     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18328     // volatile loads with NEON intrinsics not supported
18329     Info.flags = MachineMemOperand::MOLoad;
18330     return true;
18331   }
18332   case Intrinsic::arm_neon_vld1x2:
18333   case Intrinsic::arm_neon_vld1x3:
18334   case Intrinsic::arm_neon_vld1x4: {
18335     Info.opc = ISD::INTRINSIC_W_CHAIN;
18336     // Conservatively set memVT to the entire set of vectors loaded.
18337     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18338     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18339     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18340     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
18341     Info.offset = 0;
18342     Info.align.reset();
18343     // volatile loads with NEON intrinsics not supported
18344     Info.flags = MachineMemOperand::MOLoad;
18345     return true;
18346   }
18347   case Intrinsic::arm_neon_vst1:
18348   case Intrinsic::arm_neon_vst2:
18349   case Intrinsic::arm_neon_vst3:
18350   case Intrinsic::arm_neon_vst4:
18351   case Intrinsic::arm_neon_vst2lane:
18352   case Intrinsic::arm_neon_vst3lane:
18353   case Intrinsic::arm_neon_vst4lane: {
18354     Info.opc = ISD::INTRINSIC_VOID;
18355     // Conservatively set memVT to the entire set of vectors stored.
18356     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18357     unsigned NumElts = 0;
18358     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18359       Type *ArgTy = I.getArgOperand(ArgI)->getType();
18360       if (!ArgTy->isVectorTy())
18361         break;
18362       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18363     }
18364     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18365     Info.ptrVal = I.getArgOperand(0);
18366     Info.offset = 0;
18367     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18368     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18369     // volatile stores with NEON intrinsics not supported
18370     Info.flags = MachineMemOperand::MOStore;
18371     return true;
18372   }
18373   case Intrinsic::arm_neon_vst1x2:
18374   case Intrinsic::arm_neon_vst1x3:
18375   case Intrinsic::arm_neon_vst1x4: {
18376     Info.opc = ISD::INTRINSIC_VOID;
18377     // Conservatively set memVT to the entire set of vectors stored.
18378     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18379     unsigned NumElts = 0;
18380     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18381       Type *ArgTy = I.getArgOperand(ArgI)->getType();
18382       if (!ArgTy->isVectorTy())
18383         break;
18384       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18385     }
18386     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18387     Info.ptrVal = I.getArgOperand(0);
18388     Info.offset = 0;
18389     Info.align.reset();
18390     // volatile stores with NEON intrinsics not supported
18391     Info.flags = MachineMemOperand::MOStore;
18392     return true;
18393   }
18394   case Intrinsic::arm_mve_vld2q:
18395   case Intrinsic::arm_mve_vld4q: {
18396     Info.opc = ISD::INTRINSIC_W_CHAIN;
18397     // Conservatively set memVT to the entire set of vectors loaded.
18398     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
18399     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
18400     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18401     Info.ptrVal = I.getArgOperand(0);
18402     Info.offset = 0;
18403     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18404     // volatile loads with MVE intrinsics not supported
18405     Info.flags = MachineMemOperand::MOLoad;
18406     return true;
18407   }
18408   case Intrinsic::arm_mve_vst2q:
18409   case Intrinsic::arm_mve_vst4q: {
18410     Info.opc = ISD::INTRINSIC_VOID;
18411     // Conservatively set memVT to the entire set of vectors stored.
18412     Type *VecTy = I.getArgOperand(1)->getType();
18413     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
18414     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18415     Info.ptrVal = I.getArgOperand(0);
18416     Info.offset = 0;
18417     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18418     // volatile stores with MVE intrinsics not supported
18419     Info.flags = MachineMemOperand::MOStore;
18420     return true;
18421   }
18422   case Intrinsic::arm_ldaex:
18423   case Intrinsic::arm_ldrex: {
18424     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18425     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
18426     Info.opc = ISD::INTRINSIC_W_CHAIN;
18427     Info.memVT = MVT::getVT(PtrTy->getElementType());
18428     Info.ptrVal = I.getArgOperand(0);
18429     Info.offset = 0;
18430     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18431     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18432     return true;
18433   }
18434   case Intrinsic::arm_stlex:
18435   case Intrinsic::arm_strex: {
18436     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18437     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
18438     Info.opc = ISD::INTRINSIC_W_CHAIN;
18439     Info.memVT = MVT::getVT(PtrTy->getElementType());
18440     Info.ptrVal = I.getArgOperand(1);
18441     Info.offset = 0;
18442     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18443     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18444     return true;
18445   }
18446   case Intrinsic::arm_stlexd:
18447   case Intrinsic::arm_strexd:
18448     Info.opc = ISD::INTRINSIC_W_CHAIN;
18449     Info.memVT = MVT::i64;
18450     Info.ptrVal = I.getArgOperand(2);
18451     Info.offset = 0;
18452     Info.align = Align(8);
18453     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18454     return true;
18455 
18456   case Intrinsic::arm_ldaexd:
18457   case Intrinsic::arm_ldrexd:
18458     Info.opc = ISD::INTRINSIC_W_CHAIN;
18459     Info.memVT = MVT::i64;
18460     Info.ptrVal = I.getArgOperand(0);
18461     Info.offset = 0;
18462     Info.align = Align(8);
18463     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18464     return true;
18465 
18466   default:
18467     break;
18468   }
18469 
18470   return false;
18471 }
18472 
18473 /// Returns true if it is beneficial to convert a load of a constant
18474 /// to just the constant itself.
18475 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
18476                                                           Type *Ty) const {
18477   assert(Ty->isIntegerTy());
18478 
18479   unsigned Bits = Ty->getPrimitiveSizeInBits();
18480   if (Bits == 0 || Bits > 32)
18481     return false;
18482   return true;
18483 }
18484 
18485 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
18486                                                 unsigned Index) const {
18487   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
18488     return false;
18489 
18490   return (Index == 0 || Index == ResVT.getVectorNumElements());
18491 }
18492 
18493 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
18494                                         ARM_MB::MemBOpt Domain) const {
18495   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18496 
18497   // First, if the target has no DMB, see what fallback we can use.
18498   if (!Subtarget->hasDataBarrier()) {
18499     // Some ARMv6 cpus can support data barriers with an mcr instruction.
18500     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
18501     // here.
18502     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
18503       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
18504       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
18505                         Builder.getInt32(0), Builder.getInt32(7),
18506                         Builder.getInt32(10), Builder.getInt32(5)};
18507       return Builder.CreateCall(MCR, args);
18508     } else {
18509       // Instead of using barriers, atomic accesses on these subtargets use
18510       // libcalls.
18511       llvm_unreachable("makeDMB on a target so old that it has no barriers");
18512     }
18513   } else {
18514     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
18515     // Only a full system barrier exists in the M-class architectures.
18516     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
18517     Constant *CDomain = Builder.getInt32(Domain);
18518     return Builder.CreateCall(DMB, CDomain);
18519   }
18520 }
18521 
18522 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
18523 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
18524                                                  Instruction *Inst,
18525                                                  AtomicOrdering Ord) const {
18526   switch (Ord) {
18527   case AtomicOrdering::NotAtomic:
18528   case AtomicOrdering::Unordered:
18529     llvm_unreachable("Invalid fence: unordered/non-atomic");
18530   case AtomicOrdering::Monotonic:
18531   case AtomicOrdering::Acquire:
18532     return nullptr; // Nothing to do
18533   case AtomicOrdering::SequentiallyConsistent:
18534     if (!Inst->hasAtomicStore())
18535       return nullptr; // Nothing to do
18536     LLVM_FALLTHROUGH;
18537   case AtomicOrdering::Release:
18538   case AtomicOrdering::AcquireRelease:
18539     if (Subtarget->preferISHSTBarriers())
18540       return makeDMB(Builder, ARM_MB::ISHST);
18541     // FIXME: add a comment with a link to documentation justifying this.
18542     else
18543       return makeDMB(Builder, ARM_MB::ISH);
18544   }
18545   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
18546 }
18547 
18548 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
18549                                                   Instruction *Inst,
18550                                                   AtomicOrdering Ord) const {
18551   switch (Ord) {
18552   case AtomicOrdering::NotAtomic:
18553   case AtomicOrdering::Unordered:
18554     llvm_unreachable("Invalid fence: unordered/not-atomic");
18555   case AtomicOrdering::Monotonic:
18556   case AtomicOrdering::Release:
18557     return nullptr; // Nothing to do
18558   case AtomicOrdering::Acquire:
18559   case AtomicOrdering::AcquireRelease:
18560   case AtomicOrdering::SequentiallyConsistent:
18561     return makeDMB(Builder, ARM_MB::ISH);
18562   }
18563   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
18564 }
18565 
18566 // Loads and stores less than 64-bits are already atomic; ones above that
18567 // are doomed anyway, so defer to the default libcall and blame the OS when
18568 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18569 // anything for those.
18570 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18571   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
18572   return (Size == 64) && !Subtarget->isMClass();
18573 }
18574 
18575 // Loads and stores less than 64-bits are already atomic; ones above that
18576 // are doomed anyway, so defer to the default libcall and blame the OS when
18577 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18578 // anything for those.
18579 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
18580 // guarantee, see DDI0406C ARM architecture reference manual,
18581 // sections A8.8.72-74 LDRD)
18582 TargetLowering::AtomicExpansionKind
18583 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18584   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
18585   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
18586                                                   : AtomicExpansionKind::None;
18587 }
18588 
18589 // For the real atomic operations, we have ldrex/strex up to 32 bits,
18590 // and up to 64 bits on the non-M profiles
18591 TargetLowering::AtomicExpansionKind
18592 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18593   if (AI->isFloatingPointOperation())
18594     return AtomicExpansionKind::CmpXChg;
18595 
18596   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18597   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18598   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
18599              ? AtomicExpansionKind::LLSC
18600              : AtomicExpansionKind::None;
18601 }
18602 
18603 TargetLowering::AtomicExpansionKind
18604 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18605   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18606   // implement cmpxchg without spilling. If the address being exchanged is also
18607   // on the stack and close enough to the spill slot, this can lead to a
18608   // situation where the monitor always gets cleared and the atomic operation
18609   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
18610   bool HasAtomicCmpXchg =
18611       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18612   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
18613     return AtomicExpansionKind::LLSC;
18614   return AtomicExpansionKind::None;
18615 }
18616 
18617 bool ARMTargetLowering::shouldInsertFencesForAtomic(
18618     const Instruction *I) const {
18619   return InsertFencesForAtomic;
18620 }
18621 
18622 // This has so far only been implemented for MachO.
18623 bool ARMTargetLowering::useLoadStackGuardNode() const {
18624   return Subtarget->isTargetMachO();
18625 }
18626 
18627 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
18628   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18629     return TargetLowering::insertSSPDeclarations(M);
18630 
18631   // MSVC CRT has a global variable holding security cookie.
18632   M.getOrInsertGlobal("__security_cookie",
18633                       Type::getInt8PtrTy(M.getContext()));
18634 
18635   // MSVC CRT has a function to validate security cookie.
18636   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
18637       "__security_check_cookie", Type::getVoidTy(M.getContext()),
18638       Type::getInt8PtrTy(M.getContext()));
18639   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
18640     F->addAttribute(1, Attribute::AttrKind::InReg);
18641 }
18642 
18643 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
18644   // MSVC CRT has a global variable holding security cookie.
18645   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18646     return M.getGlobalVariable("__security_cookie");
18647   return TargetLowering::getSDagStackGuard(M);
18648 }
18649 
18650 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
18651   // MSVC CRT has a function to validate security cookie.
18652   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18653     return M.getFunction("__security_check_cookie");
18654   return TargetLowering::getSSPStackGuardCheck(M);
18655 }
18656 
18657 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
18658                                                   unsigned &Cost) const {
18659   // If we do not have NEON, vector types are not natively supported.
18660   if (!Subtarget->hasNEON())
18661     return false;
18662 
18663   // Floating point values and vector values map to the same register file.
18664   // Therefore, although we could do a store extract of a vector type, this is
18665   // better to leave at float as we have more freedom in the addressing mode for
18666   // those.
18667   if (VectorTy->isFPOrFPVectorTy())
18668     return false;
18669 
18670   // If the index is unknown at compile time, this is very expensive to lower
18671   // and it is not possible to combine the store with the extract.
18672   if (!isa<ConstantInt>(Idx))
18673     return false;
18674 
18675   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
18676   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
18677   // We can do a store + vector extract on any vector that fits perfectly in a D
18678   // or Q register.
18679   if (BitWidth == 64 || BitWidth == 128) {
18680     Cost = 0;
18681     return true;
18682   }
18683   return false;
18684 }
18685 
18686 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
18687   return Subtarget->hasV6T2Ops();
18688 }
18689 
18690 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
18691   return Subtarget->hasV6T2Ops();
18692 }
18693 
18694 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
18695   return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
18696 }
18697 
18698 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
18699                                          AtomicOrdering Ord) const {
18700   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18701   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
18702   bool IsAcquire = isAcquireOrStronger(Ord);
18703 
18704   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
18705   // intrinsic must return {i32, i32} and we have to recombine them into a
18706   // single i64 here.
18707   if (ValTy->getPrimitiveSizeInBits() == 64) {
18708     Intrinsic::ID Int =
18709         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
18710     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
18711 
18712     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18713     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
18714 
18715     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18716     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18717     if (!Subtarget->isLittle())
18718       std::swap (Lo, Hi);
18719     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18720     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18721     return Builder.CreateOr(
18722         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
18723   }
18724 
18725   Type *Tys[] = { Addr->getType() };
18726   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
18727   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
18728 
18729   return Builder.CreateTruncOrBitCast(
18730       Builder.CreateCall(Ldrex, Addr),
18731       cast<PointerType>(Addr->getType())->getElementType());
18732 }
18733 
18734 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
18735     IRBuilder<> &Builder) const {
18736   if (!Subtarget->hasV7Ops())
18737     return;
18738   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18739   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
18740 }
18741 
18742 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
18743                                                Value *Addr,
18744                                                AtomicOrdering Ord) const {
18745   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18746   bool IsRelease = isReleaseOrStronger(Ord);
18747 
18748   // Since the intrinsics must have legal type, the i64 intrinsics take two
18749   // parameters: "i32, i32". We must marshal Val into the appropriate form
18750   // before the call.
18751   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
18752     Intrinsic::ID Int =
18753         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
18754     Function *Strex = Intrinsic::getDeclaration(M, Int);
18755     Type *Int32Ty = Type::getInt32Ty(M->getContext());
18756 
18757     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
18758     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
18759     if (!Subtarget->isLittle())
18760       std::swap(Lo, Hi);
18761     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18762     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
18763   }
18764 
18765   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
18766   Type *Tys[] = { Addr->getType() };
18767   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
18768 
18769   return Builder.CreateCall(
18770       Strex, {Builder.CreateZExtOrBitCast(
18771                   Val, Strex->getFunctionType()->getParamType(0)),
18772               Addr});
18773 }
18774 
18775 
18776 bool ARMTargetLowering::alignLoopsWithOptSize() const {
18777   return Subtarget->isMClass();
18778 }
18779 
18780 /// A helper function for determining the number of interleaved accesses we
18781 /// will generate when lowering accesses of the given type.
18782 unsigned
18783 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
18784                                              const DataLayout &DL) const {
18785   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
18786 }
18787 
18788 bool ARMTargetLowering::isLegalInterleavedAccessType(
18789     unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const {
18790 
18791   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
18792   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
18793 
18794   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
18795     return false;
18796 
18797   // Ensure the vector doesn't have f16 elements. Even though we could do an
18798   // i16 vldN, we can't hold the f16 vectors and will end up converting via
18799   // f32.
18800   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
18801     return false;
18802   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
18803     return false;
18804 
18805   // Ensure the number of vector elements is greater than 1.
18806   if (VecTy->getNumElements() < 2)
18807     return false;
18808 
18809   // Ensure the element type is legal.
18810   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
18811     return false;
18812 
18813   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
18814   // 128 will be split into multiple interleaved accesses.
18815   if (Subtarget->hasNEON() && VecSize == 64)
18816     return true;
18817   return VecSize % 128 == 0;
18818 }
18819 
18820 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
18821   if (Subtarget->hasNEON())
18822     return 4;
18823   if (Subtarget->hasMVEIntegerOps())
18824     return MVEMaxSupportedInterleaveFactor;
18825   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
18826 }
18827 
18828 /// Lower an interleaved load into a vldN intrinsic.
18829 ///
18830 /// E.g. Lower an interleaved load (Factor = 2):
18831 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
18832 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
18833 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
18834 ///
18835 ///      Into:
18836 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
18837 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
18838 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
18839 bool ARMTargetLowering::lowerInterleavedLoad(
18840     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
18841     ArrayRef<unsigned> Indices, unsigned Factor) const {
18842   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18843          "Invalid interleave factor");
18844   assert(!Shuffles.empty() && "Empty shufflevector input");
18845   assert(Shuffles.size() == Indices.size() &&
18846          "Unmatched number of shufflevectors and indices");
18847 
18848   auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
18849   Type *EltTy = VecTy->getElementType();
18850 
18851   const DataLayout &DL = LI->getModule()->getDataLayout();
18852 
18853   // Skip if we do not have NEON and skip illegal vector types. We can
18854   // "legalize" wide vector types into multiple interleaved accesses as long as
18855   // the vector types are divisible by 128.
18856   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
18857     return false;
18858 
18859   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
18860 
18861   // A pointer vector can not be the return type of the ldN intrinsics. Need to
18862   // load integer vectors first and then convert to pointer vectors.
18863   if (EltTy->isPointerTy())
18864     VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
18865 
18866   IRBuilder<> Builder(LI);
18867 
18868   // The base address of the load.
18869   Value *BaseAddr = LI->getPointerOperand();
18870 
18871   if (NumLoads > 1) {
18872     // If we're going to generate more than one load, reset the sub-vector type
18873     // to something legal.
18874     VecTy = FixedVectorType::get(VecTy->getElementType(),
18875                                  VecTy->getNumElements() / NumLoads);
18876 
18877     // We will compute the pointer operand of each load from the original base
18878     // address using GEPs. Cast the base address to a pointer to the scalar
18879     // element type.
18880     BaseAddr = Builder.CreateBitCast(
18881         BaseAddr,
18882         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
18883   }
18884 
18885   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
18886 
18887   auto createLoadIntrinsic = [&](Value *BaseAddr) {
18888     if (Subtarget->hasNEON()) {
18889       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
18890       Type *Tys[] = {VecTy, Int8Ptr};
18891       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
18892                                                 Intrinsic::arm_neon_vld3,
18893                                                 Intrinsic::arm_neon_vld4};
18894       Function *VldnFunc =
18895           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
18896 
18897       SmallVector<Value *, 2> Ops;
18898       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18899       Ops.push_back(Builder.getInt32(LI->getAlignment()));
18900 
18901       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18902     } else {
18903       assert((Factor == 2 || Factor == 4) &&
18904              "expected interleave factor of 2 or 4 for MVE");
18905       Intrinsic::ID LoadInts =
18906           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
18907       Type *VecEltTy =
18908           VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
18909       Type *Tys[] = {VecTy, VecEltTy};
18910       Function *VldnFunc =
18911           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
18912 
18913       SmallVector<Value *, 2> Ops;
18914       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
18915       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18916     }
18917   };
18918 
18919   // Holds sub-vectors extracted from the load intrinsic return values. The
18920   // sub-vectors are associated with the shufflevector instructions they will
18921   // replace.
18922   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
18923 
18924   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
18925     // If we're generating more than one load, compute the base address of
18926     // subsequent loads as an offset from the previous.
18927     if (LoadCount > 0)
18928       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
18929                                             VecTy->getNumElements() * Factor);
18930 
18931     CallInst *VldN = createLoadIntrinsic(BaseAddr);
18932 
18933     // Replace uses of each shufflevector with the corresponding vector loaded
18934     // by ldN.
18935     for (unsigned i = 0; i < Shuffles.size(); i++) {
18936       ShuffleVectorInst *SV = Shuffles[i];
18937       unsigned Index = Indices[i];
18938 
18939       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
18940 
18941       // Convert the integer vector to pointer vector if the element is pointer.
18942       if (EltTy->isPointerTy())
18943         SubVec = Builder.CreateIntToPtr(
18944             SubVec,
18945             FixedVectorType::get(SV->getType()->getElementType(), VecTy));
18946 
18947       SubVecs[SV].push_back(SubVec);
18948     }
18949   }
18950 
18951   // Replace uses of the shufflevector instructions with the sub-vectors
18952   // returned by the load intrinsic. If a shufflevector instruction is
18953   // associated with more than one sub-vector, those sub-vectors will be
18954   // concatenated into a single wide vector.
18955   for (ShuffleVectorInst *SVI : Shuffles) {
18956     auto &SubVec = SubVecs[SVI];
18957     auto *WideVec =
18958         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
18959     SVI->replaceAllUsesWith(WideVec);
18960   }
18961 
18962   return true;
18963 }
18964 
18965 /// Lower an interleaved store into a vstN intrinsic.
18966 ///
18967 /// E.g. Lower an interleaved store (Factor = 3):
18968 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
18969 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
18970 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
18971 ///
18972 ///      Into:
18973 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
18974 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
18975 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
18976 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
18977 ///
18978 /// Note that the new shufflevectors will be removed and we'll only generate one
18979 /// vst3 instruction in CodeGen.
18980 ///
18981 /// Example for a more general valid mask (Factor 3). Lower:
18982 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
18983 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
18984 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
18985 ///
18986 ///      Into:
18987 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
18988 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
18989 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
18990 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
18991 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
18992                                               ShuffleVectorInst *SVI,
18993                                               unsigned Factor) const {
18994   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18995          "Invalid interleave factor");
18996 
18997   auto *VecTy = cast<FixedVectorType>(SVI->getType());
18998   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
18999 
19000   unsigned LaneLen = VecTy->getNumElements() / Factor;
19001   Type *EltTy = VecTy->getElementType();
19002   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
19003 
19004   const DataLayout &DL = SI->getModule()->getDataLayout();
19005 
19006   // Skip if we do not have NEON and skip illegal vector types. We can
19007   // "legalize" wide vector types into multiple interleaved accesses as long as
19008   // the vector types are divisible by 128.
19009   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
19010     return false;
19011 
19012   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
19013 
19014   Value *Op0 = SVI->getOperand(0);
19015   Value *Op1 = SVI->getOperand(1);
19016   IRBuilder<> Builder(SI);
19017 
19018   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
19019   // vectors to integer vectors.
19020   if (EltTy->isPointerTy()) {
19021     Type *IntTy = DL.getIntPtrType(EltTy);
19022 
19023     // Convert to the corresponding integer vector.
19024     auto *IntVecTy =
19025         FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
19026     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
19027     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
19028 
19029     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
19030   }
19031 
19032   // The base address of the store.
19033   Value *BaseAddr = SI->getPointerOperand();
19034 
19035   if (NumStores > 1) {
19036     // If we're going to generate more than one store, reset the lane length
19037     // and sub-vector type to something legal.
19038     LaneLen /= NumStores;
19039     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
19040 
19041     // We will compute the pointer operand of each store from the original base
19042     // address using GEPs. Cast the base address to a pointer to the scalar
19043     // element type.
19044     BaseAddr = Builder.CreateBitCast(
19045         BaseAddr,
19046         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
19047   }
19048 
19049   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
19050 
19051   auto Mask = SVI->getShuffleMask();
19052 
19053   auto createStoreIntrinsic = [&](Value *BaseAddr,
19054                                   SmallVectorImpl<Value *> &Shuffles) {
19055     if (Subtarget->hasNEON()) {
19056       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
19057                                                  Intrinsic::arm_neon_vst3,
19058                                                  Intrinsic::arm_neon_vst4};
19059       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
19060       Type *Tys[] = {Int8Ptr, SubVecTy};
19061 
19062       Function *VstNFunc = Intrinsic::getDeclaration(
19063           SI->getModule(), StoreInts[Factor - 2], Tys);
19064 
19065       SmallVector<Value *, 6> Ops;
19066       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
19067       for (auto S : Shuffles)
19068         Ops.push_back(S);
19069       Ops.push_back(Builder.getInt32(SI->getAlignment()));
19070       Builder.CreateCall(VstNFunc, Ops);
19071     } else {
19072       assert((Factor == 2 || Factor == 4) &&
19073              "expected interleave factor of 2 or 4 for MVE");
19074       Intrinsic::ID StoreInts =
19075           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
19076       Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
19077           SI->getPointerAddressSpace());
19078       Type *Tys[] = {EltPtrTy, SubVecTy};
19079       Function *VstNFunc =
19080           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
19081 
19082       SmallVector<Value *, 6> Ops;
19083       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
19084       for (auto S : Shuffles)
19085         Ops.push_back(S);
19086       for (unsigned F = 0; F < Factor; F++) {
19087         Ops.push_back(Builder.getInt32(F));
19088         Builder.CreateCall(VstNFunc, Ops);
19089         Ops.pop_back();
19090       }
19091     }
19092   };
19093 
19094   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
19095     // If we generating more than one store, we compute the base address of
19096     // subsequent stores as an offset from the previous.
19097     if (StoreCount > 0)
19098       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
19099                                             BaseAddr, LaneLen * Factor);
19100 
19101     SmallVector<Value *, 4> Shuffles;
19102 
19103     // Split the shufflevector operands into sub vectors for the new vstN call.
19104     for (unsigned i = 0; i < Factor; i++) {
19105       unsigned IdxI = StoreCount * LaneLen * Factor + i;
19106       if (Mask[IdxI] >= 0) {
19107         Shuffles.push_back(Builder.CreateShuffleVector(
19108             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
19109       } else {
19110         unsigned StartMask = 0;
19111         for (unsigned j = 1; j < LaneLen; j++) {
19112           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
19113           if (Mask[IdxJ * Factor + IdxI] >= 0) {
19114             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
19115             break;
19116           }
19117         }
19118         // Note: If all elements in a chunk are undefs, StartMask=0!
19119         // Note: Filling undef gaps with random elements is ok, since
19120         // those elements were being written anyway (with undefs).
19121         // In the case of all undefs we're defaulting to using elems from 0
19122         // Note: StartMask cannot be negative, it's checked in
19123         // isReInterleaveMask
19124         Shuffles.push_back(Builder.CreateShuffleVector(
19125             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
19126       }
19127     }
19128 
19129     createStoreIntrinsic(BaseAddr, Shuffles);
19130   }
19131   return true;
19132 }
19133 
19134 enum HABaseType {
19135   HA_UNKNOWN = 0,
19136   HA_FLOAT,
19137   HA_DOUBLE,
19138   HA_VECT64,
19139   HA_VECT128
19140 };
19141 
19142 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
19143                                    uint64_t &Members) {
19144   if (auto *ST = dyn_cast<StructType>(Ty)) {
19145     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
19146       uint64_t SubMembers = 0;
19147       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
19148         return false;
19149       Members += SubMembers;
19150     }
19151   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
19152     uint64_t SubMembers = 0;
19153     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
19154       return false;
19155     Members += SubMembers * AT->getNumElements();
19156   } else if (Ty->isFloatTy()) {
19157     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
19158       return false;
19159     Members = 1;
19160     Base = HA_FLOAT;
19161   } else if (Ty->isDoubleTy()) {
19162     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
19163       return false;
19164     Members = 1;
19165     Base = HA_DOUBLE;
19166   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
19167     Members = 1;
19168     switch (Base) {
19169     case HA_FLOAT:
19170     case HA_DOUBLE:
19171       return false;
19172     case HA_VECT64:
19173       return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
19174     case HA_VECT128:
19175       return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
19176     case HA_UNKNOWN:
19177       switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
19178       case 64:
19179         Base = HA_VECT64;
19180         return true;
19181       case 128:
19182         Base = HA_VECT128;
19183         return true;
19184       default:
19185         return false;
19186       }
19187     }
19188   }
19189 
19190   return (Members > 0 && Members <= 4);
19191 }
19192 
19193 /// Return the correct alignment for the current calling convention.
19194 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
19195                                                        DataLayout DL) const {
19196   const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
19197   if (!ArgTy->isVectorTy())
19198     return ABITypeAlign;
19199 
19200   // Avoid over-aligning vector parameters. It would require realigning the
19201   // stack and waste space for no real benefit.
19202   return std::min(ABITypeAlign, DL.getStackAlignment());
19203 }
19204 
19205 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
19206 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
19207 /// passing according to AAPCS rules.
19208 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
19209     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
19210   if (getEffectiveCallingConv(CallConv, isVarArg) !=
19211       CallingConv::ARM_AAPCS_VFP)
19212     return false;
19213 
19214   HABaseType Base = HA_UNKNOWN;
19215   uint64_t Members = 0;
19216   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
19217   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
19218 
19219   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
19220   return IsHA || IsIntArray;
19221 }
19222 
19223 Register ARMTargetLowering::getExceptionPointerRegister(
19224     const Constant *PersonalityFn) const {
19225   // Platforms which do not use SjLj EH may return values in these registers
19226   // via the personality function.
19227   return Subtarget->useSjLjEH() ? Register() : ARM::R0;
19228 }
19229 
19230 Register ARMTargetLowering::getExceptionSelectorRegister(
19231     const Constant *PersonalityFn) const {
19232   // Platforms which do not use SjLj EH may return values in these registers
19233   // via the personality function.
19234   return Subtarget->useSjLjEH() ? Register() : ARM::R1;
19235 }
19236 
19237 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
19238   // Update IsSplitCSR in ARMFunctionInfo.
19239   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
19240   AFI->setIsSplitCSR(true);
19241 }
19242 
19243 void ARMTargetLowering::insertCopiesSplitCSR(
19244     MachineBasicBlock *Entry,
19245     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
19246   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
19247   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
19248   if (!IStart)
19249     return;
19250 
19251   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19252   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
19253   MachineBasicBlock::iterator MBBI = Entry->begin();
19254   for (const MCPhysReg *I = IStart; *I; ++I) {
19255     const TargetRegisterClass *RC = nullptr;
19256     if (ARM::GPRRegClass.contains(*I))
19257       RC = &ARM::GPRRegClass;
19258     else if (ARM::DPRRegClass.contains(*I))
19259       RC = &ARM::DPRRegClass;
19260     else
19261       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
19262 
19263     Register NewVR = MRI->createVirtualRegister(RC);
19264     // Create copy from CSR to a virtual register.
19265     // FIXME: this currently does not emit CFI pseudo-instructions, it works
19266     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
19267     // nounwind. If we want to generalize this later, we may need to emit
19268     // CFI pseudo-instructions.
19269     assert(Entry->getParent()->getFunction().hasFnAttribute(
19270                Attribute::NoUnwind) &&
19271            "Function should be nounwind in insertCopiesSplitCSR!");
19272     Entry->addLiveIn(*I);
19273     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
19274         .addReg(*I);
19275 
19276     // Insert the copy-back instructions right before the terminator.
19277     for (auto *Exit : Exits)
19278       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
19279               TII->get(TargetOpcode::COPY), *I)
19280           .addReg(NewVR);
19281   }
19282 }
19283 
19284 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
19285   MF.getFrameInfo().computeMaxCallFrameSize(MF);
19286   TargetLoweringBase::finalizeLowering(MF);
19287 }
19288