1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/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/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/StringRef.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/MachineValueType.h"
56 #include "llvm/CodeGen/RuntimeLibcalls.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGNodes.h"
59 #include "llvm/CodeGen/ValueTypes.h"
60 #include "llvm/IR/Attributes.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/Constants.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugLoc.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalValue.h"
71 #include "llvm/IR/GlobalVariable.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/Instruction.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/User.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/MC/MCInstrDesc.h"
83 #include "llvm/MC/MCInstrItineraries.h"
84 #include "llvm/MC/MCRegisterInfo.h"
85 #include "llvm/MC/MCSchedule.h"
86 #include "llvm/Support/AtomicOrdering.h"
87 #include "llvm/Support/BranchProbability.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CodeGen.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include "llvm/Support/KnownBits.h"
95 #include "llvm/Support/MathExtras.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/Target/TargetInstrInfo.h"
98 #include "llvm/Target/TargetMachine.h"
99 #include "llvm/Target/TargetOptions.h"
100 #include <algorithm>
101 #include <cassert>
102 #include <cstdint>
103 #include <cstdlib>
104 #include <iterator>
105 #include <limits>
106 #include <tuple>
107 #include <string>
108 #include <utility>
109 #include <vector>
110 
111 using namespace llvm;
112 
113 #define DEBUG_TYPE "arm-isel"
114 
115 STATISTIC(NumTailCalls, "Number of tail calls");
116 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
117 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
118 STATISTIC(NumConstpoolPromoted,
119   "Number of constants with their storage promoted into constant pools");
120 
121 static cl::opt<bool>
122 ARMInterworking("arm-interworking", cl::Hidden,
123   cl::desc("Enable / disable ARM interworking (for debugging only)"),
124   cl::init(true));
125 
126 static cl::opt<bool> EnableConstpoolPromotion(
127     "arm-promote-constant", cl::Hidden,
128     cl::desc("Enable / disable promotion of unnamed_addr constants into "
129              "constant pools"),
130     cl::init(true));
131 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
132     "arm-promote-constant-max-size", cl::Hidden,
133     cl::desc("Maximum size of constant to promote into a constant pool"),
134     cl::init(64));
135 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
136     "arm-promote-constant-max-total", cl::Hidden,
137     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
138     cl::init(128));
139 
140 // The APCS parameter registers.
141 static const MCPhysReg GPRArgRegs[] = {
142   ARM::R0, ARM::R1, ARM::R2, ARM::R3
143 };
144 
145 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
146                                        MVT PromotedBitwiseVT) {
147   if (VT != PromotedLdStVT) {
148     setOperationAction(ISD::LOAD, VT, Promote);
149     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
150 
151     setOperationAction(ISD::STORE, VT, Promote);
152     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
153   }
154 
155   MVT ElemTy = VT.getVectorElementType();
156   if (ElemTy != MVT::f64)
157     setOperationAction(ISD::SETCC, VT, Custom);
158   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
159   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
160   if (ElemTy == MVT::i32) {
161     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
162     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
163     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
164     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
165   } else {
166     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
167     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
168     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
169     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
170   }
171   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
172   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
173   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
174   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
175   setOperationAction(ISD::SELECT,            VT, Expand);
176   setOperationAction(ISD::SELECT_CC,         VT, Expand);
177   setOperationAction(ISD::VSELECT,           VT, Expand);
178   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
179   if (VT.isInteger()) {
180     setOperationAction(ISD::SHL, VT, Custom);
181     setOperationAction(ISD::SRA, VT, Custom);
182     setOperationAction(ISD::SRL, VT, Custom);
183   }
184 
185   // Promote all bit-wise operations.
186   if (VT.isInteger() && VT != PromotedBitwiseVT) {
187     setOperationAction(ISD::AND, VT, Promote);
188     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
189     setOperationAction(ISD::OR,  VT, Promote);
190     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
191     setOperationAction(ISD::XOR, VT, Promote);
192     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
193   }
194 
195   // Neon does not support vector divide/remainder operations.
196   setOperationAction(ISD::SDIV, VT, Expand);
197   setOperationAction(ISD::UDIV, VT, Expand);
198   setOperationAction(ISD::FDIV, VT, Expand);
199   setOperationAction(ISD::SREM, VT, Expand);
200   setOperationAction(ISD::UREM, VT, Expand);
201   setOperationAction(ISD::FREM, VT, Expand);
202 
203   if (!VT.isFloatingPoint() &&
204       VT != MVT::v2i64 && VT != MVT::v1i64)
205     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
206       setOperationAction(Opcode, VT, Legal);
207 }
208 
209 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
210   addRegisterClass(VT, &ARM::DPRRegClass);
211   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
212 }
213 
214 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
215   addRegisterClass(VT, &ARM::DPairRegClass);
216   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
217 }
218 
219 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
220                                      const ARMSubtarget &STI)
221     : TargetLowering(TM), Subtarget(&STI) {
222   RegInfo = Subtarget->getRegisterInfo();
223   Itins = Subtarget->getInstrItineraryData();
224 
225   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
226 
227   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
228       !Subtarget->isTargetWatchOS()) {
229     const auto &E = Subtarget->getTargetTriple().getEnvironment();
230 
231     bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
232                       E == Triple::MuslEABIHF;
233     // Windows is a special case.  Technically, we will replace all of the "GNU"
234     // calls with calls to MSVCRT if appropriate and adjust the calling
235     // convention then.
236     IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
237 
238     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
239       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
240                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
241                                        : CallingConv::ARM_AAPCS);
242   }
243 
244   if (Subtarget->isTargetMachO()) {
245     // Uses VFP for Thumb libfuncs if available.
246     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
247         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
248       static const struct {
249         const RTLIB::Libcall Op;
250         const char * const Name;
251         const ISD::CondCode Cond;
252       } LibraryCalls[] = {
253         // Single-precision floating-point arithmetic.
254         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
255         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
256         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
257         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
258 
259         // Double-precision floating-point arithmetic.
260         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
262         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
263         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
264 
265         // Single-precision comparisons.
266         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
267         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
268         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
269         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
270         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
271         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
272         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
273         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
274 
275         // Double-precision comparisons.
276         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
277         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
278         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
279         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
280         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
281         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
282         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
283         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
284 
285         // Floating-point to integer conversions.
286         // i64 conversions are done via library routines even when generating VFP
287         // instructions, so use the same ones.
288         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
289         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
290         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
291         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
292 
293         // Conversions between floating types.
294         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
295         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
296 
297         // Integer to floating-point conversions.
298         // i64 conversions are done via library routines even when generating VFP
299         // instructions, so use the same ones.
300         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
301         // e.g., __floatunsidf vs. __floatunssidfvfp.
302         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
303         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
304         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
305         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
306       };
307 
308       for (const auto &LC : LibraryCalls) {
309         setLibcallName(LC.Op, LC.Name);
310         if (LC.Cond != ISD::SETCC_INVALID)
311           setCmpLibcallCC(LC.Op, LC.Cond);
312       }
313     }
314 
315     // Set the correct calling convention for ARMv7k WatchOS. It's just
316     // AAPCS_VFP for functions as simple as libcalls.
317     if (Subtarget->isTargetWatchABI()) {
318       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
319         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
320     }
321   }
322 
323   // These libcalls are not available in 32-bit.
324   setLibcallName(RTLIB::SHL_I128, nullptr);
325   setLibcallName(RTLIB::SRL_I128, nullptr);
326   setLibcallName(RTLIB::SRA_I128, nullptr);
327 
328   // RTLIB
329   if (Subtarget->isAAPCS_ABI() &&
330       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
331        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
332     static const struct {
333       const RTLIB::Libcall Op;
334       const char * const Name;
335       const CallingConv::ID CC;
336       const ISD::CondCode Cond;
337     } LibraryCalls[] = {
338       // Double-precision floating-point arithmetic helper functions
339       // RTABI chapter 4.1.2, Table 2
340       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 
345       // Double-precision floating-point comparison helper functions
346       // RTABI chapter 4.1.2, Table 3
347       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
348       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
349       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
352       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
353       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
354       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
355 
356       // Single-precision floating-point arithmetic helper functions
357       // RTABI chapter 4.1.2, Table 4
358       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
361       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
362 
363       // Single-precision floating-point comparison helper functions
364       // RTABI chapter 4.1.2, Table 5
365       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
366       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
367       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
370       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
371       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
372       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
373 
374       // Floating-point to integer conversions.
375       // RTABI chapter 4.1.2, Table 6
376       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384 
385       // Conversions between floating types.
386       // RTABI chapter 4.1.2, Table 7
387       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390 
391       // Integer to floating-point conversions.
392       // RTABI chapter 4.1.2, Table 8
393       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401 
402       // Long long helper functions
403       // RTABI chapter 4.2, Table 9
404       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408 
409       // Integer division functions
410       // RTABI chapter 4.3.1
411       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
419     };
420 
421     for (const auto &LC : LibraryCalls) {
422       setLibcallName(LC.Op, LC.Name);
423       setLibcallCallingConv(LC.Op, LC.CC);
424       if (LC.Cond != ISD::SETCC_INVALID)
425         setCmpLibcallCC(LC.Op, LC.Cond);
426     }
427 
428     // EABI dependent RTLIB
429     if (TM.Options.EABIVersion == EABI::EABI4 ||
430         TM.Options.EABIVersion == EABI::EABI5) {
431       static const struct {
432         const RTLIB::Libcall Op;
433         const char *const Name;
434         const CallingConv::ID CC;
435         const ISD::CondCode Cond;
436       } MemOpsLibraryCalls[] = {
437         // Memory operations
438         // RTABI chapter 4.3.4
439         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
440         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
441         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
442       };
443 
444       for (const auto &LC : MemOpsLibraryCalls) {
445         setLibcallName(LC.Op, LC.Name);
446         setLibcallCallingConv(LC.Op, LC.CC);
447         if (LC.Cond != ISD::SETCC_INVALID)
448           setCmpLibcallCC(LC.Op, LC.Cond);
449       }
450     }
451   }
452 
453   if (Subtarget->isTargetWindows()) {
454     static const struct {
455       const RTLIB::Libcall Op;
456       const char * const Name;
457       const CallingConv::ID CC;
458     } LibraryCalls[] = {
459       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
464       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
465       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
466       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
467     };
468 
469     for (const auto &LC : LibraryCalls) {
470       setLibcallName(LC.Op, LC.Name);
471       setLibcallCallingConv(LC.Op, LC.CC);
472     }
473   }
474 
475   // Use divmod compiler-rt calls for iOS 5.0 and later.
476   if (Subtarget->isTargetWatchOS() ||
477       (Subtarget->isTargetIOS() &&
478        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
479     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
480     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
481   }
482 
483   // The half <-> float conversion functions are always soft-float on
484   // non-watchos platforms, but are needed for some targets which use a
485   // hard-float calling convention by default.
486   if (!Subtarget->isTargetWatchABI()) {
487     if (Subtarget->isAAPCS_ABI()) {
488       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
489       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
490       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
491     } else {
492       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
493       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
494       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
495     }
496   }
497 
498   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
499   // a __gnu_ prefix (which is the default).
500   if (Subtarget->isTargetAEABI()) {
501     static const struct {
502       const RTLIB::Libcall Op;
503       const char * const Name;
504       const CallingConv::ID CC;
505     } LibraryCalls[] = {
506       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
507       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
508       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
509     };
510 
511     for (const auto &LC : LibraryCalls) {
512       setLibcallName(LC.Op, LC.Name);
513       setLibcallCallingConv(LC.Op, LC.CC);
514     }
515   }
516 
517   if (Subtarget->isThumb1Only())
518     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
519   else
520     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
521 
522   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
523       !Subtarget->isThumb1Only()) {
524     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
525     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
526   }
527 
528   for (MVT VT : MVT::vector_valuetypes()) {
529     for (MVT InnerVT : MVT::vector_valuetypes()) {
530       setTruncStoreAction(VT, InnerVT, Expand);
531       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
532       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
533       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
534     }
535 
536     setOperationAction(ISD::MULHS, VT, Expand);
537     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
538     setOperationAction(ISD::MULHU, VT, Expand);
539     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
540 
541     setOperationAction(ISD::BSWAP, VT, Expand);
542   }
543 
544   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
545   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
546 
547   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
548   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
549 
550   if (Subtarget->hasNEON()) {
551     addDRTypeForNEON(MVT::v2f32);
552     addDRTypeForNEON(MVT::v8i8);
553     addDRTypeForNEON(MVT::v4i16);
554     addDRTypeForNEON(MVT::v2i32);
555     addDRTypeForNEON(MVT::v1i64);
556 
557     addQRTypeForNEON(MVT::v4f32);
558     addQRTypeForNEON(MVT::v2f64);
559     addQRTypeForNEON(MVT::v16i8);
560     addQRTypeForNEON(MVT::v8i16);
561     addQRTypeForNEON(MVT::v4i32);
562     addQRTypeForNEON(MVT::v2i64);
563 
564     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
565     // neither Neon nor VFP support any arithmetic operations on it.
566     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
567     // supported for v4f32.
568     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
569     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
570     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
571     // FIXME: Code duplication: FDIV and FREM are expanded always, see
572     // ARMTargetLowering::addTypeForNEON method for details.
573     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
574     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
575     // FIXME: Create unittest.
576     // In another words, find a way when "copysign" appears in DAG with vector
577     // operands.
578     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
579     // FIXME: Code duplication: SETCC has custom operation action, see
580     // ARMTargetLowering::addTypeForNEON method for details.
581     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
582     // FIXME: Create unittest for FNEG and for FABS.
583     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
584     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
585     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
586     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
587     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
588     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
589     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
590     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
591     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
592     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
593     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
594     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
595     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
596     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
597     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
598     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
599     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
600     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
601     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
602 
603     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
604     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
605     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
606     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
607     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
608     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
609     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
610     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
611     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
612     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
613     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
614     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
615     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
616     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
617     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
618 
619     // Mark v2f32 intrinsics.
620     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
621     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
622     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
623     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
624     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
625     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
626     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
627     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
628     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
629     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
630     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
631     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
632     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
633     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
634     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
635 
636     // Neon does not support some operations on v1i64 and v2i64 types.
637     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
638     // Custom handling for some quad-vector types to detect VMULL.
639     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
640     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
641     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
642     // Custom handling for some vector types to avoid expensive expansions
643     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
644     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
645     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
646     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
647     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
648     // a destination type that is wider than the source, and nor does
649     // it have a FP_TO_[SU]INT instruction with a narrower destination than
650     // source.
651     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
652     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
653     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
654     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
655 
656     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
657     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
658 
659     // NEON does not have single instruction CTPOP for vectors with element
660     // types wider than 8-bits.  However, custom lowering can leverage the
661     // v8i8/v16i8 vcnt instruction.
662     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
663     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
664     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
665     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
666     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
667     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
668 
669     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
670     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
671 
672     // NEON does not have single instruction CTTZ for vectors.
673     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
674     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
675     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
676     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
677 
678     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
679     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
680     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
681     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
682 
683     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
684     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
686     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
687 
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
689     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
691     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
692 
693     // NEON only has FMA instructions as of VFP4.
694     if (!Subtarget->hasVFP4()) {
695       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
696       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
697     }
698 
699     setTargetDAGCombine(ISD::INTRINSIC_VOID);
700     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
701     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
702     setTargetDAGCombine(ISD::SHL);
703     setTargetDAGCombine(ISD::SRL);
704     setTargetDAGCombine(ISD::SRA);
705     setTargetDAGCombine(ISD::SIGN_EXTEND);
706     setTargetDAGCombine(ISD::ZERO_EXTEND);
707     setTargetDAGCombine(ISD::ANY_EXTEND);
708     setTargetDAGCombine(ISD::BUILD_VECTOR);
709     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
710     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
711     setTargetDAGCombine(ISD::STORE);
712     setTargetDAGCombine(ISD::FP_TO_SINT);
713     setTargetDAGCombine(ISD::FP_TO_UINT);
714     setTargetDAGCombine(ISD::FDIV);
715     setTargetDAGCombine(ISD::LOAD);
716 
717     // It is legal to extload from v4i8 to v4i16 or v4i32.
718     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
719                    MVT::v2i32}) {
720       for (MVT VT : MVT::integer_vector_valuetypes()) {
721         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
722         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
723         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
724       }
725     }
726   }
727 
728   if (Subtarget->isFPOnlySP()) {
729     // When targeting a floating-point unit with only single-precision
730     // operations, f64 is legal for the few double-precision instructions which
731     // are present However, no double-precision operations other than moves,
732     // loads and stores are provided by the hardware.
733     setOperationAction(ISD::FADD,       MVT::f64, Expand);
734     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
735     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
736     setOperationAction(ISD::FMA,        MVT::f64, Expand);
737     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
738     setOperationAction(ISD::FREM,       MVT::f64, Expand);
739     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
740     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
741     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
742     setOperationAction(ISD::FABS,       MVT::f64, Expand);
743     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
744     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
745     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
746     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
747     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
748     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
749     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
750     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
751     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
752     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
753     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
754     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
755     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
756     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
757     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
758     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
759     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
760     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
761     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
762     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
763     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
764     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
765     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
766   }
767 
768   computeRegisterProperties(Subtarget->getRegisterInfo());
769 
770   // ARM does not have floating-point extending loads.
771   for (MVT VT : MVT::fp_valuetypes()) {
772     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
773     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
774   }
775 
776   // ... or truncating stores
777   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
778   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
779   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
780 
781   // ARM does not have i1 sign extending load.
782   for (MVT VT : MVT::integer_valuetypes())
783     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
784 
785   // ARM supports all 4 flavors of integer indexed load / store.
786   if (!Subtarget->isThumb1Only()) {
787     for (unsigned im = (unsigned)ISD::PRE_INC;
788          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
789       setIndexedLoadAction(im,  MVT::i1,  Legal);
790       setIndexedLoadAction(im,  MVT::i8,  Legal);
791       setIndexedLoadAction(im,  MVT::i16, Legal);
792       setIndexedLoadAction(im,  MVT::i32, Legal);
793       setIndexedStoreAction(im, MVT::i1,  Legal);
794       setIndexedStoreAction(im, MVT::i8,  Legal);
795       setIndexedStoreAction(im, MVT::i16, Legal);
796       setIndexedStoreAction(im, MVT::i32, Legal);
797     }
798   } else {
799     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
800     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
801     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
802   }
803 
804   setOperationAction(ISD::SADDO, MVT::i32, Custom);
805   setOperationAction(ISD::UADDO, MVT::i32, Custom);
806   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
807   setOperationAction(ISD::USUBO, MVT::i32, Custom);
808 
809   // i64 operation support.
810   setOperationAction(ISD::MUL,     MVT::i64, Expand);
811   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
812   if (Subtarget->isThumb1Only()) {
813     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
814     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
815   }
816   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
817       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
818     setOperationAction(ISD::MULHS, MVT::i32, Expand);
819 
820   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
821   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
822   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
823   setOperationAction(ISD::SRL,       MVT::i64, Custom);
824   setOperationAction(ISD::SRA,       MVT::i64, Custom);
825   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
826 
827   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
828   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
829   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
830   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
831 
832   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
833     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
834 
835   // ARM does not have ROTL.
836   setOperationAction(ISD::ROTL, MVT::i32, Expand);
837   for (MVT VT : MVT::vector_valuetypes()) {
838     setOperationAction(ISD::ROTL, VT, Expand);
839     setOperationAction(ISD::ROTR, VT, Expand);
840   }
841   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
842   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
843   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
844     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
845 
846   // @llvm.readcyclecounter requires the Performance Monitors extension.
847   // Default to the 0 expansion on unsupported platforms.
848   // FIXME: Technically there are older ARM CPUs that have
849   // implementation-specific ways of obtaining this information.
850   if (Subtarget->hasPerfMon())
851     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
852 
853   // Only ARMv6 has BSWAP.
854   if (!Subtarget->hasV6Ops())
855     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
856 
857   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
858                                         : Subtarget->hasDivideInARMMode();
859   if (!hasDivide) {
860     // These are expanded into libcalls if the cpu doesn't have HW divider.
861     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
862     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
863   }
864 
865   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
866     setOperationAction(ISD::SDIV, MVT::i32, Custom);
867     setOperationAction(ISD::UDIV, MVT::i32, Custom);
868 
869     setOperationAction(ISD::SDIV, MVT::i64, Custom);
870     setOperationAction(ISD::UDIV, MVT::i64, Custom);
871   }
872 
873   setOperationAction(ISD::SREM,  MVT::i32, Expand);
874   setOperationAction(ISD::UREM,  MVT::i32, Expand);
875 
876   // Register based DivRem for AEABI (RTABI 4.2)
877   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
878       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
879       Subtarget->isTargetWindows()) {
880     setOperationAction(ISD::SREM, MVT::i64, Custom);
881     setOperationAction(ISD::UREM, MVT::i64, Custom);
882     HasStandaloneRem = false;
883 
884     if (Subtarget->isTargetWindows()) {
885       const struct {
886         const RTLIB::Libcall Op;
887         const char * const Name;
888         const CallingConv::ID CC;
889       } LibraryCalls[] = {
890         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
891         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
892         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
893         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
894 
895         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
896         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
897         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
898         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
899       };
900 
901       for (const auto &LC : LibraryCalls) {
902         setLibcallName(LC.Op, LC.Name);
903         setLibcallCallingConv(LC.Op, LC.CC);
904       }
905     } else {
906       const struct {
907         const RTLIB::Libcall Op;
908         const char * const Name;
909         const CallingConv::ID CC;
910       } LibraryCalls[] = {
911         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
912         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
913         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
914         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
915 
916         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
918         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
919         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
920       };
921 
922       for (const auto &LC : LibraryCalls) {
923         setLibcallName(LC.Op, LC.Name);
924         setLibcallCallingConv(LC.Op, LC.CC);
925       }
926     }
927 
928     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
929     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
930     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
931     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
932   } else {
933     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
934     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
935   }
936 
937   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
938     for (auto &VT : {MVT::f32, MVT::f64})
939       setOperationAction(ISD::FPOWI, VT, Custom);
940 
941   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
942   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
943   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
944   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
945 
946   setOperationAction(ISD::TRAP, MVT::Other, Legal);
947 
948   // Use the default implementation.
949   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
950   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
951   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
952   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
953   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
954   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
955 
956   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
957     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
958   else
959     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
960 
961   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
962   // the default expansion.
963   InsertFencesForAtomic = false;
964   if (Subtarget->hasAnyDataBarrier() &&
965       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
966     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
967     // to ldrex/strex loops already.
968     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
969     if (!Subtarget->isThumb() || !Subtarget->isMClass())
970       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
971 
972     // On v8, we have particularly efficient implementations of atomic fences
973     // if they can be combined with nearby atomic loads and stores.
974     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
975       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
976       InsertFencesForAtomic = true;
977     }
978   } else {
979     // If there's anything we can use as a barrier, go through custom lowering
980     // for ATOMIC_FENCE.
981     // If target has DMB in thumb, Fences can be inserted.
982     if (Subtarget->hasDataBarrier())
983       InsertFencesForAtomic = true;
984 
985     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
986                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
987 
988     // Set them all for expansion, which will force libcalls.
989     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
990     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
991     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
992     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1001     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1002     // Unordered/Monotonic case.
1003     if (!InsertFencesForAtomic) {
1004       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1005       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1006     }
1007   }
1008 
1009   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1010 
1011   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1012   if (!Subtarget->hasV6Ops()) {
1013     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1014     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1015   }
1016   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1017 
1018   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1019       !Subtarget->isThumb1Only()) {
1020     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1021     // iff target supports vfp2.
1022     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1023     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1024   }
1025 
1026   // We want to custom lower some of our intrinsics.
1027   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1028   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1029   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1030   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1031   if (Subtarget->useSjLjEH())
1032     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1033 
1034   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1035   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1036   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1037   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1038   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1039   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1040   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1041   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1042   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1043 
1044   // Thumb-1 cannot currently select ARMISD::SUBE.
1045   if (!Subtarget->isThumb1Only())
1046     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1047 
1048   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1049   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1050   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1051   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1052   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1053 
1054   // We don't support sin/cos/fmod/copysign/pow
1055   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1056   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1057   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1058   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1059   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1060   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1061   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1062   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1063   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1064       !Subtarget->isThumb1Only()) {
1065     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1066     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1067   }
1068   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1069   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1070 
1071   if (!Subtarget->hasVFP4()) {
1072     setOperationAction(ISD::FMA, MVT::f64, Expand);
1073     setOperationAction(ISD::FMA, MVT::f32, Expand);
1074   }
1075 
1076   // Various VFP goodness
1077   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1078     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1079     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1080       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1081       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1082     }
1083 
1084     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1085     if (!Subtarget->hasFP16()) {
1086       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1087       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1088     }
1089   }
1090 
1091   // Combine sin / cos into one node or libcall if possible.
1092   if (Subtarget->hasSinCos()) {
1093     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1094     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1095     if (Subtarget->isTargetWatchABI()) {
1096       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1097       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1098     }
1099     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1100       // For iOS, we don't want to the normal expansion of a libcall to
1101       // sincos. We want to issue a libcall to __sincos_stret.
1102       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1103       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1104     }
1105   }
1106 
1107   // FP-ARMv8 implements a lot of rounding-like FP operations.
1108   if (Subtarget->hasFPARMv8()) {
1109     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1110     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1111     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1112     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1113     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1114     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1115     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1116     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1117     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1118     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1119     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1120     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1121 
1122     if (!Subtarget->isFPOnlySP()) {
1123       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1124       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1125       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1126       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1127       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1128       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1129       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1130       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1131     }
1132   }
1133 
1134   if (Subtarget->hasNEON()) {
1135     // vmin and vmax aren't available in a scalar form, so we use
1136     // a NEON instruction with an undef lane instead.
1137     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1138     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1139     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1140     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1141     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1142     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1143   }
1144 
1145   // We have target-specific dag combine patterns for the following nodes:
1146   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1147   setTargetDAGCombine(ISD::ADD);
1148   setTargetDAGCombine(ISD::SUB);
1149   setTargetDAGCombine(ISD::MUL);
1150   setTargetDAGCombine(ISD::AND);
1151   setTargetDAGCombine(ISD::OR);
1152   setTargetDAGCombine(ISD::XOR);
1153 
1154   if (Subtarget->hasV6Ops())
1155     setTargetDAGCombine(ISD::SRL);
1156 
1157   setStackPointerRegisterToSaveRestore(ARM::SP);
1158 
1159   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1160       !Subtarget->hasVFP2())
1161     setSchedulingPreference(Sched::RegPressure);
1162   else
1163     setSchedulingPreference(Sched::Hybrid);
1164 
1165   //// temporary - rewrite interface to use type
1166   MaxStoresPerMemset = 8;
1167   MaxStoresPerMemsetOptSize = 4;
1168   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1169   MaxStoresPerMemcpyOptSize = 2;
1170   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1171   MaxStoresPerMemmoveOptSize = 2;
1172 
1173   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1174   // are at least 4 bytes aligned.
1175   setMinStackArgumentAlignment(4);
1176 
1177   // Prefer likely predicted branches to selects on out-of-order cores.
1178   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1179 
1180   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1181 }
1182 
1183 bool ARMTargetLowering::useSoftFloat() const {
1184   return Subtarget->useSoftFloat();
1185 }
1186 
1187 // FIXME: It might make sense to define the representative register class as the
1188 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1189 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1190 // SPR's representative would be DPR_VFP2. This should work well if register
1191 // pressure tracking were modified such that a register use would increment the
1192 // pressure of the register class's representative and all of it's super
1193 // classes' representatives transitively. We have not implemented this because
1194 // of the difficulty prior to coalescing of modeling operand register classes
1195 // due to the common occurrence of cross class copies and subregister insertions
1196 // and extractions.
1197 std::pair<const TargetRegisterClass *, uint8_t>
1198 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1199                                            MVT VT) const {
1200   const TargetRegisterClass *RRC = nullptr;
1201   uint8_t Cost = 1;
1202   switch (VT.SimpleTy) {
1203   default:
1204     return TargetLowering::findRepresentativeClass(TRI, VT);
1205   // Use DPR as representative register class for all floating point
1206   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1207   // the cost is 1 for both f32 and f64.
1208   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1209   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1210     RRC = &ARM::DPRRegClass;
1211     // When NEON is used for SP, only half of the register file is available
1212     // because operations that define both SP and DP results will be constrained
1213     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1214     // coalescing by double-counting the SP regs. See the FIXME above.
1215     if (Subtarget->useNEONForSinglePrecisionFP())
1216       Cost = 2;
1217     break;
1218   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1219   case MVT::v4f32: case MVT::v2f64:
1220     RRC = &ARM::DPRRegClass;
1221     Cost = 2;
1222     break;
1223   case MVT::v4i64:
1224     RRC = &ARM::DPRRegClass;
1225     Cost = 4;
1226     break;
1227   case MVT::v8i64:
1228     RRC = &ARM::DPRRegClass;
1229     Cost = 8;
1230     break;
1231   }
1232   return std::make_pair(RRC, Cost);
1233 }
1234 
1235 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1236   switch ((ARMISD::NodeType)Opcode) {
1237   case ARMISD::FIRST_NUMBER:  break;
1238   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1239   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1240   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1241   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1242   case ARMISD::CALL:          return "ARMISD::CALL";
1243   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1244   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1245   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1246   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1247   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1248   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1249   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1250   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1251   case ARMISD::CMP:           return "ARMISD::CMP";
1252   case ARMISD::CMN:           return "ARMISD::CMN";
1253   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1254   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1255   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1256   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1257   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1258 
1259   case ARMISD::CMOV:          return "ARMISD::CMOV";
1260 
1261   case ARMISD::SSAT:          return "ARMISD::SSAT";
1262 
1263   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1264   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1265   case ARMISD::RRX:           return "ARMISD::RRX";
1266 
1267   case ARMISD::ADDC:          return "ARMISD::ADDC";
1268   case ARMISD::ADDE:          return "ARMISD::ADDE";
1269   case ARMISD::SUBC:          return "ARMISD::SUBC";
1270   case ARMISD::SUBE:          return "ARMISD::SUBE";
1271 
1272   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1273   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1274 
1275   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1276   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1277   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1278 
1279   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1280 
1281   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1282 
1283   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1284 
1285   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1286 
1287   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1288 
1289   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1290   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1291 
1292   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1293   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1294   case ARMISD::VCGE:          return "ARMISD::VCGE";
1295   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1296   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1297   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1298   case ARMISD::VCGT:          return "ARMISD::VCGT";
1299   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1300   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1301   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1302   case ARMISD::VTST:          return "ARMISD::VTST";
1303 
1304   case ARMISD::VSHL:          return "ARMISD::VSHL";
1305   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1306   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1307   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1308   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1309   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1310   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1311   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1312   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1313   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1314   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1315   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1316   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1317   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1318   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1319   case ARMISD::VSLI:          return "ARMISD::VSLI";
1320   case ARMISD::VSRI:          return "ARMISD::VSRI";
1321   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1322   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1323   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1324   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1325   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1326   case ARMISD::VDUP:          return "ARMISD::VDUP";
1327   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1328   case ARMISD::VEXT:          return "ARMISD::VEXT";
1329   case ARMISD::VREV64:        return "ARMISD::VREV64";
1330   case ARMISD::VREV32:        return "ARMISD::VREV32";
1331   case ARMISD::VREV16:        return "ARMISD::VREV16";
1332   case ARMISD::VZIP:          return "ARMISD::VZIP";
1333   case ARMISD::VUZP:          return "ARMISD::VUZP";
1334   case ARMISD::VTRN:          return "ARMISD::VTRN";
1335   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1336   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1337   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1338   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1339   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1340   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1341   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1342   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1343   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1344   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1345   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1346   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1347   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1348   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1349   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1350   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1351   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1352   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1353   case ARMISD::BFI:           return "ARMISD::BFI";
1354   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1355   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1356   case ARMISD::VBSL:          return "ARMISD::VBSL";
1357   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1358   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1359   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1360   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1361   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1362   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1363   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1364   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1365   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1366   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1367   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1368   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1369   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1370   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1371   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1372   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1373   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1374   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1375   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1376   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1377   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1378   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1379   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1380   }
1381   return nullptr;
1382 }
1383 
1384 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1385                                           EVT VT) const {
1386   if (!VT.isVector())
1387     return getPointerTy(DL);
1388   return VT.changeVectorElementTypeToInteger();
1389 }
1390 
1391 /// getRegClassFor - Return the register class that should be used for the
1392 /// specified value type.
1393 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1394   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1395   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1396   // load / store 4 to 8 consecutive D registers.
1397   if (Subtarget->hasNEON()) {
1398     if (VT == MVT::v4i64)
1399       return &ARM::QQPRRegClass;
1400     if (VT == MVT::v8i64)
1401       return &ARM::QQQQPRRegClass;
1402   }
1403   return TargetLowering::getRegClassFor(VT);
1404 }
1405 
1406 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1407 // source/dest is aligned and the copy size is large enough. We therefore want
1408 // to align such objects passed to memory intrinsics.
1409 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1410                                                unsigned &PrefAlign) const {
1411   if (!isa<MemIntrinsic>(CI))
1412     return false;
1413   MinSize = 8;
1414   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1415   // cycle faster than 4-byte aligned LDM.
1416   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1417   return true;
1418 }
1419 
1420 // Create a fast isel object.
1421 FastISel *
1422 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1423                                   const TargetLibraryInfo *libInfo) const {
1424   return ARM::createFastISel(funcInfo, libInfo);
1425 }
1426 
1427 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1428   unsigned NumVals = N->getNumValues();
1429   if (!NumVals)
1430     return Sched::RegPressure;
1431 
1432   for (unsigned i = 0; i != NumVals; ++i) {
1433     EVT VT = N->getValueType(i);
1434     if (VT == MVT::Glue || VT == MVT::Other)
1435       continue;
1436     if (VT.isFloatingPoint() || VT.isVector())
1437       return Sched::ILP;
1438   }
1439 
1440   if (!N->isMachineOpcode())
1441     return Sched::RegPressure;
1442 
1443   // Load are scheduled for latency even if there instruction itinerary
1444   // is not available.
1445   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1446   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1447 
1448   if (MCID.getNumDefs() == 0)
1449     return Sched::RegPressure;
1450   if (!Itins->isEmpty() &&
1451       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1452     return Sched::ILP;
1453 
1454   return Sched::RegPressure;
1455 }
1456 
1457 //===----------------------------------------------------------------------===//
1458 // Lowering Code
1459 //===----------------------------------------------------------------------===//
1460 
1461 static bool isSRL16(const SDValue &Op) {
1462   if (Op.getOpcode() != ISD::SRL)
1463     return false;
1464   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1465     return Const->getZExtValue() == 16;
1466   return false;
1467 }
1468 
1469 static bool isSRA16(const SDValue &Op) {
1470   if (Op.getOpcode() != ISD::SRA)
1471     return false;
1472   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1473     return Const->getZExtValue() == 16;
1474   return false;
1475 }
1476 
1477 static bool isSHL16(const SDValue &Op) {
1478   if (Op.getOpcode() != ISD::SHL)
1479     return false;
1480   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1481     return Const->getZExtValue() == 16;
1482   return false;
1483 }
1484 
1485 // Check for a signed 16-bit value. We special case SRA because it makes it
1486 // more simple when also looking for SRAs that aren't sign extending a
1487 // smaller value. Without the check, we'd need to take extra care with
1488 // checking order for some operations.
1489 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1490   if (isSRA16(Op))
1491     return isSHL16(Op.getOperand(0));
1492   return DAG.ComputeNumSignBits(Op) == 17;
1493 }
1494 
1495 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1496 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1497   switch (CC) {
1498   default: llvm_unreachable("Unknown condition code!");
1499   case ISD::SETNE:  return ARMCC::NE;
1500   case ISD::SETEQ:  return ARMCC::EQ;
1501   case ISD::SETGT:  return ARMCC::GT;
1502   case ISD::SETGE:  return ARMCC::GE;
1503   case ISD::SETLT:  return ARMCC::LT;
1504   case ISD::SETLE:  return ARMCC::LE;
1505   case ISD::SETUGT: return ARMCC::HI;
1506   case ISD::SETUGE: return ARMCC::HS;
1507   case ISD::SETULT: return ARMCC::LO;
1508   case ISD::SETULE: return ARMCC::LS;
1509   }
1510 }
1511 
1512 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1513 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1514                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1515   CondCode2 = ARMCC::AL;
1516   InvalidOnQNaN = true;
1517   switch (CC) {
1518   default: llvm_unreachable("Unknown FP condition!");
1519   case ISD::SETEQ:
1520   case ISD::SETOEQ:
1521     CondCode = ARMCC::EQ;
1522     InvalidOnQNaN = false;
1523     break;
1524   case ISD::SETGT:
1525   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1526   case ISD::SETGE:
1527   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1528   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1529   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1530   case ISD::SETONE:
1531     CondCode = ARMCC::MI;
1532     CondCode2 = ARMCC::GT;
1533     InvalidOnQNaN = false;
1534     break;
1535   case ISD::SETO:   CondCode = ARMCC::VC; break;
1536   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1537   case ISD::SETUEQ:
1538     CondCode = ARMCC::EQ;
1539     CondCode2 = ARMCC::VS;
1540     InvalidOnQNaN = false;
1541     break;
1542   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1543   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1544   case ISD::SETLT:
1545   case ISD::SETULT: CondCode = ARMCC::LT; break;
1546   case ISD::SETLE:
1547   case ISD::SETULE: CondCode = ARMCC::LE; break;
1548   case ISD::SETNE:
1549   case ISD::SETUNE:
1550     CondCode = ARMCC::NE;
1551     InvalidOnQNaN = false;
1552     break;
1553   }
1554 }
1555 
1556 //===----------------------------------------------------------------------===//
1557 //                      Calling Convention Implementation
1558 //===----------------------------------------------------------------------===//
1559 
1560 #include "ARMGenCallingConv.inc"
1561 
1562 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1563 /// account presence of floating point hardware and calling convention
1564 /// limitations, such as support for variadic functions.
1565 CallingConv::ID
1566 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1567                                            bool isVarArg) const {
1568   switch (CC) {
1569   default:
1570     llvm_unreachable("Unsupported calling convention");
1571   case CallingConv::ARM_AAPCS:
1572   case CallingConv::ARM_APCS:
1573   case CallingConv::GHC:
1574     return CC;
1575   case CallingConv::PreserveMost:
1576     return CallingConv::PreserveMost;
1577   case CallingConv::ARM_AAPCS_VFP:
1578   case CallingConv::Swift:
1579     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1580   case CallingConv::C:
1581     if (!Subtarget->isAAPCS_ABI())
1582       return CallingConv::ARM_APCS;
1583     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1584              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1585              !isVarArg)
1586       return CallingConv::ARM_AAPCS_VFP;
1587     else
1588       return CallingConv::ARM_AAPCS;
1589   case CallingConv::Fast:
1590   case CallingConv::CXX_FAST_TLS:
1591     if (!Subtarget->isAAPCS_ABI()) {
1592       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1593         return CallingConv::Fast;
1594       return CallingConv::ARM_APCS;
1595     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1596       return CallingConv::ARM_AAPCS_VFP;
1597     else
1598       return CallingConv::ARM_AAPCS;
1599   }
1600 }
1601 
1602 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1603                                                  bool isVarArg) const {
1604   return CCAssignFnForNode(CC, false, isVarArg);
1605 }
1606 
1607 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1608                                                    bool isVarArg) const {
1609   return CCAssignFnForNode(CC, true, isVarArg);
1610 }
1611 
1612 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1613 /// CallingConvention.
1614 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1615                                                  bool Return,
1616                                                  bool isVarArg) const {
1617   switch (getEffectiveCallingConv(CC, isVarArg)) {
1618   default:
1619     llvm_unreachable("Unsupported calling convention");
1620   case CallingConv::ARM_APCS:
1621     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1622   case CallingConv::ARM_AAPCS:
1623     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1624   case CallingConv::ARM_AAPCS_VFP:
1625     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1626   case CallingConv::Fast:
1627     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1628   case CallingConv::GHC:
1629     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1630   case CallingConv::PreserveMost:
1631     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1632   }
1633 }
1634 
1635 /// LowerCallResult - Lower the result values of a call into the
1636 /// appropriate copies out of appropriate physical registers.
1637 SDValue ARMTargetLowering::LowerCallResult(
1638     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1639     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1640     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1641     SDValue ThisVal) const {
1642 
1643   // Assign locations to each value returned by this call.
1644   SmallVector<CCValAssign, 16> RVLocs;
1645   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1646                  *DAG.getContext());
1647   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1648 
1649   // Copy all of the result registers out of their specified physreg.
1650   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1651     CCValAssign VA = RVLocs[i];
1652 
1653     // Pass 'this' value directly from the argument to return value, to avoid
1654     // reg unit interference
1655     if (i == 0 && isThisReturn) {
1656       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1657              "unexpected return calling convention register assignment");
1658       InVals.push_back(ThisVal);
1659       continue;
1660     }
1661 
1662     SDValue Val;
1663     if (VA.needsCustom()) {
1664       // Handle f64 or half of a v2f64.
1665       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1666                                       InFlag);
1667       Chain = Lo.getValue(1);
1668       InFlag = Lo.getValue(2);
1669       VA = RVLocs[++i]; // skip ahead to next loc
1670       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1671                                       InFlag);
1672       Chain = Hi.getValue(1);
1673       InFlag = Hi.getValue(2);
1674       if (!Subtarget->isLittle())
1675         std::swap (Lo, Hi);
1676       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1677 
1678       if (VA.getLocVT() == MVT::v2f64) {
1679         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1680         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1681                           DAG.getConstant(0, dl, MVT::i32));
1682 
1683         VA = RVLocs[++i]; // skip ahead to next loc
1684         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1685         Chain = Lo.getValue(1);
1686         InFlag = Lo.getValue(2);
1687         VA = RVLocs[++i]; // skip ahead to next loc
1688         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1689         Chain = Hi.getValue(1);
1690         InFlag = Hi.getValue(2);
1691         if (!Subtarget->isLittle())
1692           std::swap (Lo, Hi);
1693         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1694         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1695                           DAG.getConstant(1, dl, MVT::i32));
1696       }
1697     } else {
1698       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1699                                InFlag);
1700       Chain = Val.getValue(1);
1701       InFlag = Val.getValue(2);
1702     }
1703 
1704     switch (VA.getLocInfo()) {
1705     default: llvm_unreachable("Unknown loc info!");
1706     case CCValAssign::Full: break;
1707     case CCValAssign::BCvt:
1708       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1709       break;
1710     }
1711 
1712     InVals.push_back(Val);
1713   }
1714 
1715   return Chain;
1716 }
1717 
1718 /// LowerMemOpCallTo - Store the argument to the stack.
1719 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1720                                             SDValue Arg, const SDLoc &dl,
1721                                             SelectionDAG &DAG,
1722                                             const CCValAssign &VA,
1723                                             ISD::ArgFlagsTy Flags) const {
1724   unsigned LocMemOffset = VA.getLocMemOffset();
1725   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1726   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1727                        StackPtr, PtrOff);
1728   return DAG.getStore(
1729       Chain, dl, Arg, PtrOff,
1730       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1731 }
1732 
1733 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1734                                          SDValue Chain, SDValue &Arg,
1735                                          RegsToPassVector &RegsToPass,
1736                                          CCValAssign &VA, CCValAssign &NextVA,
1737                                          SDValue &StackPtr,
1738                                          SmallVectorImpl<SDValue> &MemOpChains,
1739                                          ISD::ArgFlagsTy Flags) const {
1740 
1741   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1742                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1743   unsigned id = Subtarget->isLittle() ? 0 : 1;
1744   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1745 
1746   if (NextVA.isRegLoc())
1747     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1748   else {
1749     assert(NextVA.isMemLoc());
1750     if (!StackPtr.getNode())
1751       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1752                                     getPointerTy(DAG.getDataLayout()));
1753 
1754     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1755                                            dl, DAG, NextVA,
1756                                            Flags));
1757   }
1758 }
1759 
1760 /// LowerCall - Lowering a call into a callseq_start <-
1761 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1762 /// nodes.
1763 SDValue
1764 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1765                              SmallVectorImpl<SDValue> &InVals) const {
1766   SelectionDAG &DAG                     = CLI.DAG;
1767   SDLoc &dl                             = CLI.DL;
1768   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1769   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1770   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1771   SDValue Chain                         = CLI.Chain;
1772   SDValue Callee                        = CLI.Callee;
1773   bool &isTailCall                      = CLI.IsTailCall;
1774   CallingConv::ID CallConv              = CLI.CallConv;
1775   bool doesNotRet                       = CLI.DoesNotReturn;
1776   bool isVarArg                         = CLI.IsVarArg;
1777 
1778   MachineFunction &MF = DAG.getMachineFunction();
1779   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1780   bool isThisReturn   = false;
1781   bool isSibCall      = false;
1782   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1783 
1784   // Disable tail calls if they're not supported.
1785   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1786     isTailCall = false;
1787 
1788   if (isTailCall) {
1789     // Check if it's really possible to do a tail call.
1790     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1791                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1792                                                    Outs, OutVals, Ins, DAG);
1793     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1794       report_fatal_error("failed to perform tail call elimination on a call "
1795                          "site marked musttail");
1796     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1797     // detected sibcalls.
1798     if (isTailCall) {
1799       ++NumTailCalls;
1800       isSibCall = true;
1801     }
1802   }
1803 
1804   // Analyze operands of the call, assigning locations to each operand.
1805   SmallVector<CCValAssign, 16> ArgLocs;
1806   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1807                  *DAG.getContext());
1808   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1809 
1810   // Get a count of how many bytes are to be pushed on the stack.
1811   unsigned NumBytes = CCInfo.getNextStackOffset();
1812 
1813   // For tail calls, memory operands are available in our caller's stack.
1814   if (isSibCall)
1815     NumBytes = 0;
1816 
1817   // Adjust the stack pointer for the new arguments...
1818   // These operations are automatically eliminated by the prolog/epilog pass
1819   if (!isSibCall)
1820     Chain = DAG.getCALLSEQ_START(Chain,
1821                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1822 
1823   SDValue StackPtr =
1824       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1825 
1826   RegsToPassVector RegsToPass;
1827   SmallVector<SDValue, 8> MemOpChains;
1828 
1829   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1830   // of tail call optimization, arguments are handled later.
1831   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1832        i != e;
1833        ++i, ++realArgIdx) {
1834     CCValAssign &VA = ArgLocs[i];
1835     SDValue Arg = OutVals[realArgIdx];
1836     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1837     bool isByVal = Flags.isByVal();
1838 
1839     // Promote the value if needed.
1840     switch (VA.getLocInfo()) {
1841     default: llvm_unreachable("Unknown loc info!");
1842     case CCValAssign::Full: break;
1843     case CCValAssign::SExt:
1844       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1845       break;
1846     case CCValAssign::ZExt:
1847       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1848       break;
1849     case CCValAssign::AExt:
1850       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1851       break;
1852     case CCValAssign::BCvt:
1853       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1854       break;
1855     }
1856 
1857     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1858     if (VA.needsCustom()) {
1859       if (VA.getLocVT() == MVT::v2f64) {
1860         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1861                                   DAG.getConstant(0, dl, MVT::i32));
1862         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1863                                   DAG.getConstant(1, dl, MVT::i32));
1864 
1865         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1866                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1867 
1868         VA = ArgLocs[++i]; // skip ahead to next loc
1869         if (VA.isRegLoc()) {
1870           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1871                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1872         } else {
1873           assert(VA.isMemLoc());
1874 
1875           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1876                                                  dl, DAG, VA, Flags));
1877         }
1878       } else {
1879         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1880                          StackPtr, MemOpChains, Flags);
1881       }
1882     } else if (VA.isRegLoc()) {
1883       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1884           Outs[0].VT == MVT::i32) {
1885         assert(VA.getLocVT() == MVT::i32 &&
1886                "unexpected calling convention register assignment");
1887         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1888                "unexpected use of 'returned'");
1889         isThisReturn = true;
1890       }
1891       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1892     } else if (isByVal) {
1893       assert(VA.isMemLoc());
1894       unsigned offset = 0;
1895 
1896       // True if this byval aggregate will be split between registers
1897       // and memory.
1898       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1899       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1900 
1901       if (CurByValIdx < ByValArgsCount) {
1902 
1903         unsigned RegBegin, RegEnd;
1904         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1905 
1906         EVT PtrVT =
1907             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1908         unsigned int i, j;
1909         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1910           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1911           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1912           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1913                                      MachinePointerInfo(),
1914                                      DAG.InferPtrAlignment(AddArg));
1915           MemOpChains.push_back(Load.getValue(1));
1916           RegsToPass.push_back(std::make_pair(j, Load));
1917         }
1918 
1919         // If parameter size outsides register area, "offset" value
1920         // helps us to calculate stack slot for remained part properly.
1921         offset = RegEnd - RegBegin;
1922 
1923         CCInfo.nextInRegsParam();
1924       }
1925 
1926       if (Flags.getByValSize() > 4*offset) {
1927         auto PtrVT = getPointerTy(DAG.getDataLayout());
1928         unsigned LocMemOffset = VA.getLocMemOffset();
1929         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1930         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1931         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1932         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1933         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1934                                            MVT::i32);
1935         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1936                                             MVT::i32);
1937 
1938         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1939         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1940         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1941                                           Ops));
1942       }
1943     } else if (!isSibCall) {
1944       assert(VA.isMemLoc());
1945 
1946       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1947                                              dl, DAG, VA, Flags));
1948     }
1949   }
1950 
1951   if (!MemOpChains.empty())
1952     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1953 
1954   // Build a sequence of copy-to-reg nodes chained together with token chain
1955   // and flag operands which copy the outgoing args into the appropriate regs.
1956   SDValue InFlag;
1957   // Tail call byval lowering might overwrite argument registers so in case of
1958   // tail call optimization the copies to registers are lowered later.
1959   if (!isTailCall)
1960     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1961       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1962                                RegsToPass[i].second, InFlag);
1963       InFlag = Chain.getValue(1);
1964     }
1965 
1966   // For tail calls lower the arguments to the 'real' stack slot.
1967   if (isTailCall) {
1968     // Force all the incoming stack arguments to be loaded from the stack
1969     // before any new outgoing arguments are stored to the stack, because the
1970     // outgoing stack slots may alias the incoming argument stack slots, and
1971     // the alias isn't otherwise explicit. This is slightly more conservative
1972     // than necessary, because it means that each store effectively depends
1973     // on every argument instead of just those arguments it would clobber.
1974 
1975     // Do not flag preceding copytoreg stuff together with the following stuff.
1976     InFlag = SDValue();
1977     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1978       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1979                                RegsToPass[i].second, InFlag);
1980       InFlag = Chain.getValue(1);
1981     }
1982     InFlag = SDValue();
1983   }
1984 
1985   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1986   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1987   // node so that legalize doesn't hack it.
1988   bool isDirect = false;
1989 
1990   const TargetMachine &TM = getTargetMachine();
1991   const Module *Mod = MF.getFunction()->getParent();
1992   const GlobalValue *GV = nullptr;
1993   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1994     GV = G->getGlobal();
1995   bool isStub =
1996       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1997 
1998   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1999   bool isLocalARMFunc = false;
2000   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2001   auto PtrVt = getPointerTy(DAG.getDataLayout());
2002 
2003   if (Subtarget->genLongCalls()) {
2004     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2005            "long-calls codegen is not position independent!");
2006     // Handle a global address or an external symbol. If it's not one of
2007     // those, the target's already in a register, so we don't need to do
2008     // anything extra.
2009     if (isa<GlobalAddressSDNode>(Callee)) {
2010       // Create a constant pool entry for the callee address
2011       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2012       ARMConstantPoolValue *CPV =
2013         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2014 
2015       // Get the address of the callee into a register
2016       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2017       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2018       Callee = DAG.getLoad(
2019           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2020           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2021     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2022       const char *Sym = S->getSymbol();
2023 
2024       // Create a constant pool entry for the callee address
2025       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2026       ARMConstantPoolValue *CPV =
2027         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2028                                       ARMPCLabelIndex, 0);
2029       // Get the address of the callee into a register
2030       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2031       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2032       Callee = DAG.getLoad(
2033           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2034           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2035     }
2036   } else if (isa<GlobalAddressSDNode>(Callee)) {
2037     // If we're optimizing for minimum size and the function is called three or
2038     // more times in this block, we can improve codesize by calling indirectly
2039     // as BLXr has a 16-bit encoding.
2040     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2041     auto *BB = CLI.CS->getParent();
2042     bool PreferIndirect =
2043         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2044         count_if(GV->users(), [&BB](const User *U) {
2045           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2046         }) > 2;
2047 
2048     if (!PreferIndirect) {
2049       isDirect = true;
2050       bool isDef = GV->isStrongDefinitionForLinker();
2051 
2052       // ARM call to a local ARM function is predicable.
2053       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2054       // tBX takes a register source operand.
2055       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2056         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2057         Callee = DAG.getNode(
2058             ARMISD::WrapperPIC, dl, PtrVt,
2059             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2060         Callee = DAG.getLoad(
2061             PtrVt, dl, DAG.getEntryNode(), Callee,
2062             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2063             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2064                                      MachineMemOperand::MOInvariant);
2065       } else if (Subtarget->isTargetCOFF()) {
2066         assert(Subtarget->isTargetWindows() &&
2067                "Windows is the only supported COFF target");
2068         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2069                                    ? ARMII::MO_DLLIMPORT
2070                                    : ARMII::MO_NO_FLAG;
2071         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2072                                             TargetFlags);
2073         if (GV->hasDLLImportStorageClass())
2074           Callee =
2075               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2076                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2077                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2078       } else {
2079         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2080       }
2081     }
2082   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2083     isDirect = true;
2084     // tBX takes a register source operand.
2085     const char *Sym = S->getSymbol();
2086     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2087       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2088       ARMConstantPoolValue *CPV =
2089         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2090                                       ARMPCLabelIndex, 4);
2091       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2092       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2093       Callee = DAG.getLoad(
2094           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2095           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2096       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2097       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2098     } else {
2099       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2100     }
2101   }
2102 
2103   // FIXME: handle tail calls differently.
2104   unsigned CallOpc;
2105   if (Subtarget->isThumb()) {
2106     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2107       CallOpc = ARMISD::CALL_NOLINK;
2108     else
2109       CallOpc = ARMISD::CALL;
2110   } else {
2111     if (!isDirect && !Subtarget->hasV5TOps())
2112       CallOpc = ARMISD::CALL_NOLINK;
2113     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2114              // Emit regular call when code size is the priority
2115              !MF.getFunction()->optForMinSize())
2116       // "mov lr, pc; b _foo" to avoid confusing the RSP
2117       CallOpc = ARMISD::CALL_NOLINK;
2118     else
2119       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2120   }
2121 
2122   std::vector<SDValue> Ops;
2123   Ops.push_back(Chain);
2124   Ops.push_back(Callee);
2125 
2126   // Add argument registers to the end of the list so that they are known live
2127   // into the call.
2128   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2129     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2130                                   RegsToPass[i].second.getValueType()));
2131 
2132   // Add a register mask operand representing the call-preserved registers.
2133   if (!isTailCall) {
2134     const uint32_t *Mask;
2135     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2136     if (isThisReturn) {
2137       // For 'this' returns, use the R0-preserving mask if applicable
2138       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2139       if (!Mask) {
2140         // Set isThisReturn to false if the calling convention is not one that
2141         // allows 'returned' to be modeled in this way, so LowerCallResult does
2142         // not try to pass 'this' straight through
2143         isThisReturn = false;
2144         Mask = ARI->getCallPreservedMask(MF, CallConv);
2145       }
2146     } else
2147       Mask = ARI->getCallPreservedMask(MF, CallConv);
2148 
2149     assert(Mask && "Missing call preserved mask for calling convention");
2150     Ops.push_back(DAG.getRegisterMask(Mask));
2151   }
2152 
2153   if (InFlag.getNode())
2154     Ops.push_back(InFlag);
2155 
2156   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2157   if (isTailCall) {
2158     MF.getFrameInfo().setHasTailCall();
2159     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2160   }
2161 
2162   // Returns a chain and a flag for retval copy to use.
2163   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2164   InFlag = Chain.getValue(1);
2165 
2166   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2167                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2168   if (!Ins.empty())
2169     InFlag = Chain.getValue(1);
2170 
2171   // Handle result values, copying them out of physregs into vregs that we
2172   // return.
2173   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2174                          InVals, isThisReturn,
2175                          isThisReturn ? OutVals[0] : SDValue());
2176 }
2177 
2178 /// HandleByVal - Every parameter *after* a byval parameter is passed
2179 /// on the stack.  Remember the next parameter register to allocate,
2180 /// and then confiscate the rest of the parameter registers to insure
2181 /// this.
2182 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2183                                     unsigned Align) const {
2184   // Byval (as with any stack) slots are always at least 4 byte aligned.
2185   Align = std::max(Align, 4U);
2186 
2187   unsigned Reg = State->AllocateReg(GPRArgRegs);
2188   if (!Reg)
2189     return;
2190 
2191   unsigned AlignInRegs = Align / 4;
2192   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2193   for (unsigned i = 0; i < Waste; ++i)
2194     Reg = State->AllocateReg(GPRArgRegs);
2195 
2196   if (!Reg)
2197     return;
2198 
2199   unsigned Excess = 4 * (ARM::R4 - Reg);
2200 
2201   // Special case when NSAA != SP and parameter size greater than size of
2202   // all remained GPR regs. In that case we can't split parameter, we must
2203   // send it to stack. We also must set NCRN to R4, so waste all
2204   // remained registers.
2205   const unsigned NSAAOffset = State->getNextStackOffset();
2206   if (NSAAOffset != 0 && Size > Excess) {
2207     while (State->AllocateReg(GPRArgRegs))
2208       ;
2209     return;
2210   }
2211 
2212   // First register for byval parameter is the first register that wasn't
2213   // allocated before this method call, so it would be "reg".
2214   // If parameter is small enough to be saved in range [reg, r4), then
2215   // the end (first after last) register would be reg + param-size-in-regs,
2216   // else parameter would be splitted between registers and stack,
2217   // end register would be r4 in this case.
2218   unsigned ByValRegBegin = Reg;
2219   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2220   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2221   // Note, first register is allocated in the beginning of function already,
2222   // allocate remained amount of registers we need.
2223   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2224     State->AllocateReg(GPRArgRegs);
2225   // A byval parameter that is split between registers and memory needs its
2226   // size truncated here.
2227   // In the case where the entire structure fits in registers, we set the
2228   // size in memory to zero.
2229   Size = std::max<int>(Size - Excess, 0);
2230 }
2231 
2232 /// MatchingStackOffset - Return true if the given stack call argument is
2233 /// already available in the same position (relatively) of the caller's
2234 /// incoming argument stack.
2235 static
2236 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2237                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2238                          const TargetInstrInfo *TII) {
2239   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2240   int FI = std::numeric_limits<int>::max();
2241   if (Arg.getOpcode() == ISD::CopyFromReg) {
2242     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2243     if (!TargetRegisterInfo::isVirtualRegister(VR))
2244       return false;
2245     MachineInstr *Def = MRI->getVRegDef(VR);
2246     if (!Def)
2247       return false;
2248     if (!Flags.isByVal()) {
2249       if (!TII->isLoadFromStackSlot(*Def, FI))
2250         return false;
2251     } else {
2252       return false;
2253     }
2254   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2255     if (Flags.isByVal())
2256       // ByVal argument is passed in as a pointer but it's now being
2257       // dereferenced. e.g.
2258       // define @foo(%struct.X* %A) {
2259       //   tail call @bar(%struct.X* byval %A)
2260       // }
2261       return false;
2262     SDValue Ptr = Ld->getBasePtr();
2263     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2264     if (!FINode)
2265       return false;
2266     FI = FINode->getIndex();
2267   } else
2268     return false;
2269 
2270   assert(FI != std::numeric_limits<int>::max());
2271   if (!MFI.isFixedObjectIndex(FI))
2272     return false;
2273   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2274 }
2275 
2276 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2277 /// for tail call optimization. Targets which want to do tail call
2278 /// optimization should implement this function.
2279 bool
2280 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2281                                                      CallingConv::ID CalleeCC,
2282                                                      bool isVarArg,
2283                                                      bool isCalleeStructRet,
2284                                                      bool isCallerStructRet,
2285                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2286                                     const SmallVectorImpl<SDValue> &OutVals,
2287                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2288                                                      SelectionDAG& DAG) const {
2289   MachineFunction &MF = DAG.getMachineFunction();
2290   const Function *CallerF = MF.getFunction();
2291   CallingConv::ID CallerCC = CallerF->getCallingConv();
2292 
2293   assert(Subtarget->supportsTailCall());
2294 
2295   // Look for obvious safe cases to perform tail call optimization that do not
2296   // require ABI changes. This is what gcc calls sibcall.
2297 
2298   // Exception-handling functions need a special set of instructions to indicate
2299   // a return to the hardware. Tail-calling another function would probably
2300   // break this.
2301   if (CallerF->hasFnAttribute("interrupt"))
2302     return false;
2303 
2304   // Also avoid sibcall optimization if either caller or callee uses struct
2305   // return semantics.
2306   if (isCalleeStructRet || isCallerStructRet)
2307     return false;
2308 
2309   // Externally-defined functions with weak linkage should not be
2310   // tail-called on ARM when the OS does not support dynamic
2311   // pre-emption of symbols, as the AAELF spec requires normal calls
2312   // to undefined weak functions to be replaced with a NOP or jump to the
2313   // next instruction. The behaviour of branch instructions in this
2314   // situation (as used for tail calls) is implementation-defined, so we
2315   // cannot rely on the linker replacing the tail call with a return.
2316   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2317     const GlobalValue *GV = G->getGlobal();
2318     const Triple &TT = getTargetMachine().getTargetTriple();
2319     if (GV->hasExternalWeakLinkage() &&
2320         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2321       return false;
2322   }
2323 
2324   // Check that the call results are passed in the same way.
2325   LLVMContext &C = *DAG.getContext();
2326   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2327                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2328                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2329     return false;
2330   // The callee has to preserve all registers the caller needs to preserve.
2331   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2332   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2333   if (CalleeCC != CallerCC) {
2334     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2335     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2336       return false;
2337   }
2338 
2339   // If Caller's vararg or byval argument has been split between registers and
2340   // stack, do not perform tail call, since part of the argument is in caller's
2341   // local frame.
2342   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2343   if (AFI_Caller->getArgRegsSaveSize())
2344     return false;
2345 
2346   // If the callee takes no arguments then go on to check the results of the
2347   // call.
2348   if (!Outs.empty()) {
2349     // Check if stack adjustment is needed. For now, do not do this if any
2350     // argument is passed on the stack.
2351     SmallVector<CCValAssign, 16> ArgLocs;
2352     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2353     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2354     if (CCInfo.getNextStackOffset()) {
2355       // Check if the arguments are already laid out in the right way as
2356       // the caller's fixed stack objects.
2357       MachineFrameInfo &MFI = MF.getFrameInfo();
2358       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2359       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2360       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2361            i != e;
2362            ++i, ++realArgIdx) {
2363         CCValAssign &VA = ArgLocs[i];
2364         EVT RegVT = VA.getLocVT();
2365         SDValue Arg = OutVals[realArgIdx];
2366         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2367         if (VA.getLocInfo() == CCValAssign::Indirect)
2368           return false;
2369         if (VA.needsCustom()) {
2370           // f64 and vector types are split into multiple registers or
2371           // register/stack-slot combinations.  The types will not match
2372           // the registers; give up on memory f64 refs until we figure
2373           // out what to do about this.
2374           if (!VA.isRegLoc())
2375             return false;
2376           if (!ArgLocs[++i].isRegLoc())
2377             return false;
2378           if (RegVT == MVT::v2f64) {
2379             if (!ArgLocs[++i].isRegLoc())
2380               return false;
2381             if (!ArgLocs[++i].isRegLoc())
2382               return false;
2383           }
2384         } else if (!VA.isRegLoc()) {
2385           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2386                                    MFI, MRI, TII))
2387             return false;
2388         }
2389       }
2390     }
2391 
2392     const MachineRegisterInfo &MRI = MF.getRegInfo();
2393     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2394       return false;
2395   }
2396 
2397   return true;
2398 }
2399 
2400 bool
2401 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2402                                   MachineFunction &MF, bool isVarArg,
2403                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2404                                   LLVMContext &Context) const {
2405   SmallVector<CCValAssign, 16> RVLocs;
2406   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2407   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2408 }
2409 
2410 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2411                                     const SDLoc &DL, SelectionDAG &DAG) {
2412   const MachineFunction &MF = DAG.getMachineFunction();
2413   const Function *F = MF.getFunction();
2414 
2415   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2416 
2417   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2418   // version of the "preferred return address". These offsets affect the return
2419   // instruction if this is a return from PL1 without hypervisor extensions.
2420   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2421   //    SWI:     0      "subs pc, lr, #0"
2422   //    ABORT:   +4     "subs pc, lr, #4"
2423   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2424   // UNDEF varies depending on where the exception came from ARM or Thumb
2425   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2426 
2427   int64_t LROffset;
2428   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2429       IntKind == "ABORT")
2430     LROffset = 4;
2431   else if (IntKind == "SWI" || IntKind == "UNDEF")
2432     LROffset = 0;
2433   else
2434     report_fatal_error("Unsupported interrupt attribute. If present, value "
2435                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2436 
2437   RetOps.insert(RetOps.begin() + 1,
2438                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2439 
2440   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2441 }
2442 
2443 SDValue
2444 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2445                                bool isVarArg,
2446                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2447                                const SmallVectorImpl<SDValue> &OutVals,
2448                                const SDLoc &dl, SelectionDAG &DAG) const {
2449 
2450   // CCValAssign - represent the assignment of the return value to a location.
2451   SmallVector<CCValAssign, 16> RVLocs;
2452 
2453   // CCState - Info about the registers and stack slots.
2454   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2455                  *DAG.getContext());
2456 
2457   // Analyze outgoing return values.
2458   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2459 
2460   SDValue Flag;
2461   SmallVector<SDValue, 4> RetOps;
2462   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2463   bool isLittleEndian = Subtarget->isLittle();
2464 
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   AFI->setReturnRegsCount(RVLocs.size());
2468 
2469   // Copy the result values into the output registers.
2470   for (unsigned i = 0, realRVLocIdx = 0;
2471        i != RVLocs.size();
2472        ++i, ++realRVLocIdx) {
2473     CCValAssign &VA = RVLocs[i];
2474     assert(VA.isRegLoc() && "Can only return in registers!");
2475 
2476     SDValue Arg = OutVals[realRVLocIdx];
2477 
2478     switch (VA.getLocInfo()) {
2479     default: llvm_unreachable("Unknown loc info!");
2480     case CCValAssign::Full: break;
2481     case CCValAssign::BCvt:
2482       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2483       break;
2484     }
2485 
2486     if (VA.needsCustom()) {
2487       if (VA.getLocVT() == MVT::v2f64) {
2488         // Extract the first half and return it in two registers.
2489         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2490                                    DAG.getConstant(0, dl, MVT::i32));
2491         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2492                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2493 
2494         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2496                                  Flag);
2497         Flag = Chain.getValue(1);
2498         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2499         VA = RVLocs[++i]; // skip ahead to next loc
2500         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2501                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2502                                  Flag);
2503         Flag = Chain.getValue(1);
2504         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2505         VA = RVLocs[++i]; // skip ahead to next loc
2506 
2507         // Extract the 2nd half and fall through to handle it as an f64 value.
2508         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2509                           DAG.getConstant(1, dl, MVT::i32));
2510       }
2511       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2512       // available.
2513       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2514                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2515       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2517                                Flag);
2518       Flag = Chain.getValue(1);
2519       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2520       VA = RVLocs[++i]; // skip ahead to next loc
2521       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2522                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2523                                Flag);
2524     } else
2525       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2526 
2527     // Guarantee that all emitted copies are
2528     // stuck together, avoiding something bad.
2529     Flag = Chain.getValue(1);
2530     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2531   }
2532   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2533   const MCPhysReg *I =
2534       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2535   if (I) {
2536     for (; *I; ++I) {
2537       if (ARM::GPRRegClass.contains(*I))
2538         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2539       else if (ARM::DPRRegClass.contains(*I))
2540         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2541       else
2542         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2543     }
2544   }
2545 
2546   // Update chain and glue.
2547   RetOps[0] = Chain;
2548   if (Flag.getNode())
2549     RetOps.push_back(Flag);
2550 
2551   // CPUs which aren't M-class use a special sequence to return from
2552   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2553   // though we use "subs pc, lr, #N").
2554   //
2555   // M-class CPUs actually use a normal return sequence with a special
2556   // (hardware-provided) value in LR, so the normal code path works.
2557   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2558       !Subtarget->isMClass()) {
2559     if (Subtarget->isThumb1Only())
2560       report_fatal_error("interrupt attribute is not supported in Thumb1");
2561     return LowerInterruptReturn(RetOps, dl, DAG);
2562   }
2563 
2564   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2565 }
2566 
2567 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2568   if (N->getNumValues() != 1)
2569     return false;
2570   if (!N->hasNUsesOfValue(1, 0))
2571     return false;
2572 
2573   SDValue TCChain = Chain;
2574   SDNode *Copy = *N->use_begin();
2575   if (Copy->getOpcode() == ISD::CopyToReg) {
2576     // If the copy has a glue operand, we conservatively assume it isn't safe to
2577     // perform a tail call.
2578     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2579       return false;
2580     TCChain = Copy->getOperand(0);
2581   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2582     SDNode *VMov = Copy;
2583     // f64 returned in a pair of GPRs.
2584     SmallPtrSet<SDNode*, 2> Copies;
2585     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2586          UI != UE; ++UI) {
2587       if (UI->getOpcode() != ISD::CopyToReg)
2588         return false;
2589       Copies.insert(*UI);
2590     }
2591     if (Copies.size() > 2)
2592       return false;
2593 
2594     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2595          UI != UE; ++UI) {
2596       SDValue UseChain = UI->getOperand(0);
2597       if (Copies.count(UseChain.getNode()))
2598         // Second CopyToReg
2599         Copy = *UI;
2600       else {
2601         // We are at the top of this chain.
2602         // If the copy has a glue operand, we conservatively assume it
2603         // isn't safe to perform a tail call.
2604         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2605           return false;
2606         // First CopyToReg
2607         TCChain = UseChain;
2608       }
2609     }
2610   } else if (Copy->getOpcode() == ISD::BITCAST) {
2611     // f32 returned in a single GPR.
2612     if (!Copy->hasOneUse())
2613       return false;
2614     Copy = *Copy->use_begin();
2615     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2616       return false;
2617     // If the copy has a glue operand, we conservatively assume it isn't safe to
2618     // perform a tail call.
2619     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2620       return false;
2621     TCChain = Copy->getOperand(0);
2622   } else {
2623     return false;
2624   }
2625 
2626   bool HasRet = false;
2627   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2628        UI != UE; ++UI) {
2629     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2630         UI->getOpcode() != ARMISD::INTRET_FLAG)
2631       return false;
2632     HasRet = true;
2633   }
2634 
2635   if (!HasRet)
2636     return false;
2637 
2638   Chain = TCChain;
2639   return true;
2640 }
2641 
2642 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2643   if (!Subtarget->supportsTailCall())
2644     return false;
2645 
2646   auto Attr =
2647       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2648   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2649     return false;
2650 
2651   return true;
2652 }
2653 
2654 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2655 // and pass the lower and high parts through.
2656 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2657   SDLoc DL(Op);
2658   SDValue WriteValue = Op->getOperand(2);
2659 
2660   // This function is only supposed to be called for i64 type argument.
2661   assert(WriteValue.getValueType() == MVT::i64
2662           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2663 
2664   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2665                            DAG.getConstant(0, DL, MVT::i32));
2666   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2667                            DAG.getConstant(1, DL, MVT::i32));
2668   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2669   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2670 }
2671 
2672 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2673 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2674 // one of the above mentioned nodes. It has to be wrapped because otherwise
2675 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2676 // be used to form addressing mode. These wrapped nodes will be selected
2677 // into MOVi.
2678 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2679   EVT PtrVT = Op.getValueType();
2680   // FIXME there is no actual debug info here
2681   SDLoc dl(Op);
2682   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2683   SDValue Res;
2684   if (CP->isMachineConstantPoolEntry())
2685     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2686                                     CP->getAlignment());
2687   else
2688     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2689                                     CP->getAlignment());
2690   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2691 }
2692 
2693 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2694   return MachineJumpTableInfo::EK_Inline;
2695 }
2696 
2697 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2698                                              SelectionDAG &DAG) const {
2699   MachineFunction &MF = DAG.getMachineFunction();
2700   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2701   unsigned ARMPCLabelIndex = 0;
2702   SDLoc DL(Op);
2703   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2704   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2705   SDValue CPAddr;
2706   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2707   if (!IsPositionIndependent) {
2708     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2709   } else {
2710     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2711     ARMPCLabelIndex = AFI->createPICLabelUId();
2712     ARMConstantPoolValue *CPV =
2713       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2714                                       ARMCP::CPBlockAddress, PCAdj);
2715     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2716   }
2717   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2718   SDValue Result = DAG.getLoad(
2719       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2720       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2721   if (!IsPositionIndependent)
2722     return Result;
2723   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2724   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2725 }
2726 
2727 /// \brief Convert a TLS address reference into the correct sequence of loads
2728 /// and calls to compute the variable's address for Darwin, and return an
2729 /// SDValue containing the final node.
2730 
2731 /// Darwin only has one TLS scheme which must be capable of dealing with the
2732 /// fully general situation, in the worst case. This means:
2733 ///     + "extern __thread" declaration.
2734 ///     + Defined in a possibly unknown dynamic library.
2735 ///
2736 /// The general system is that each __thread variable has a [3 x i32] descriptor
2737 /// which contains information used by the runtime to calculate the address. The
2738 /// only part of this the compiler needs to know about is the first word, which
2739 /// contains a function pointer that must be called with the address of the
2740 /// entire descriptor in "r0".
2741 ///
2742 /// Since this descriptor may be in a different unit, in general access must
2743 /// proceed along the usual ARM rules. A common sequence to produce is:
2744 ///
2745 ///     movw rT1, :lower16:_var$non_lazy_ptr
2746 ///     movt rT1, :upper16:_var$non_lazy_ptr
2747 ///     ldr r0, [rT1]
2748 ///     ldr rT2, [r0]
2749 ///     blx rT2
2750 ///     [...address now in r0...]
2751 SDValue
2752 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2753                                                SelectionDAG &DAG) const {
2754   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2755   SDLoc DL(Op);
2756 
2757   // First step is to get the address of the actua global symbol. This is where
2758   // the TLS descriptor lives.
2759   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2760 
2761   // The first entry in the descriptor is a function pointer that we must call
2762   // to obtain the address of the variable.
2763   SDValue Chain = DAG.getEntryNode();
2764   SDValue FuncTLVGet = DAG.getLoad(
2765       MVT::i32, DL, Chain, DescAddr,
2766       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2767       /* Alignment = */ 4,
2768       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2769           MachineMemOperand::MOInvariant);
2770   Chain = FuncTLVGet.getValue(1);
2771 
2772   MachineFunction &F = DAG.getMachineFunction();
2773   MachineFrameInfo &MFI = F.getFrameInfo();
2774   MFI.setAdjustsStack(true);
2775 
2776   // TLS calls preserve all registers except those that absolutely must be
2777   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2778   // silly).
2779   auto TRI =
2780       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2781   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2782   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2783 
2784   // Finally, we can make the call. This is just a degenerate version of a
2785   // normal AArch64 call node: r0 takes the address of the descriptor, and
2786   // returns the address of the variable in this thread.
2787   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2788   Chain =
2789       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2790                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2791                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2792   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2793 }
2794 
2795 SDValue
2796 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2797                                                 SelectionDAG &DAG) const {
2798   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2799 
2800   SDValue Chain = DAG.getEntryNode();
2801   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2802   SDLoc DL(Op);
2803 
2804   // Load the current TEB (thread environment block)
2805   SDValue Ops[] = {Chain,
2806                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2807                    DAG.getConstant(15, DL, MVT::i32),
2808                    DAG.getConstant(0, DL, MVT::i32),
2809                    DAG.getConstant(13, DL, MVT::i32),
2810                    DAG.getConstant(0, DL, MVT::i32),
2811                    DAG.getConstant(2, DL, MVT::i32)};
2812   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2813                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2814 
2815   SDValue TEB = CurrentTEB.getValue(0);
2816   Chain = CurrentTEB.getValue(1);
2817 
2818   // Load the ThreadLocalStoragePointer from the TEB
2819   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2820   SDValue TLSArray =
2821       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2822   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2823 
2824   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2825   // offset into the TLSArray.
2826 
2827   // Load the TLS index from the C runtime
2828   SDValue TLSIndex =
2829       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2830   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2831   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2832 
2833   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2834                               DAG.getConstant(2, DL, MVT::i32));
2835   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2836                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2837                             MachinePointerInfo());
2838 
2839   // Get the offset of the start of the .tls section (section base)
2840   const auto *GA = cast<GlobalAddressSDNode>(Op);
2841   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2842   SDValue Offset = DAG.getLoad(
2843       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2844                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2845       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2846 
2847   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2848 }
2849 
2850 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2851 SDValue
2852 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2853                                                  SelectionDAG &DAG) const {
2854   SDLoc dl(GA);
2855   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2856   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2857   MachineFunction &MF = DAG.getMachineFunction();
2858   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2859   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2860   ARMConstantPoolValue *CPV =
2861     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2862                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2863   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2864   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2865   Argument = DAG.getLoad(
2866       PtrVT, dl, DAG.getEntryNode(), Argument,
2867       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2868   SDValue Chain = Argument.getValue(1);
2869 
2870   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2871   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2872 
2873   // call __tls_get_addr.
2874   ArgListTy Args;
2875   ArgListEntry Entry;
2876   Entry.Node = Argument;
2877   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2878   Args.push_back(Entry);
2879 
2880   // FIXME: is there useful debug info available here?
2881   TargetLowering::CallLoweringInfo CLI(DAG);
2882   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2883       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2884       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2885 
2886   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2887   return CallResult.first;
2888 }
2889 
2890 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2891 // "local exec" model.
2892 SDValue
2893 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2894                                         SelectionDAG &DAG,
2895                                         TLSModel::Model model) const {
2896   const GlobalValue *GV = GA->getGlobal();
2897   SDLoc dl(GA);
2898   SDValue Offset;
2899   SDValue Chain = DAG.getEntryNode();
2900   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2901   // Get the Thread Pointer
2902   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2903 
2904   if (model == TLSModel::InitialExec) {
2905     MachineFunction &MF = DAG.getMachineFunction();
2906     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2907     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2908     // Initial exec model.
2909     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2910     ARMConstantPoolValue *CPV =
2911       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2912                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2913                                       true);
2914     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2915     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2916     Offset = DAG.getLoad(
2917         PtrVT, dl, Chain, Offset,
2918         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2919     Chain = Offset.getValue(1);
2920 
2921     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2922     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2923 
2924     Offset = DAG.getLoad(
2925         PtrVT, dl, Chain, Offset,
2926         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2927   } else {
2928     // local exec model
2929     assert(model == TLSModel::LocalExec);
2930     ARMConstantPoolValue *CPV =
2931       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2932     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2933     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2934     Offset = DAG.getLoad(
2935         PtrVT, dl, Chain, Offset,
2936         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2937   }
2938 
2939   // The address of the thread local variable is the add of the thread
2940   // pointer with the offset of the variable.
2941   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2942 }
2943 
2944 SDValue
2945 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2946   if (Subtarget->isTargetDarwin())
2947     return LowerGlobalTLSAddressDarwin(Op, DAG);
2948 
2949   if (Subtarget->isTargetWindows())
2950     return LowerGlobalTLSAddressWindows(Op, DAG);
2951 
2952   // TODO: implement the "local dynamic" model
2953   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2954   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2955   if (DAG.getTarget().Options.EmulatedTLS)
2956     return LowerToTLSEmulatedModel(GA, DAG);
2957 
2958   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2959 
2960   switch (model) {
2961     case TLSModel::GeneralDynamic:
2962     case TLSModel::LocalDynamic:
2963       return LowerToTLSGeneralDynamicModel(GA, DAG);
2964     case TLSModel::InitialExec:
2965     case TLSModel::LocalExec:
2966       return LowerToTLSExecModels(GA, DAG, model);
2967   }
2968   llvm_unreachable("bogus TLS model");
2969 }
2970 
2971 /// Return true if all users of V are within function F, looking through
2972 /// ConstantExprs.
2973 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2974   SmallVector<const User*,4> Worklist;
2975   for (auto *U : V->users())
2976     Worklist.push_back(U);
2977   while (!Worklist.empty()) {
2978     auto *U = Worklist.pop_back_val();
2979     if (isa<ConstantExpr>(U)) {
2980       for (auto *UU : U->users())
2981         Worklist.push_back(UU);
2982       continue;
2983     }
2984 
2985     auto *I = dyn_cast<Instruction>(U);
2986     if (!I || I->getParent()->getParent() != F)
2987       return false;
2988   }
2989   return true;
2990 }
2991 
2992 /// Return true if all users of V are within some (any) function, looking through
2993 /// ConstantExprs. In other words, are there any global constant users?
2994 static bool allUsersAreInFunctions(const Value *V) {
2995   SmallVector<const User*,4> Worklist;
2996   for (auto *U : V->users())
2997     Worklist.push_back(U);
2998   while (!Worklist.empty()) {
2999     auto *U = Worklist.pop_back_val();
3000     if (isa<ConstantExpr>(U)) {
3001       for (auto *UU : U->users())
3002         Worklist.push_back(UU);
3003       continue;
3004     }
3005 
3006     if (!isa<Instruction>(U))
3007       return false;
3008   }
3009   return true;
3010 }
3011 
3012 // Return true if T is an integer, float or an array/vector of either.
3013 static bool isSimpleType(Type *T) {
3014   if (T->isIntegerTy() || T->isFloatingPointTy())
3015     return true;
3016   Type *SubT = nullptr;
3017   if (T->isArrayTy())
3018     SubT = T->getArrayElementType();
3019   else if (T->isVectorTy())
3020     SubT = T->getVectorElementType();
3021   else
3022     return false;
3023   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3024 }
3025 
3026 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3027                                      EVT PtrVT, const SDLoc &dl) {
3028   // If we're creating a pool entry for a constant global with unnamed address,
3029   // and the global is small enough, we can emit it inline into the constant pool
3030   // to save ourselves an indirection.
3031   //
3032   // This is a win if the constant is only used in one function (so it doesn't
3033   // need to be duplicated) or duplicating the constant wouldn't increase code
3034   // size (implying the constant is no larger than 4 bytes).
3035   const Function *F = DAG.getMachineFunction().getFunction();
3036 
3037   // We rely on this decision to inline being idemopotent and unrelated to the
3038   // use-site. We know that if we inline a variable at one use site, we'll
3039   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3040   // doesn't know about this optimization, so bail out if it's enabled else
3041   // we could decide to inline here (and thus never emit the GV) but require
3042   // the GV from fast-isel generated code.
3043   if (!EnableConstpoolPromotion ||
3044       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3045       return SDValue();
3046 
3047   auto *GVar = dyn_cast<GlobalVariable>(GV);
3048   if (!GVar || !GVar->hasInitializer() ||
3049       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3050       !GVar->hasLocalLinkage())
3051     return SDValue();
3052 
3053   // Ensure that we don't try and inline any type that contains pointers. If
3054   // we inline a value that contains relocations, we move the relocations from
3055   // .data to .text which is not ideal.
3056   auto *Init = GVar->getInitializer();
3057   if (!isSimpleType(Init->getType()))
3058     return SDValue();
3059 
3060   // The constant islands pass can only really deal with alignment requests
3061   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3062   // any type wanting greater alignment requirements than 4 bytes. We also
3063   // can only promote constants that are multiples of 4 bytes in size or
3064   // are paddable to a multiple of 4. Currently we only try and pad constants
3065   // that are strings for simplicity.
3066   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3067   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3068   unsigned Align = GVar->getAlignment();
3069   unsigned RequiredPadding = 4 - (Size % 4);
3070   bool PaddingPossible =
3071     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3072   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3073       Size == 0)
3074     return SDValue();
3075 
3076   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3077   MachineFunction &MF = DAG.getMachineFunction();
3078   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3079 
3080   // We can't bloat the constant pool too much, else the ConstantIslands pass
3081   // may fail to converge. If we haven't promoted this global yet (it may have
3082   // multiple uses), and promoting it would increase the constant pool size (Sz
3083   // > 4), ensure we have space to do so up to MaxTotal.
3084   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3085     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3086         ConstpoolPromotionMaxTotal)
3087       return SDValue();
3088 
3089   // This is only valid if all users are in a single function OR it has users
3090   // in multiple functions but it no larger than a pointer. We also check if
3091   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3092   // address taken.
3093   if (!allUsersAreInFunction(GVar, F) &&
3094       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3095     return SDValue();
3096 
3097   // We're going to inline this global. Pad it out if needed.
3098   if (RequiredPadding != 4) {
3099     StringRef S = CDAInit->getAsString();
3100 
3101     SmallVector<uint8_t,16> V(S.size());
3102     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3103     while (RequiredPadding--)
3104       V.push_back(0);
3105     Init = ConstantDataArray::get(*DAG.getContext(), V);
3106   }
3107 
3108   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3109   SDValue CPAddr =
3110     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3111   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3112     AFI->markGlobalAsPromotedToConstantPool(GVar);
3113     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3114                                       PaddedSize - 4);
3115   }
3116   ++NumConstpoolPromoted;
3117   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3118 }
3119 
3120 static bool isReadOnly(const GlobalValue *GV) {
3121   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3122     GV = GA->getBaseObject();
3123   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3124          isa<Function>(GV);
3125 }
3126 
3127 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3128                                                  SelectionDAG &DAG) const {
3129   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3130   SDLoc dl(Op);
3131   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3132   const TargetMachine &TM = getTargetMachine();
3133   bool IsRO = isReadOnly(GV);
3134 
3135   // promoteToConstantPool only if not generating XO text section
3136   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3137     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3138       return V;
3139 
3140   if (isPositionIndependent()) {
3141     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3142 
3143     MachineFunction &MF = DAG.getMachineFunction();
3144     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3145     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3146     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3147     SDLoc dl(Op);
3148     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3149     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3150         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3151         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3152         /*AddCurrentAddress=*/UseGOT_PREL);
3153     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3154     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3155     SDValue Result = DAG.getLoad(
3156         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3157         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3158     SDValue Chain = Result.getValue(1);
3159     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3160     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3161     if (UseGOT_PREL)
3162       Result =
3163           DAG.getLoad(PtrVT, dl, Chain, Result,
3164                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3165     return Result;
3166   } else if (Subtarget->isROPI() && IsRO) {
3167     // PC-relative.
3168     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3169     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3170     return Result;
3171   } else if (Subtarget->isRWPI() && !IsRO) {
3172     // SB-relative.
3173     SDValue RelAddr;
3174     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3175       ++NumMovwMovt;
3176       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3177       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3178     } else { // use literal pool for address constant
3179       ARMConstantPoolValue *CPV =
3180         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3181       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3182       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3183       RelAddr = DAG.getLoad(
3184           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3185           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3186     }
3187     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3188     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3189     return Result;
3190   }
3191 
3192   // If we have T2 ops, we can materialize the address directly via movt/movw
3193   // pair. This is always cheaper.
3194   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3195     ++NumMovwMovt;
3196     // FIXME: Once remat is capable of dealing with instructions with register
3197     // operands, expand this into two nodes.
3198     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3199                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3200   } else {
3201     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3202     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3203     return DAG.getLoad(
3204         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3205         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3206   }
3207 }
3208 
3209 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3210                                                     SelectionDAG &DAG) const {
3211   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3212          "ROPI/RWPI not currently supported for Darwin");
3213   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3214   SDLoc dl(Op);
3215   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3216 
3217   if (Subtarget->useMovt(DAG.getMachineFunction()))
3218     ++NumMovwMovt;
3219 
3220   // FIXME: Once remat is capable of dealing with instructions with register
3221   // operands, expand this into multiple nodes
3222   unsigned Wrapper =
3223       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3224 
3225   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3226   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3227 
3228   if (Subtarget->isGVIndirectSymbol(GV))
3229     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3230                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3231   return Result;
3232 }
3233 
3234 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3235                                                      SelectionDAG &DAG) const {
3236   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3237   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3238          "Windows on ARM expects to use movw/movt");
3239   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3240          "ROPI/RWPI not currently supported for Windows");
3241 
3242   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3243   const ARMII::TOF TargetFlags =
3244     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3245   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3246   SDValue Result;
3247   SDLoc DL(Op);
3248 
3249   ++NumMovwMovt;
3250 
3251   // FIXME: Once remat is capable of dealing with instructions with register
3252   // operands, expand this into two nodes.
3253   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3254                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3255                                                   TargetFlags));
3256   if (GV->hasDLLImportStorageClass())
3257     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3258                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3259   return Result;
3260 }
3261 
3262 SDValue
3263 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3264   SDLoc dl(Op);
3265   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3266   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3267                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3268                      Op.getOperand(1), Val);
3269 }
3270 
3271 SDValue
3272 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3273   SDLoc dl(Op);
3274   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3275                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3276 }
3277 
3278 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3279                                                       SelectionDAG &DAG) const {
3280   SDLoc dl(Op);
3281   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3282                      Op.getOperand(0));
3283 }
3284 
3285 SDValue
3286 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3287                                           const ARMSubtarget *Subtarget) const {
3288   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3289   SDLoc dl(Op);
3290   switch (IntNo) {
3291   default: return SDValue();    // Don't custom lower most intrinsics.
3292   case Intrinsic::thread_pointer: {
3293     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3294     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3295   }
3296   case Intrinsic::eh_sjlj_lsda: {
3297     MachineFunction &MF = DAG.getMachineFunction();
3298     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3299     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3300     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3301     SDValue CPAddr;
3302     bool IsPositionIndependent = isPositionIndependent();
3303     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3304     ARMConstantPoolValue *CPV =
3305       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3306                                       ARMCP::CPLSDA, PCAdj);
3307     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3308     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3309     SDValue Result = DAG.getLoad(
3310         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3311         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3312 
3313     if (IsPositionIndependent) {
3314       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3315       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3316     }
3317     return Result;
3318   }
3319   case Intrinsic::arm_neon_vmulls:
3320   case Intrinsic::arm_neon_vmullu: {
3321     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3322       ? ARMISD::VMULLs : ARMISD::VMULLu;
3323     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3324                        Op.getOperand(1), Op.getOperand(2));
3325   }
3326   case Intrinsic::arm_neon_vminnm:
3327   case Intrinsic::arm_neon_vmaxnm: {
3328     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3329       ? ISD::FMINNUM : ISD::FMAXNUM;
3330     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3331                        Op.getOperand(1), Op.getOperand(2));
3332   }
3333   case Intrinsic::arm_neon_vminu:
3334   case Intrinsic::arm_neon_vmaxu: {
3335     if (Op.getValueType().isFloatingPoint())
3336       return SDValue();
3337     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3338       ? ISD::UMIN : ISD::UMAX;
3339     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3340                          Op.getOperand(1), Op.getOperand(2));
3341   }
3342   case Intrinsic::arm_neon_vmins:
3343   case Intrinsic::arm_neon_vmaxs: {
3344     // v{min,max}s is overloaded between signed integers and floats.
3345     if (!Op.getValueType().isFloatingPoint()) {
3346       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3347         ? ISD::SMIN : ISD::SMAX;
3348       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3349                          Op.getOperand(1), Op.getOperand(2));
3350     }
3351     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3352       ? ISD::FMINNAN : ISD::FMAXNAN;
3353     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3354                        Op.getOperand(1), Op.getOperand(2));
3355   }
3356   case Intrinsic::arm_neon_vtbl1:
3357     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3358                        Op.getOperand(1), Op.getOperand(2));
3359   case Intrinsic::arm_neon_vtbl2:
3360     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3361                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3362   }
3363 }
3364 
3365 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3366                                  const ARMSubtarget *Subtarget) {
3367   SDLoc dl(Op);
3368   ConstantSDNode *ScopeN = cast<ConstantSDNode>(Op.getOperand(2));
3369   auto Scope = static_cast<SynchronizationScope>(ScopeN->getZExtValue());
3370   if (Scope == SynchronizationScope::SingleThread)
3371     return Op;
3372 
3373   if (!Subtarget->hasDataBarrier()) {
3374     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3375     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3376     // here.
3377     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3378            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3379     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3380                        DAG.getConstant(0, dl, MVT::i32));
3381   }
3382 
3383   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3384   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3385   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3386   if (Subtarget->isMClass()) {
3387     // Only a full system barrier exists in the M-class architectures.
3388     Domain = ARM_MB::SY;
3389   } else if (Subtarget->preferISHSTBarriers() &&
3390              Ord == AtomicOrdering::Release) {
3391     // Swift happens to implement ISHST barriers in a way that's compatible with
3392     // Release semantics but weaker than ISH so we'd be fools not to use
3393     // it. Beware: other processors probably don't!
3394     Domain = ARM_MB::ISHST;
3395   }
3396 
3397   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3398                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3399                      DAG.getConstant(Domain, dl, MVT::i32));
3400 }
3401 
3402 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3403                              const ARMSubtarget *Subtarget) {
3404   // ARM pre v5TE and Thumb1 does not have preload instructions.
3405   if (!(Subtarget->isThumb2() ||
3406         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3407     // Just preserve the chain.
3408     return Op.getOperand(0);
3409 
3410   SDLoc dl(Op);
3411   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3412   if (!isRead &&
3413       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3414     // ARMv7 with MP extension has PLDW.
3415     return Op.getOperand(0);
3416 
3417   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3418   if (Subtarget->isThumb()) {
3419     // Invert the bits.
3420     isRead = ~isRead & 1;
3421     isData = ~isData & 1;
3422   }
3423 
3424   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3425                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3426                      DAG.getConstant(isData, dl, MVT::i32));
3427 }
3428 
3429 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3430   MachineFunction &MF = DAG.getMachineFunction();
3431   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3432 
3433   // vastart just stores the address of the VarArgsFrameIndex slot into the
3434   // memory location argument.
3435   SDLoc dl(Op);
3436   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3437   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3438   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3439   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3440                       MachinePointerInfo(SV));
3441 }
3442 
3443 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3444                                                 CCValAssign &NextVA,
3445                                                 SDValue &Root,
3446                                                 SelectionDAG &DAG,
3447                                                 const SDLoc &dl) const {
3448   MachineFunction &MF = DAG.getMachineFunction();
3449   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3450 
3451   const TargetRegisterClass *RC;
3452   if (AFI->isThumb1OnlyFunction())
3453     RC = &ARM::tGPRRegClass;
3454   else
3455     RC = &ARM::GPRRegClass;
3456 
3457   // Transform the arguments stored in physical registers into virtual ones.
3458   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3459   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3460 
3461   SDValue ArgValue2;
3462   if (NextVA.isMemLoc()) {
3463     MachineFrameInfo &MFI = MF.getFrameInfo();
3464     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3465 
3466     // Create load node to retrieve arguments from the stack.
3467     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3468     ArgValue2 = DAG.getLoad(
3469         MVT::i32, dl, Root, FIN,
3470         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3471   } else {
3472     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3473     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3474   }
3475   if (!Subtarget->isLittle())
3476     std::swap (ArgValue, ArgValue2);
3477   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3478 }
3479 
3480 // The remaining GPRs hold either the beginning of variable-argument
3481 // data, or the beginning of an aggregate passed by value (usually
3482 // byval).  Either way, we allocate stack slots adjacent to the data
3483 // provided by our caller, and store the unallocated registers there.
3484 // If this is a variadic function, the va_list pointer will begin with
3485 // these values; otherwise, this reassembles a (byval) structure that
3486 // was split between registers and memory.
3487 // Return: The frame index registers were stored into.
3488 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3489                                       const SDLoc &dl, SDValue &Chain,
3490                                       const Value *OrigArg,
3491                                       unsigned InRegsParamRecordIdx,
3492                                       int ArgOffset, unsigned ArgSize) const {
3493   // Currently, two use-cases possible:
3494   // Case #1. Non-var-args function, and we meet first byval parameter.
3495   //          Setup first unallocated register as first byval register;
3496   //          eat all remained registers
3497   //          (these two actions are performed by HandleByVal method).
3498   //          Then, here, we initialize stack frame with
3499   //          "store-reg" instructions.
3500   // Case #2. Var-args function, that doesn't contain byval parameters.
3501   //          The same: eat all remained unallocated registers,
3502   //          initialize stack frame.
3503 
3504   MachineFunction &MF = DAG.getMachineFunction();
3505   MachineFrameInfo &MFI = MF.getFrameInfo();
3506   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3507   unsigned RBegin, REnd;
3508   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3509     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3510   } else {
3511     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3512     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3513     REnd = ARM::R4;
3514   }
3515 
3516   if (REnd != RBegin)
3517     ArgOffset = -4 * (ARM::R4 - RBegin);
3518 
3519   auto PtrVT = getPointerTy(DAG.getDataLayout());
3520   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3521   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3522 
3523   SmallVector<SDValue, 4> MemOps;
3524   const TargetRegisterClass *RC =
3525       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3526 
3527   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3528     unsigned VReg = MF.addLiveIn(Reg, RC);
3529     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3530     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3531                                  MachinePointerInfo(OrigArg, 4 * i));
3532     MemOps.push_back(Store);
3533     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3534   }
3535 
3536   if (!MemOps.empty())
3537     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3538   return FrameIndex;
3539 }
3540 
3541 // Setup stack frame, the va_list pointer will start from.
3542 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3543                                              const SDLoc &dl, SDValue &Chain,
3544                                              unsigned ArgOffset,
3545                                              unsigned TotalArgRegsSaveSize,
3546                                              bool ForceMutable) const {
3547   MachineFunction &MF = DAG.getMachineFunction();
3548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3549 
3550   // Try to store any remaining integer argument regs
3551   // to their spots on the stack so that they may be loaded by dereferencing
3552   // the result of va_next.
3553   // If there is no regs to be stored, just point address after last
3554   // argument passed via stack.
3555   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3556                                   CCInfo.getInRegsParamsCount(),
3557                                   CCInfo.getNextStackOffset(), 4);
3558   AFI->setVarArgsFrameIndex(FrameIndex);
3559 }
3560 
3561 SDValue ARMTargetLowering::LowerFormalArguments(
3562     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3563     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3564     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3565   MachineFunction &MF = DAG.getMachineFunction();
3566   MachineFrameInfo &MFI = MF.getFrameInfo();
3567 
3568   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3569 
3570   // Assign locations to all of the incoming arguments.
3571   SmallVector<CCValAssign, 16> ArgLocs;
3572   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3573                  *DAG.getContext());
3574   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3575 
3576   SmallVector<SDValue, 16> ArgValues;
3577   SDValue ArgValue;
3578   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3579   unsigned CurArgIdx = 0;
3580 
3581   // Initially ArgRegsSaveSize is zero.
3582   // Then we increase this value each time we meet byval parameter.
3583   // We also increase this value in case of varargs function.
3584   AFI->setArgRegsSaveSize(0);
3585 
3586   // Calculate the amount of stack space that we need to allocate to store
3587   // byval and variadic arguments that are passed in registers.
3588   // We need to know this before we allocate the first byval or variadic
3589   // argument, as they will be allocated a stack slot below the CFA (Canonical
3590   // Frame Address, the stack pointer at entry to the function).
3591   unsigned ArgRegBegin = ARM::R4;
3592   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3593     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3594       break;
3595 
3596     CCValAssign &VA = ArgLocs[i];
3597     unsigned Index = VA.getValNo();
3598     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3599     if (!Flags.isByVal())
3600       continue;
3601 
3602     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3603     unsigned RBegin, REnd;
3604     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3605     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3606 
3607     CCInfo.nextInRegsParam();
3608   }
3609   CCInfo.rewindByValRegsInfo();
3610 
3611   int lastInsIndex = -1;
3612   if (isVarArg && MFI.hasVAStart()) {
3613     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3614     if (RegIdx != array_lengthof(GPRArgRegs))
3615       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3616   }
3617 
3618   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3619   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3620   auto PtrVT = getPointerTy(DAG.getDataLayout());
3621 
3622   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3623     CCValAssign &VA = ArgLocs[i];
3624     if (Ins[VA.getValNo()].isOrigArg()) {
3625       std::advance(CurOrigArg,
3626                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3627       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3628     }
3629     // Arguments stored in registers.
3630     if (VA.isRegLoc()) {
3631       EVT RegVT = VA.getLocVT();
3632 
3633       if (VA.needsCustom()) {
3634         // f64 and vector types are split up into multiple registers or
3635         // combinations of registers and stack slots.
3636         if (VA.getLocVT() == MVT::v2f64) {
3637           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3638                                                    Chain, DAG, dl);
3639           VA = ArgLocs[++i]; // skip ahead to next loc
3640           SDValue ArgValue2;
3641           if (VA.isMemLoc()) {
3642             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3643             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3644             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3645                                     MachinePointerInfo::getFixedStack(
3646                                         DAG.getMachineFunction(), FI));
3647           } else {
3648             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3649                                              Chain, DAG, dl);
3650           }
3651           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3652           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3653                                  ArgValue, ArgValue1,
3654                                  DAG.getIntPtrConstant(0, dl));
3655           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3656                                  ArgValue, ArgValue2,
3657                                  DAG.getIntPtrConstant(1, dl));
3658         } else
3659           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3660 
3661       } else {
3662         const TargetRegisterClass *RC;
3663 
3664         if (RegVT == MVT::f32)
3665           RC = &ARM::SPRRegClass;
3666         else if (RegVT == MVT::f64)
3667           RC = &ARM::DPRRegClass;
3668         else if (RegVT == MVT::v2f64)
3669           RC = &ARM::QPRRegClass;
3670         else if (RegVT == MVT::i32)
3671           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3672                                            : &ARM::GPRRegClass;
3673         else
3674           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3675 
3676         // Transform the arguments in physical registers into virtual ones.
3677         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3678         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3679       }
3680 
3681       // If this is an 8 or 16-bit value, it is really passed promoted
3682       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3683       // truncate to the right size.
3684       switch (VA.getLocInfo()) {
3685       default: llvm_unreachable("Unknown loc info!");
3686       case CCValAssign::Full: break;
3687       case CCValAssign::BCvt:
3688         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3689         break;
3690       case CCValAssign::SExt:
3691         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3692                                DAG.getValueType(VA.getValVT()));
3693         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3694         break;
3695       case CCValAssign::ZExt:
3696         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3697                                DAG.getValueType(VA.getValVT()));
3698         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3699         break;
3700       }
3701 
3702       InVals.push_back(ArgValue);
3703 
3704     } else { // VA.isRegLoc()
3705       // sanity check
3706       assert(VA.isMemLoc());
3707       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3708 
3709       int index = VA.getValNo();
3710 
3711       // Some Ins[] entries become multiple ArgLoc[] entries.
3712       // Process them only once.
3713       if (index != lastInsIndex)
3714         {
3715           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3716           // FIXME: For now, all byval parameter objects are marked mutable.
3717           // This can be changed with more analysis.
3718           // In case of tail call optimization mark all arguments mutable.
3719           // Since they could be overwritten by lowering of arguments in case of
3720           // a tail call.
3721           if (Flags.isByVal()) {
3722             assert(Ins[index].isOrigArg() &&
3723                    "Byval arguments cannot be implicit");
3724             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3725 
3726             int FrameIndex = StoreByValRegs(
3727                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3728                 VA.getLocMemOffset(), Flags.getByValSize());
3729             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3730             CCInfo.nextInRegsParam();
3731           } else {
3732             unsigned FIOffset = VA.getLocMemOffset();
3733             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3734                                            FIOffset, true);
3735 
3736             // Create load nodes to retrieve arguments from the stack.
3737             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3738             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3739                                          MachinePointerInfo::getFixedStack(
3740                                              DAG.getMachineFunction(), FI)));
3741           }
3742           lastInsIndex = index;
3743         }
3744     }
3745   }
3746 
3747   // varargs
3748   if (isVarArg && MFI.hasVAStart())
3749     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3750                          CCInfo.getNextStackOffset(),
3751                          TotalArgRegsSaveSize);
3752 
3753   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3754 
3755   return Chain;
3756 }
3757 
3758 /// isFloatingPointZero - Return true if this is +0.0.
3759 static bool isFloatingPointZero(SDValue Op) {
3760   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3761     return CFP->getValueAPF().isPosZero();
3762   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3763     // Maybe this has already been legalized into the constant pool?
3764     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3765       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3766       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3767         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3768           return CFP->getValueAPF().isPosZero();
3769     }
3770   } else if (Op->getOpcode() == ISD::BITCAST &&
3771              Op->getValueType(0) == MVT::f64) {
3772     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3773     // created by LowerConstantFP().
3774     SDValue BitcastOp = Op->getOperand(0);
3775     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3776         isNullConstant(BitcastOp->getOperand(0)))
3777       return true;
3778   }
3779   return false;
3780 }
3781 
3782 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3783 /// the given operands.
3784 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3785                                      SDValue &ARMcc, SelectionDAG &DAG,
3786                                      const SDLoc &dl) const {
3787   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3788     unsigned C = RHSC->getZExtValue();
3789     if (!isLegalICmpImmediate(C)) {
3790       // Constant does not fit, try adjusting it by one?
3791       switch (CC) {
3792       default: break;
3793       case ISD::SETLT:
3794       case ISD::SETGE:
3795         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3796           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3797           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3798         }
3799         break;
3800       case ISD::SETULT:
3801       case ISD::SETUGE:
3802         if (C != 0 && isLegalICmpImmediate(C-1)) {
3803           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3804           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3805         }
3806         break;
3807       case ISD::SETLE:
3808       case ISD::SETGT:
3809         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3810           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3811           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3812         }
3813         break;
3814       case ISD::SETULE:
3815       case ISD::SETUGT:
3816         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3817           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3818           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3819         }
3820         break;
3821       }
3822     }
3823   }
3824 
3825   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3826   ARMISD::NodeType CompareType;
3827   switch (CondCode) {
3828   default:
3829     CompareType = ARMISD::CMP;
3830     break;
3831   case ARMCC::EQ:
3832   case ARMCC::NE:
3833     // Uses only Z Flag
3834     CompareType = ARMISD::CMPZ;
3835     break;
3836   }
3837   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3838   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3839 }
3840 
3841 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3842 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3843                                      SelectionDAG &DAG, const SDLoc &dl,
3844                                      bool InvalidOnQNaN) const {
3845   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3846   SDValue Cmp;
3847   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3848   if (!isFloatingPointZero(RHS))
3849     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3850   else
3851     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3852   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3853 }
3854 
3855 /// duplicateCmp - Glue values can have only one use, so this function
3856 /// duplicates a comparison node.
3857 SDValue
3858 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3859   unsigned Opc = Cmp.getOpcode();
3860   SDLoc DL(Cmp);
3861   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3862     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3863 
3864   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3865   Cmp = Cmp.getOperand(0);
3866   Opc = Cmp.getOpcode();
3867   if (Opc == ARMISD::CMPFP)
3868     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3869                       Cmp.getOperand(1), Cmp.getOperand(2));
3870   else {
3871     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3872     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3873                       Cmp.getOperand(1));
3874   }
3875   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3876 }
3877 
3878 std::pair<SDValue, SDValue>
3879 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3880                                  SDValue &ARMcc) const {
3881   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3882 
3883   SDValue Value, OverflowCmp;
3884   SDValue LHS = Op.getOperand(0);
3885   SDValue RHS = Op.getOperand(1);
3886   SDLoc dl(Op);
3887 
3888   // FIXME: We are currently always generating CMPs because we don't support
3889   // generating CMN through the backend. This is not as good as the natural
3890   // CMP case because it causes a register dependency and cannot be folded
3891   // later.
3892 
3893   switch (Op.getOpcode()) {
3894   default:
3895     llvm_unreachable("Unknown overflow instruction!");
3896   case ISD::SADDO:
3897     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3898     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3899     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3900     break;
3901   case ISD::UADDO:
3902     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3903     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3904     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3905     break;
3906   case ISD::SSUBO:
3907     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3908     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3909     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3910     break;
3911   case ISD::USUBO:
3912     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3913     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3914     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3915     break;
3916   } // switch (...)
3917 
3918   return std::make_pair(Value, OverflowCmp);
3919 }
3920 
3921 SDValue
3922 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3923   // Let legalize expand this if it isn't a legal type yet.
3924   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3925     return SDValue();
3926 
3927   SDValue Value, OverflowCmp;
3928   SDValue ARMcc;
3929   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3930   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3931   SDLoc dl(Op);
3932   // We use 0 and 1 as false and true values.
3933   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3934   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3935   EVT VT = Op.getValueType();
3936 
3937   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3938                                  ARMcc, CCR, OverflowCmp);
3939 
3940   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3941   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3942 }
3943 
3944 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3945   SDValue Cond = Op.getOperand(0);
3946   SDValue SelectTrue = Op.getOperand(1);
3947   SDValue SelectFalse = Op.getOperand(2);
3948   SDLoc dl(Op);
3949   unsigned Opc = Cond.getOpcode();
3950 
3951   if (Cond.getResNo() == 1 &&
3952       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3953        Opc == ISD::USUBO)) {
3954     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3955       return SDValue();
3956 
3957     SDValue Value, OverflowCmp;
3958     SDValue ARMcc;
3959     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3960     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3961     EVT VT = Op.getValueType();
3962 
3963     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3964                    OverflowCmp, DAG);
3965   }
3966 
3967   // Convert:
3968   //
3969   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3970   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3971   //
3972   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3973     const ConstantSDNode *CMOVTrue =
3974       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3975     const ConstantSDNode *CMOVFalse =
3976       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3977 
3978     if (CMOVTrue && CMOVFalse) {
3979       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3980       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3981 
3982       SDValue True;
3983       SDValue False;
3984       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3985         True = SelectTrue;
3986         False = SelectFalse;
3987       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3988         True = SelectFalse;
3989         False = SelectTrue;
3990       }
3991 
3992       if (True.getNode() && False.getNode()) {
3993         EVT VT = Op.getValueType();
3994         SDValue ARMcc = Cond.getOperand(2);
3995         SDValue CCR = Cond.getOperand(3);
3996         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3997         assert(True.getValueType() == VT);
3998         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3999       }
4000     }
4001   }
4002 
4003   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4004   // undefined bits before doing a full-word comparison with zero.
4005   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4006                      DAG.getConstant(1, dl, Cond.getValueType()));
4007 
4008   return DAG.getSelectCC(dl, Cond,
4009                          DAG.getConstant(0, dl, Cond.getValueType()),
4010                          SelectTrue, SelectFalse, ISD::SETNE);
4011 }
4012 
4013 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4014                                  bool &swpCmpOps, bool &swpVselOps) {
4015   // Start by selecting the GE condition code for opcodes that return true for
4016   // 'equality'
4017   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4018       CC == ISD::SETULE)
4019     CondCode = ARMCC::GE;
4020 
4021   // and GT for opcodes that return false for 'equality'.
4022   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4023            CC == ISD::SETULT)
4024     CondCode = ARMCC::GT;
4025 
4026   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4027   // to swap the compare operands.
4028   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4029       CC == ISD::SETULT)
4030     swpCmpOps = true;
4031 
4032   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4033   // If we have an unordered opcode, we need to swap the operands to the VSEL
4034   // instruction (effectively negating the condition).
4035   //
4036   // This also has the effect of swapping which one of 'less' or 'greater'
4037   // returns true, so we also swap the compare operands. It also switches
4038   // whether we return true for 'equality', so we compensate by picking the
4039   // opposite condition code to our original choice.
4040   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4041       CC == ISD::SETUGT) {
4042     swpCmpOps = !swpCmpOps;
4043     swpVselOps = !swpVselOps;
4044     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4045   }
4046 
4047   // 'ordered' is 'anything but unordered', so use the VS condition code and
4048   // swap the VSEL operands.
4049   if (CC == ISD::SETO) {
4050     CondCode = ARMCC::VS;
4051     swpVselOps = true;
4052   }
4053 
4054   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4055   // code and swap the VSEL operands.
4056   if (CC == ISD::SETUNE) {
4057     CondCode = ARMCC::EQ;
4058     swpVselOps = true;
4059   }
4060 }
4061 
4062 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4063                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4064                                    SDValue Cmp, SelectionDAG &DAG) const {
4065   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4066     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4067                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4068     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4069                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4070 
4071     SDValue TrueLow = TrueVal.getValue(0);
4072     SDValue TrueHigh = TrueVal.getValue(1);
4073     SDValue FalseLow = FalseVal.getValue(0);
4074     SDValue FalseHigh = FalseVal.getValue(1);
4075 
4076     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4077                               ARMcc, CCR, Cmp);
4078     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4079                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4080 
4081     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4082   } else {
4083     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4084                        Cmp);
4085   }
4086 }
4087 
4088 static bool isGTorGE(ISD::CondCode CC) {
4089   return CC == ISD::SETGT || CC == ISD::SETGE;
4090 }
4091 
4092 static bool isLTorLE(ISD::CondCode CC) {
4093   return CC == ISD::SETLT || CC == ISD::SETLE;
4094 }
4095 
4096 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4097 // All of these conditions (and their <= and >= counterparts) will do:
4098 //          x < k ? k : x
4099 //          x > k ? x : k
4100 //          k < x ? x : k
4101 //          k > x ? k : x
4102 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4103                             const SDValue TrueVal, const SDValue FalseVal,
4104                             const ISD::CondCode CC, const SDValue K) {
4105   return (isGTorGE(CC) &&
4106           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4107          (isLTorLE(CC) &&
4108           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4109 }
4110 
4111 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4112 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4113                             const SDValue TrueVal, const SDValue FalseVal,
4114                             const ISD::CondCode CC, const SDValue K) {
4115   return (isGTorGE(CC) &&
4116           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4117          (isLTorLE(CC) &&
4118           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4119 }
4120 
4121 // Check if two chained conditionals could be converted into SSAT.
4122 //
4123 // SSAT can replace a set of two conditional selectors that bound a number to an
4124 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4125 //
4126 //     x < -k ? -k : (x > k ? k : x)
4127 //     x < -k ? -k : (x < k ? x : k)
4128 //     x > -k ? (x > k ? k : x) : -k
4129 //     x < k ? (x < -k ? -k : x) : k
4130 //     etc.
4131 //
4132 // It returns true if the conversion can be done, false otherwise.
4133 // Additionally, the variable is returned in parameter V and the constant in K.
4134 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4135                                     uint64_t &K) {
4136   SDValue LHS1 = Op.getOperand(0);
4137   SDValue RHS1 = Op.getOperand(1);
4138   SDValue TrueVal1 = Op.getOperand(2);
4139   SDValue FalseVal1 = Op.getOperand(3);
4140   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4141 
4142   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4143   if (Op2.getOpcode() != ISD::SELECT_CC)
4144     return false;
4145 
4146   SDValue LHS2 = Op2.getOperand(0);
4147   SDValue RHS2 = Op2.getOperand(1);
4148   SDValue TrueVal2 = Op2.getOperand(2);
4149   SDValue FalseVal2 = Op2.getOperand(3);
4150   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4151 
4152   // Find out which are the constants and which are the variables
4153   // in each conditional
4154   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4155                                                         ? &RHS1
4156                                                         : nullptr;
4157   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4158                                                         ? &RHS2
4159                                                         : nullptr;
4160   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4161   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4162   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4163   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4164 
4165   // We must detect cases where the original operations worked with 16- or
4166   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4167   // must work with sign-extended values but the select operations return
4168   // the original non-extended value.
4169   SDValue V2TmpReg = V2Tmp;
4170   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4171     V2TmpReg = V2Tmp->getOperand(0);
4172 
4173   // Check that the registers and the constants have the correct values
4174   // in both conditionals
4175   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4176       V2TmpReg != V2)
4177     return false;
4178 
4179   // Figure out which conditional is saturating the lower/upper bound.
4180   const SDValue *LowerCheckOp =
4181       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4182           ? &Op
4183           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4184                 ? &Op2
4185                 : nullptr;
4186   const SDValue *UpperCheckOp =
4187       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4188           ? &Op
4189           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4190                 ? &Op2
4191                 : nullptr;
4192 
4193   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4194     return false;
4195 
4196   // Check that the constant in the lower-bound check is
4197   // the opposite of the constant in the upper-bound check
4198   // in 1's complement.
4199   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4200   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4201   int64_t PosVal = std::max(Val1, Val2);
4202 
4203   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4204        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4205       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4206 
4207     V = V2;
4208     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4209     return true;
4210   }
4211 
4212   return false;
4213 }
4214 
4215 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4216   EVT VT = Op.getValueType();
4217   SDLoc dl(Op);
4218 
4219   // Try to convert two saturating conditional selects into a single SSAT
4220   SDValue SatValue;
4221   uint64_t SatConstant;
4222   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4223       isSaturatingConditional(Op, SatValue, SatConstant))
4224     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4225                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4226 
4227   SDValue LHS = Op.getOperand(0);
4228   SDValue RHS = Op.getOperand(1);
4229   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4230   SDValue TrueVal = Op.getOperand(2);
4231   SDValue FalseVal = Op.getOperand(3);
4232 
4233   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4234     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4235                                                     dl);
4236 
4237     // If softenSetCCOperands only returned one value, we should compare it to
4238     // zero.
4239     if (!RHS.getNode()) {
4240       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4241       CC = ISD::SETNE;
4242     }
4243   }
4244 
4245   if (LHS.getValueType() == MVT::i32) {
4246     // Try to generate VSEL on ARMv8.
4247     // The VSEL instruction can't use all the usual ARM condition
4248     // codes: it only has two bits to select the condition code, so it's
4249     // constrained to use only GE, GT, VS and EQ.
4250     //
4251     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4252     // swap the operands of the previous compare instruction (effectively
4253     // inverting the compare condition, swapping 'less' and 'greater') and
4254     // sometimes need to swap the operands to the VSEL (which inverts the
4255     // condition in the sense of firing whenever the previous condition didn't)
4256     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4257                                     TrueVal.getValueType() == MVT::f64)) {
4258       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4259       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4260           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4261         CC = ISD::getSetCCInverse(CC, true);
4262         std::swap(TrueVal, FalseVal);
4263       }
4264     }
4265 
4266     SDValue ARMcc;
4267     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4268     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4269     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4270   }
4271 
4272   ARMCC::CondCodes CondCode, CondCode2;
4273   bool InvalidOnQNaN;
4274   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4275 
4276   // Try to generate VMAXNM/VMINNM on ARMv8.
4277   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4278                                   TrueVal.getValueType() == MVT::f64)) {
4279     bool swpCmpOps = false;
4280     bool swpVselOps = false;
4281     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4282 
4283     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4284         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4285       if (swpCmpOps)
4286         std::swap(LHS, RHS);
4287       if (swpVselOps)
4288         std::swap(TrueVal, FalseVal);
4289     }
4290   }
4291 
4292   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4293   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4294   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4295   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4296   if (CondCode2 != ARMCC::AL) {
4297     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4298     // FIXME: Needs another CMP because flag can have but one use.
4299     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4300     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4301   }
4302   return Result;
4303 }
4304 
4305 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4306 /// to morph to an integer compare sequence.
4307 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4308                            const ARMSubtarget *Subtarget) {
4309   SDNode *N = Op.getNode();
4310   if (!N->hasOneUse())
4311     // Otherwise it requires moving the value from fp to integer registers.
4312     return false;
4313   if (!N->getNumValues())
4314     return false;
4315   EVT VT = Op.getValueType();
4316   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4317     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4318     // vmrs are very slow, e.g. cortex-a8.
4319     return false;
4320 
4321   if (isFloatingPointZero(Op)) {
4322     SeenZero = true;
4323     return true;
4324   }
4325   return ISD::isNormalLoad(N);
4326 }
4327 
4328 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4329   if (isFloatingPointZero(Op))
4330     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4331 
4332   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4333     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4334                        Ld->getPointerInfo(), Ld->getAlignment(),
4335                        Ld->getMemOperand()->getFlags());
4336 
4337   llvm_unreachable("Unknown VFP cmp argument!");
4338 }
4339 
4340 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4341                            SDValue &RetVal1, SDValue &RetVal2) {
4342   SDLoc dl(Op);
4343 
4344   if (isFloatingPointZero(Op)) {
4345     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4346     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4347     return;
4348   }
4349 
4350   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4351     SDValue Ptr = Ld->getBasePtr();
4352     RetVal1 =
4353         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4354                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4355 
4356     EVT PtrType = Ptr.getValueType();
4357     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4358     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4359                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4360     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4361                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4362                           Ld->getMemOperand()->getFlags());
4363     return;
4364   }
4365 
4366   llvm_unreachable("Unknown VFP cmp argument!");
4367 }
4368 
4369 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4370 /// f32 and even f64 comparisons to integer ones.
4371 SDValue
4372 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4373   SDValue Chain = Op.getOperand(0);
4374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4375   SDValue LHS = Op.getOperand(2);
4376   SDValue RHS = Op.getOperand(3);
4377   SDValue Dest = Op.getOperand(4);
4378   SDLoc dl(Op);
4379 
4380   bool LHSSeenZero = false;
4381   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4382   bool RHSSeenZero = false;
4383   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4384   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4385     // If unsafe fp math optimization is enabled and there are no other uses of
4386     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4387     // to an integer comparison.
4388     if (CC == ISD::SETOEQ)
4389       CC = ISD::SETEQ;
4390     else if (CC == ISD::SETUNE)
4391       CC = ISD::SETNE;
4392 
4393     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4394     SDValue ARMcc;
4395     if (LHS.getValueType() == MVT::f32) {
4396       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4397                         bitcastf32Toi32(LHS, DAG), Mask);
4398       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4399                         bitcastf32Toi32(RHS, DAG), Mask);
4400       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4401       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4402       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4403                          Chain, Dest, ARMcc, CCR, Cmp);
4404     }
4405 
4406     SDValue LHS1, LHS2;
4407     SDValue RHS1, RHS2;
4408     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4409     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4410     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4411     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4412     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4413     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4414     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4415     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4416     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4417   }
4418 
4419   return SDValue();
4420 }
4421 
4422 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4423   SDValue Chain = Op.getOperand(0);
4424   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4425   SDValue LHS = Op.getOperand(2);
4426   SDValue RHS = Op.getOperand(3);
4427   SDValue Dest = Op.getOperand(4);
4428   SDLoc dl(Op);
4429 
4430   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4431     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4432                                                     dl);
4433 
4434     // If softenSetCCOperands only returned one value, we should compare it to
4435     // zero.
4436     if (!RHS.getNode()) {
4437       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4438       CC = ISD::SETNE;
4439     }
4440   }
4441 
4442   if (LHS.getValueType() == MVT::i32) {
4443     SDValue ARMcc;
4444     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4445     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4446     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4447                        Chain, Dest, ARMcc, CCR, Cmp);
4448   }
4449 
4450   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4451 
4452   if (getTargetMachine().Options.UnsafeFPMath &&
4453       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4454        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4455     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4456       return Result;
4457   }
4458 
4459   ARMCC::CondCodes CondCode, CondCode2;
4460   bool InvalidOnQNaN;
4461   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4462 
4463   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4464   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4465   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4466   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4467   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4468   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4469   if (CondCode2 != ARMCC::AL) {
4470     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4471     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4472     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4473   }
4474   return Res;
4475 }
4476 
4477 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4478   SDValue Chain = Op.getOperand(0);
4479   SDValue Table = Op.getOperand(1);
4480   SDValue Index = Op.getOperand(2);
4481   SDLoc dl(Op);
4482 
4483   EVT PTy = getPointerTy(DAG.getDataLayout());
4484   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4485   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4486   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4487   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4488   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4489   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4490     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4491     // which does another jump to the destination. This also makes it easier
4492     // to translate it to TBB / TBH later (Thumb2 only).
4493     // FIXME: This might not work if the function is extremely large.
4494     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4495                        Addr, Op.getOperand(2), JTI);
4496   }
4497   if (isPositionIndependent() || Subtarget->isROPI()) {
4498     Addr =
4499         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4500                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4501     Chain = Addr.getValue(1);
4502     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4503     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4504   } else {
4505     Addr =
4506         DAG.getLoad(PTy, dl, Chain, Addr,
4507                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4508     Chain = Addr.getValue(1);
4509     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4510   }
4511 }
4512 
4513 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4514   EVT VT = Op.getValueType();
4515   SDLoc dl(Op);
4516 
4517   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4518     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4519       return Op;
4520     return DAG.UnrollVectorOp(Op.getNode());
4521   }
4522 
4523   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4524          "Invalid type for custom lowering!");
4525   if (VT != MVT::v4i16)
4526     return DAG.UnrollVectorOp(Op.getNode());
4527 
4528   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4529   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4530 }
4531 
4532 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4533   EVT VT = Op.getValueType();
4534   if (VT.isVector())
4535     return LowerVectorFP_TO_INT(Op, DAG);
4536   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4537     RTLIB::Libcall LC;
4538     if (Op.getOpcode() == ISD::FP_TO_SINT)
4539       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4540                               Op.getValueType());
4541     else
4542       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4543                               Op.getValueType());
4544     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4545                        /*isSigned*/ false, SDLoc(Op)).first;
4546   }
4547 
4548   return Op;
4549 }
4550 
4551 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4552   EVT VT = Op.getValueType();
4553   SDLoc dl(Op);
4554 
4555   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4556     if (VT.getVectorElementType() == MVT::f32)
4557       return Op;
4558     return DAG.UnrollVectorOp(Op.getNode());
4559   }
4560 
4561   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4562          "Invalid type for custom lowering!");
4563   if (VT != MVT::v4f32)
4564     return DAG.UnrollVectorOp(Op.getNode());
4565 
4566   unsigned CastOpc;
4567   unsigned Opc;
4568   switch (Op.getOpcode()) {
4569   default: llvm_unreachable("Invalid opcode!");
4570   case ISD::SINT_TO_FP:
4571     CastOpc = ISD::SIGN_EXTEND;
4572     Opc = ISD::SINT_TO_FP;
4573     break;
4574   case ISD::UINT_TO_FP:
4575     CastOpc = ISD::ZERO_EXTEND;
4576     Opc = ISD::UINT_TO_FP;
4577     break;
4578   }
4579 
4580   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4581   return DAG.getNode(Opc, dl, VT, Op);
4582 }
4583 
4584 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4585   EVT VT = Op.getValueType();
4586   if (VT.isVector())
4587     return LowerVectorINT_TO_FP(Op, DAG);
4588   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4589     RTLIB::Libcall LC;
4590     if (Op.getOpcode() == ISD::SINT_TO_FP)
4591       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4592                               Op.getValueType());
4593     else
4594       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4595                               Op.getValueType());
4596     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4597                        /*isSigned*/ false, SDLoc(Op)).first;
4598   }
4599 
4600   return Op;
4601 }
4602 
4603 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4604   // Implement fcopysign with a fabs and a conditional fneg.
4605   SDValue Tmp0 = Op.getOperand(0);
4606   SDValue Tmp1 = Op.getOperand(1);
4607   SDLoc dl(Op);
4608   EVT VT = Op.getValueType();
4609   EVT SrcVT = Tmp1.getValueType();
4610   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4611     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4612   bool UseNEON = !InGPR && Subtarget->hasNEON();
4613 
4614   if (UseNEON) {
4615     // Use VBSL to copy the sign bit.
4616     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4617     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4618                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4619     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4620     if (VT == MVT::f64)
4621       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4622                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4623                          DAG.getConstant(32, dl, MVT::i32));
4624     else /*if (VT == MVT::f32)*/
4625       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4626     if (SrcVT == MVT::f32) {
4627       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4628       if (VT == MVT::f64)
4629         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4630                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4631                            DAG.getConstant(32, dl, MVT::i32));
4632     } else if (VT == MVT::f32)
4633       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4634                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4635                          DAG.getConstant(32, dl, MVT::i32));
4636     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4637     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4638 
4639     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4640                                             dl, MVT::i32);
4641     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4642     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4643                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4644 
4645     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4646                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4647                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4648     if (VT == MVT::f32) {
4649       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4650       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4651                         DAG.getConstant(0, dl, MVT::i32));
4652     } else {
4653       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4654     }
4655 
4656     return Res;
4657   }
4658 
4659   // Bitcast operand 1 to i32.
4660   if (SrcVT == MVT::f64)
4661     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4662                        Tmp1).getValue(1);
4663   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4664 
4665   // Or in the signbit with integer operations.
4666   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4667   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4668   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4669   if (VT == MVT::f32) {
4670     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4671                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4672     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4673                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4674   }
4675 
4676   // f64: Or the high part with signbit and then combine two parts.
4677   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4678                      Tmp0);
4679   SDValue Lo = Tmp0.getValue(0);
4680   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4681   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4682   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4683 }
4684 
4685 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4686   MachineFunction &MF = DAG.getMachineFunction();
4687   MachineFrameInfo &MFI = MF.getFrameInfo();
4688   MFI.setReturnAddressIsTaken(true);
4689 
4690   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4691     return SDValue();
4692 
4693   EVT VT = Op.getValueType();
4694   SDLoc dl(Op);
4695   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4696   if (Depth) {
4697     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4698     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4699     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4700                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4701                        MachinePointerInfo());
4702   }
4703 
4704   // Return LR, which contains the return address. Mark it an implicit live-in.
4705   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4706   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4707 }
4708 
4709 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4710   const ARMBaseRegisterInfo &ARI =
4711     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4712   MachineFunction &MF = DAG.getMachineFunction();
4713   MachineFrameInfo &MFI = MF.getFrameInfo();
4714   MFI.setFrameAddressIsTaken(true);
4715 
4716   EVT VT = Op.getValueType();
4717   SDLoc dl(Op);  // FIXME probably not meaningful
4718   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4719   unsigned FrameReg = ARI.getFrameRegister(MF);
4720   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4721   while (Depth--)
4722     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4723                             MachinePointerInfo());
4724   return FrameAddr;
4725 }
4726 
4727 // FIXME? Maybe this could be a TableGen attribute on some registers and
4728 // this table could be generated automatically from RegInfo.
4729 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4730                                               SelectionDAG &DAG) const {
4731   unsigned Reg = StringSwitch<unsigned>(RegName)
4732                        .Case("sp", ARM::SP)
4733                        .Default(0);
4734   if (Reg)
4735     return Reg;
4736   report_fatal_error(Twine("Invalid register name \""
4737                               + StringRef(RegName)  + "\"."));
4738 }
4739 
4740 // Result is 64 bit value so split into two 32 bit values and return as a
4741 // pair of values.
4742 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4743                                 SelectionDAG &DAG) {
4744   SDLoc DL(N);
4745 
4746   // This function is only supposed to be called for i64 type destination.
4747   assert(N->getValueType(0) == MVT::i64
4748           && "ExpandREAD_REGISTER called for non-i64 type result.");
4749 
4750   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4751                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4752                              N->getOperand(0),
4753                              N->getOperand(1));
4754 
4755   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4756                     Read.getValue(1)));
4757   Results.push_back(Read.getOperand(0));
4758 }
4759 
4760 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4761 /// When \p DstVT, the destination type of \p BC, is on the vector
4762 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4763 /// it might be possible to combine them, such that everything stays on the
4764 /// vector register bank.
4765 /// \p return The node that would replace \p BT, if the combine
4766 /// is possible.
4767 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4768                                                 SelectionDAG &DAG) {
4769   SDValue Op = BC->getOperand(0);
4770   EVT DstVT = BC->getValueType(0);
4771 
4772   // The only vector instruction that can produce a scalar (remember,
4773   // since the bitcast was about to be turned into VMOVDRR, the source
4774   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4775   // Moreover, we can do this combine only if there is one use.
4776   // Finally, if the destination type is not a vector, there is not
4777   // much point on forcing everything on the vector bank.
4778   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4779       !Op.hasOneUse())
4780     return SDValue();
4781 
4782   // If the index is not constant, we will introduce an additional
4783   // multiply that will stick.
4784   // Give up in that case.
4785   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4786   if (!Index)
4787     return SDValue();
4788   unsigned DstNumElt = DstVT.getVectorNumElements();
4789 
4790   // Compute the new index.
4791   const APInt &APIntIndex = Index->getAPIntValue();
4792   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4793   NewIndex *= APIntIndex;
4794   // Check if the new constant index fits into i32.
4795   if (NewIndex.getBitWidth() > 32)
4796     return SDValue();
4797 
4798   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4799   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4800   SDLoc dl(Op);
4801   SDValue ExtractSrc = Op.getOperand(0);
4802   EVT VecVT = EVT::getVectorVT(
4803       *DAG.getContext(), DstVT.getScalarType(),
4804       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4805   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4806   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4807                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4808 }
4809 
4810 /// ExpandBITCAST - If the target supports VFP, this function is called to
4811 /// expand a bit convert where either the source or destination type is i64 to
4812 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4813 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4814 /// vectors), since the legalizer won't know what to do with that.
4815 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4817   SDLoc dl(N);
4818   SDValue Op = N->getOperand(0);
4819 
4820   // This function is only supposed to be called for i64 types, either as the
4821   // source or destination of the bit convert.
4822   EVT SrcVT = Op.getValueType();
4823   EVT DstVT = N->getValueType(0);
4824   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4825          "ExpandBITCAST called for non-i64 type");
4826 
4827   // Turn i64->f64 into VMOVDRR.
4828   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4829     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4830     // if we can combine the bitcast with its source.
4831     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4832       return Val;
4833 
4834     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4835                              DAG.getConstant(0, dl, MVT::i32));
4836     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4837                              DAG.getConstant(1, dl, MVT::i32));
4838     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4839                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4840   }
4841 
4842   // Turn f64->i64 into VMOVRRD.
4843   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4844     SDValue Cvt;
4845     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4846         SrcVT.getVectorNumElements() > 1)
4847       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4848                         DAG.getVTList(MVT::i32, MVT::i32),
4849                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4850     else
4851       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4852                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4853     // Merge the pieces into a single i64 value.
4854     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4855   }
4856 
4857   return SDValue();
4858 }
4859 
4860 /// getZeroVector - Returns a vector of specified type with all zero elements.
4861 /// Zero vectors are used to represent vector negation and in those cases
4862 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4863 /// not support i64 elements, so sometimes the zero vectors will need to be
4864 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4865 /// zero vector.
4866 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4867   assert(VT.isVector() && "Expected a vector type");
4868   // The canonical modified immediate encoding of a zero vector is....0!
4869   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4870   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4871   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4872   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4873 }
4874 
4875 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4876 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4877 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4878                                                 SelectionDAG &DAG) const {
4879   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4880   EVT VT = Op.getValueType();
4881   unsigned VTBits = VT.getSizeInBits();
4882   SDLoc dl(Op);
4883   SDValue ShOpLo = Op.getOperand(0);
4884   SDValue ShOpHi = Op.getOperand(1);
4885   SDValue ShAmt  = Op.getOperand(2);
4886   SDValue ARMcc;
4887   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4888   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4889 
4890   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4891 
4892   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4893                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4894   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4895   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4896                                    DAG.getConstant(VTBits, dl, MVT::i32));
4897   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4898   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4899   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4900   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4901                             ISD::SETGE, ARMcc, DAG, dl);
4902   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4903                            ARMcc, CCR, CmpLo);
4904 
4905 
4906   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4907   SDValue HiBigShift = Opc == ISD::SRA
4908                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
4909                                          DAG.getConstant(VTBits - 1, dl, VT))
4910                            : DAG.getConstant(0, dl, VT);
4911   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4912                             ISD::SETGE, ARMcc, DAG, dl);
4913   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4914                            ARMcc, CCR, CmpHi);
4915 
4916   SDValue Ops[2] = { Lo, Hi };
4917   return DAG.getMergeValues(Ops, dl);
4918 }
4919 
4920 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4921 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4922 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4923                                                SelectionDAG &DAG) const {
4924   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4925   EVT VT = Op.getValueType();
4926   unsigned VTBits = VT.getSizeInBits();
4927   SDLoc dl(Op);
4928   SDValue ShOpLo = Op.getOperand(0);
4929   SDValue ShOpHi = Op.getOperand(1);
4930   SDValue ShAmt  = Op.getOperand(2);
4931   SDValue ARMcc;
4932   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4933 
4934   assert(Op.getOpcode() == ISD::SHL_PARTS);
4935   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4936                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4937   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4938   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4939   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4940 
4941   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4942                                    DAG.getConstant(VTBits, dl, MVT::i32));
4943   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4944   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4945                             ISD::SETGE, ARMcc, DAG, dl);
4946   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4947                            ARMcc, CCR, CmpHi);
4948 
4949   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4950                           ISD::SETGE, ARMcc, DAG, dl);
4951   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4952   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
4953                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
4954 
4955   SDValue Ops[2] = { Lo, Hi };
4956   return DAG.getMergeValues(Ops, dl);
4957 }
4958 
4959 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4960                                             SelectionDAG &DAG) const {
4961   // The rounding mode is in bits 23:22 of the FPSCR.
4962   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4963   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4964   // so that the shift + and get folded into a bitfield extract.
4965   SDLoc dl(Op);
4966   SDValue Ops[] = { DAG.getEntryNode(),
4967                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
4968 
4969   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
4970   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4971                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4972   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4973                               DAG.getConstant(22, dl, MVT::i32));
4974   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4975                      DAG.getConstant(3, dl, MVT::i32));
4976 }
4977 
4978 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4979                          const ARMSubtarget *ST) {
4980   SDLoc dl(N);
4981   EVT VT = N->getValueType(0);
4982   if (VT.isVector()) {
4983     assert(ST->hasNEON());
4984 
4985     // Compute the least significant set bit: LSB = X & -X
4986     SDValue X = N->getOperand(0);
4987     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4988     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4989 
4990     EVT ElemTy = VT.getVectorElementType();
4991 
4992     if (ElemTy == MVT::i8) {
4993       // Compute with: cttz(x) = ctpop(lsb - 1)
4994       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4995                                 DAG.getTargetConstant(1, dl, ElemTy));
4996       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4997       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4998     }
4999 
5000     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5001         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5002       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5003       unsigned NumBits = ElemTy.getSizeInBits();
5004       SDValue WidthMinus1 =
5005           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5006                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5007       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5008       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5009     }
5010 
5011     // Compute with: cttz(x) = ctpop(lsb - 1)
5012 
5013     // Since we can only compute the number of bits in a byte with vcnt.8, we
5014     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5015     // and i64.
5016 
5017     // Compute LSB - 1.
5018     SDValue Bits;
5019     if (ElemTy == MVT::i64) {
5020       // Load constant 0xffff'ffff'ffff'ffff to register.
5021       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5022                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5023       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5024     } else {
5025       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5026                                 DAG.getTargetConstant(1, dl, ElemTy));
5027       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5028     }
5029 
5030     // Count #bits with vcnt.8.
5031     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5032     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5033     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5034 
5035     // Gather the #bits with vpaddl (pairwise add.)
5036     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5037     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5038         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5039         Cnt8);
5040     if (ElemTy == MVT::i16)
5041       return Cnt16;
5042 
5043     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5044     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5045         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5046         Cnt16);
5047     if (ElemTy == MVT::i32)
5048       return Cnt32;
5049 
5050     assert(ElemTy == MVT::i64);
5051     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5052         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5053         Cnt32);
5054     return Cnt64;
5055   }
5056 
5057   if (!ST->hasV6T2Ops())
5058     return SDValue();
5059 
5060   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5061   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5062 }
5063 
5064 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5065 /// for each 16-bit element from operand, repeated.  The basic idea is to
5066 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5067 ///
5068 /// Trace for v4i16:
5069 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5070 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5071 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5072 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5073 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5074 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5075 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5076 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5077 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5078   EVT VT = N->getValueType(0);
5079   SDLoc DL(N);
5080 
5081   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5082   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5083   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5084   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5085   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5086   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5087 }
5088 
5089 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5090 /// bit-count for each 16-bit element from the operand.  We need slightly
5091 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5092 /// 64/128-bit registers.
5093 ///
5094 /// Trace for v4i16:
5095 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5096 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5097 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5098 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5099 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5100   EVT VT = N->getValueType(0);
5101   SDLoc DL(N);
5102 
5103   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5104   if (VT.is64BitVector()) {
5105     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5106     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5107                        DAG.getIntPtrConstant(0, DL));
5108   } else {
5109     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5110                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5111     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5112   }
5113 }
5114 
5115 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5116 /// bit-count for each 32-bit element from the operand.  The idea here is
5117 /// to split the vector into 16-bit elements, leverage the 16-bit count
5118 /// routine, and then combine the results.
5119 ///
5120 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5121 /// input    = [v0    v1    ] (vi: 32-bit elements)
5122 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5123 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5124 /// vrev: N0 = [k1 k0 k3 k2 ]
5125 ///            [k0 k1 k2 k3 ]
5126 ///       N1 =+[k1 k0 k3 k2 ]
5127 ///            [k0 k2 k1 k3 ]
5128 ///       N2 =+[k1 k3 k0 k2 ]
5129 ///            [k0    k2    k1    k3    ]
5130 /// Extended =+[k1    k3    k0    k2    ]
5131 ///            [k0    k2    ]
5132 /// Extracted=+[k1    k3    ]
5133 ///
5134 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5135   EVT VT = N->getValueType(0);
5136   SDLoc DL(N);
5137 
5138   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5139 
5140   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5141   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5142   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5143   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5144   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5145 
5146   if (VT.is64BitVector()) {
5147     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5148     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5149                        DAG.getIntPtrConstant(0, DL));
5150   } else {
5151     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5152                                     DAG.getIntPtrConstant(0, DL));
5153     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5154   }
5155 }
5156 
5157 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5158                           const ARMSubtarget *ST) {
5159   EVT VT = N->getValueType(0);
5160 
5161   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5162   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5163           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5164          "Unexpected type for custom ctpop lowering");
5165 
5166   if (VT.getVectorElementType() == MVT::i32)
5167     return lowerCTPOP32BitElements(N, DAG);
5168   else
5169     return lowerCTPOP16BitElements(N, DAG);
5170 }
5171 
5172 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5173                           const ARMSubtarget *ST) {
5174   EVT VT = N->getValueType(0);
5175   SDLoc dl(N);
5176 
5177   if (!VT.isVector())
5178     return SDValue();
5179 
5180   // Lower vector shifts on NEON to use VSHL.
5181   assert(ST->hasNEON() && "unexpected vector shift");
5182 
5183   // Left shifts translate directly to the vshiftu intrinsic.
5184   if (N->getOpcode() == ISD::SHL)
5185     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5186                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5187                                        MVT::i32),
5188                        N->getOperand(0), N->getOperand(1));
5189 
5190   assert((N->getOpcode() == ISD::SRA ||
5191           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5192 
5193   // NEON uses the same intrinsics for both left and right shifts.  For
5194   // right shifts, the shift amounts are negative, so negate the vector of
5195   // shift amounts.
5196   EVT ShiftVT = N->getOperand(1).getValueType();
5197   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5198                                      getZeroVector(ShiftVT, DAG, dl),
5199                                      N->getOperand(1));
5200   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5201                              Intrinsic::arm_neon_vshifts :
5202                              Intrinsic::arm_neon_vshiftu);
5203   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5204                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5205                      N->getOperand(0), NegatedCount);
5206 }
5207 
5208 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5209                                 const ARMSubtarget *ST) {
5210   EVT VT = N->getValueType(0);
5211   SDLoc dl(N);
5212 
5213   // We can get here for a node like i32 = ISD::SHL i32, i64
5214   if (VT != MVT::i64)
5215     return SDValue();
5216 
5217   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5218          "Unknown shift to lower!");
5219 
5220   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5221   if (!isOneConstant(N->getOperand(1)))
5222     return SDValue();
5223 
5224   // If we are in thumb mode, we don't have RRX.
5225   if (ST->isThumb1Only()) return SDValue();
5226 
5227   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5228   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5229                            DAG.getConstant(0, dl, MVT::i32));
5230   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5231                            DAG.getConstant(1, dl, MVT::i32));
5232 
5233   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5234   // captures the result into a carry flag.
5235   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5236   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5237 
5238   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5239   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5240 
5241   // Merge the pieces into a single i64 value.
5242  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5243 }
5244 
5245 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5246   SDValue TmpOp0, TmpOp1;
5247   bool Invert = false;
5248   bool Swap = false;
5249   unsigned Opc = 0;
5250 
5251   SDValue Op0 = Op.getOperand(0);
5252   SDValue Op1 = Op.getOperand(1);
5253   SDValue CC = Op.getOperand(2);
5254   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5255   EVT VT = Op.getValueType();
5256   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5257   SDLoc dl(Op);
5258 
5259   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5260       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5261     // Special-case integer 64-bit equality comparisons. They aren't legal,
5262     // but they can be lowered with a few vector instructions.
5263     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5264     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5265     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5266     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5267     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5268                               DAG.getCondCode(ISD::SETEQ));
5269     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5270     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5271     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5272     if (SetCCOpcode == ISD::SETNE)
5273       Merged = DAG.getNOT(dl, Merged, CmpVT);
5274     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5275     return Merged;
5276   }
5277 
5278   if (CmpVT.getVectorElementType() == MVT::i64)
5279     // 64-bit comparisons are not legal in general.
5280     return SDValue();
5281 
5282   if (Op1.getValueType().isFloatingPoint()) {
5283     switch (SetCCOpcode) {
5284     default: llvm_unreachable("Illegal FP comparison");
5285     case ISD::SETUNE:
5286     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5287     case ISD::SETOEQ:
5288     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5289     case ISD::SETOLT:
5290     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5291     case ISD::SETOGT:
5292     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5293     case ISD::SETOLE:
5294     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5295     case ISD::SETOGE:
5296     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5297     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5298     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5299     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5300     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5301     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5302     case ISD::SETONE:
5303       // Expand this to (OLT | OGT).
5304       TmpOp0 = Op0;
5305       TmpOp1 = Op1;
5306       Opc = ISD::OR;
5307       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5308       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5309       break;
5310     case ISD::SETUO:
5311       Invert = true;
5312       LLVM_FALLTHROUGH;
5313     case ISD::SETO:
5314       // Expand this to (OLT | OGE).
5315       TmpOp0 = Op0;
5316       TmpOp1 = Op1;
5317       Opc = ISD::OR;
5318       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5319       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5320       break;
5321     }
5322   } else {
5323     // Integer comparisons.
5324     switch (SetCCOpcode) {
5325     default: llvm_unreachable("Illegal integer comparison");
5326     case ISD::SETNE:  Invert = true;
5327     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5328     case ISD::SETLT:  Swap = true;
5329     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5330     case ISD::SETLE:  Swap = true;
5331     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5332     case ISD::SETULT: Swap = true;
5333     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5334     case ISD::SETULE: Swap = true;
5335     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5336     }
5337 
5338     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5339     if (Opc == ARMISD::VCEQ) {
5340 
5341       SDValue AndOp;
5342       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5343         AndOp = Op0;
5344       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5345         AndOp = Op1;
5346 
5347       // Ignore bitconvert.
5348       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5349         AndOp = AndOp.getOperand(0);
5350 
5351       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5352         Opc = ARMISD::VTST;
5353         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5354         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5355         Invert = !Invert;
5356       }
5357     }
5358   }
5359 
5360   if (Swap)
5361     std::swap(Op0, Op1);
5362 
5363   // If one of the operands is a constant vector zero, attempt to fold the
5364   // comparison to a specialized compare-against-zero form.
5365   SDValue SingleOp;
5366   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5367     SingleOp = Op0;
5368   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5369     if (Opc == ARMISD::VCGE)
5370       Opc = ARMISD::VCLEZ;
5371     else if (Opc == ARMISD::VCGT)
5372       Opc = ARMISD::VCLTZ;
5373     SingleOp = Op1;
5374   }
5375 
5376   SDValue Result;
5377   if (SingleOp.getNode()) {
5378     switch (Opc) {
5379     case ARMISD::VCEQ:
5380       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5381     case ARMISD::VCGE:
5382       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5383     case ARMISD::VCLEZ:
5384       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5385     case ARMISD::VCGT:
5386       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5387     case ARMISD::VCLTZ:
5388       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5389     default:
5390       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5391     }
5392   } else {
5393      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5394   }
5395 
5396   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5397 
5398   if (Invert)
5399     Result = DAG.getNOT(dl, Result, VT);
5400 
5401   return Result;
5402 }
5403 
5404 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5405   SDValue LHS = Op.getOperand(0);
5406   SDValue RHS = Op.getOperand(1);
5407   SDValue Carry = Op.getOperand(2);
5408   SDValue Cond = Op.getOperand(3);
5409   SDLoc DL(Op);
5410 
5411   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5412 
5413   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5414   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5415   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5416 
5417   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5418   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5419   SDValue ARMcc = DAG.getConstant(
5420       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5421   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5422   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5423                                    Cmp.getValue(1), SDValue());
5424   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5425                      CCR, Chain.getValue(1));
5426 }
5427 
5428 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5429 /// valid vector constant for a NEON instruction with a "modified immediate"
5430 /// operand (e.g., VMOV).  If so, return the encoded value.
5431 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5432                                  unsigned SplatBitSize, SelectionDAG &DAG,
5433                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5434                                  NEONModImmType type) {
5435   unsigned OpCmode, Imm;
5436 
5437   // SplatBitSize is set to the smallest size that splats the vector, so a
5438   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5439   // immediate instructions others than VMOV do not support the 8-bit encoding
5440   // of a zero vector, and the default encoding of zero is supposed to be the
5441   // 32-bit version.
5442   if (SplatBits == 0)
5443     SplatBitSize = 32;
5444 
5445   switch (SplatBitSize) {
5446   case 8:
5447     if (type != VMOVModImm)
5448       return SDValue();
5449     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5450     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5451     OpCmode = 0xe;
5452     Imm = SplatBits;
5453     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5454     break;
5455 
5456   case 16:
5457     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5458     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5459     if ((SplatBits & ~0xff) == 0) {
5460       // Value = 0x00nn: Op=x, Cmode=100x.
5461       OpCmode = 0x8;
5462       Imm = SplatBits;
5463       break;
5464     }
5465     if ((SplatBits & ~0xff00) == 0) {
5466       // Value = 0xnn00: Op=x, Cmode=101x.
5467       OpCmode = 0xa;
5468       Imm = SplatBits >> 8;
5469       break;
5470     }
5471     return SDValue();
5472 
5473   case 32:
5474     // NEON's 32-bit VMOV supports splat values where:
5475     // * only one byte is nonzero, or
5476     // * the least significant byte is 0xff and the second byte is nonzero, or
5477     // * the least significant 2 bytes are 0xff and the third is nonzero.
5478     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5479     if ((SplatBits & ~0xff) == 0) {
5480       // Value = 0x000000nn: Op=x, Cmode=000x.
5481       OpCmode = 0;
5482       Imm = SplatBits;
5483       break;
5484     }
5485     if ((SplatBits & ~0xff00) == 0) {
5486       // Value = 0x0000nn00: Op=x, Cmode=001x.
5487       OpCmode = 0x2;
5488       Imm = SplatBits >> 8;
5489       break;
5490     }
5491     if ((SplatBits & ~0xff0000) == 0) {
5492       // Value = 0x00nn0000: Op=x, Cmode=010x.
5493       OpCmode = 0x4;
5494       Imm = SplatBits >> 16;
5495       break;
5496     }
5497     if ((SplatBits & ~0xff000000) == 0) {
5498       // Value = 0xnn000000: Op=x, Cmode=011x.
5499       OpCmode = 0x6;
5500       Imm = SplatBits >> 24;
5501       break;
5502     }
5503 
5504     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5505     if (type == OtherModImm) return SDValue();
5506 
5507     if ((SplatBits & ~0xffff) == 0 &&
5508         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5509       // Value = 0x0000nnff: Op=x, Cmode=1100.
5510       OpCmode = 0xc;
5511       Imm = SplatBits >> 8;
5512       break;
5513     }
5514 
5515     if ((SplatBits & ~0xffffff) == 0 &&
5516         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5517       // Value = 0x00nnffff: Op=x, Cmode=1101.
5518       OpCmode = 0xd;
5519       Imm = SplatBits >> 16;
5520       break;
5521     }
5522 
5523     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5524     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5525     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5526     // and fall through here to test for a valid 64-bit splat.  But, then the
5527     // caller would also need to check and handle the change in size.
5528     return SDValue();
5529 
5530   case 64: {
5531     if (type != VMOVModImm)
5532       return SDValue();
5533     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5534     uint64_t BitMask = 0xff;
5535     uint64_t Val = 0;
5536     unsigned ImmMask = 1;
5537     Imm = 0;
5538     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5539       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5540         Val |= BitMask;
5541         Imm |= ImmMask;
5542       } else if ((SplatBits & BitMask) != 0) {
5543         return SDValue();
5544       }
5545       BitMask <<= 8;
5546       ImmMask <<= 1;
5547     }
5548 
5549     if (DAG.getDataLayout().isBigEndian())
5550       // swap higher and lower 32 bit word
5551       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5552 
5553     // Op=1, Cmode=1110.
5554     OpCmode = 0x1e;
5555     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5556     break;
5557   }
5558 
5559   default:
5560     llvm_unreachable("unexpected size for isNEONModifiedImm");
5561   }
5562 
5563   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5564   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5565 }
5566 
5567 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5568                                            const ARMSubtarget *ST) const {
5569   bool IsDouble = Op.getValueType() == MVT::f64;
5570   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5571   const APFloat &FPVal = CFP->getValueAPF();
5572 
5573   // Prevent floating-point constants from using literal loads
5574   // when execute-only is enabled.
5575   if (ST->genExecuteOnly()) {
5576     APInt INTVal = FPVal.bitcastToAPInt();
5577     SDLoc DL(CFP);
5578     if (IsDouble) {
5579       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5580       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5581       if (!ST->isLittle())
5582         std::swap(Lo, Hi);
5583       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5584     } else {
5585       return DAG.getConstant(INTVal, DL, MVT::i32);
5586     }
5587   }
5588 
5589   if (!ST->hasVFP3())
5590     return SDValue();
5591 
5592   // Use the default (constant pool) lowering for double constants when we have
5593   // an SP-only FPU
5594   if (IsDouble && Subtarget->isFPOnlySP())
5595     return SDValue();
5596 
5597   // Try splatting with a VMOV.f32...
5598   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5599 
5600   if (ImmVal != -1) {
5601     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5602       // We have code in place to select a valid ConstantFP already, no need to
5603       // do any mangling.
5604       return Op;
5605     }
5606 
5607     // It's a float and we are trying to use NEON operations where
5608     // possible. Lower it to a splat followed by an extract.
5609     SDLoc DL(Op);
5610     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5611     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5612                                       NewVal);
5613     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5614                        DAG.getConstant(0, DL, MVT::i32));
5615   }
5616 
5617   // The rest of our options are NEON only, make sure that's allowed before
5618   // proceeding..
5619   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5620     return SDValue();
5621 
5622   EVT VMovVT;
5623   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5624 
5625   // It wouldn't really be worth bothering for doubles except for one very
5626   // important value, which does happen to match: 0.0. So make sure we don't do
5627   // anything stupid.
5628   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5629     return SDValue();
5630 
5631   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5632   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5633                                      VMovVT, false, VMOVModImm);
5634   if (NewVal != SDValue()) {
5635     SDLoc DL(Op);
5636     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5637                                       NewVal);
5638     if (IsDouble)
5639       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5640 
5641     // It's a float: cast and extract a vector element.
5642     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5643                                        VecConstant);
5644     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5645                        DAG.getConstant(0, DL, MVT::i32));
5646   }
5647 
5648   // Finally, try a VMVN.i32
5649   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5650                              false, VMVNModImm);
5651   if (NewVal != SDValue()) {
5652     SDLoc DL(Op);
5653     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5654 
5655     if (IsDouble)
5656       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5657 
5658     // It's a float: cast and extract a vector element.
5659     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5660                                        VecConstant);
5661     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5662                        DAG.getConstant(0, DL, MVT::i32));
5663   }
5664 
5665   return SDValue();
5666 }
5667 
5668 // check if an VEXT instruction can handle the shuffle mask when the
5669 // vector sources of the shuffle are the same.
5670 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5671   unsigned NumElts = VT.getVectorNumElements();
5672 
5673   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5674   if (M[0] < 0)
5675     return false;
5676 
5677   Imm = M[0];
5678 
5679   // If this is a VEXT shuffle, the immediate value is the index of the first
5680   // element.  The other shuffle indices must be the successive elements after
5681   // the first one.
5682   unsigned ExpectedElt = Imm;
5683   for (unsigned i = 1; i < NumElts; ++i) {
5684     // Increment the expected index.  If it wraps around, just follow it
5685     // back to index zero and keep going.
5686     ++ExpectedElt;
5687     if (ExpectedElt == NumElts)
5688       ExpectedElt = 0;
5689 
5690     if (M[i] < 0) continue; // ignore UNDEF indices
5691     if (ExpectedElt != static_cast<unsigned>(M[i]))
5692       return false;
5693   }
5694 
5695   return true;
5696 }
5697 
5698 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5699                        bool &ReverseVEXT, unsigned &Imm) {
5700   unsigned NumElts = VT.getVectorNumElements();
5701   ReverseVEXT = false;
5702 
5703   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5704   if (M[0] < 0)
5705     return false;
5706 
5707   Imm = M[0];
5708 
5709   // If this is a VEXT shuffle, the immediate value is the index of the first
5710   // element.  The other shuffle indices must be the successive elements after
5711   // the first one.
5712   unsigned ExpectedElt = Imm;
5713   for (unsigned i = 1; i < NumElts; ++i) {
5714     // Increment the expected index.  If it wraps around, it may still be
5715     // a VEXT but the source vectors must be swapped.
5716     ExpectedElt += 1;
5717     if (ExpectedElt == NumElts * 2) {
5718       ExpectedElt = 0;
5719       ReverseVEXT = true;
5720     }
5721 
5722     if (M[i] < 0) continue; // ignore UNDEF indices
5723     if (ExpectedElt != static_cast<unsigned>(M[i]))
5724       return false;
5725   }
5726 
5727   // Adjust the index value if the source operands will be swapped.
5728   if (ReverseVEXT)
5729     Imm -= NumElts;
5730 
5731   return true;
5732 }
5733 
5734 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5735 /// instruction with the specified blocksize.  (The order of the elements
5736 /// within each block of the vector is reversed.)
5737 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5738   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5739          "Only possible block sizes for VREV are: 16, 32, 64");
5740 
5741   unsigned EltSz = VT.getScalarSizeInBits();
5742   if (EltSz == 64)
5743     return false;
5744 
5745   unsigned NumElts = VT.getVectorNumElements();
5746   unsigned BlockElts = M[0] + 1;
5747   // If the first shuffle index is UNDEF, be optimistic.
5748   if (M[0] < 0)
5749     BlockElts = BlockSize / EltSz;
5750 
5751   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5752     return false;
5753 
5754   for (unsigned i = 0; i < NumElts; ++i) {
5755     if (M[i] < 0) continue; // ignore UNDEF indices
5756     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5757       return false;
5758   }
5759 
5760   return true;
5761 }
5762 
5763 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5764   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5765   // range, then 0 is placed into the resulting vector. So pretty much any mask
5766   // of 8 elements can work here.
5767   return VT == MVT::v8i8 && M.size() == 8;
5768 }
5769 
5770 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5771 // checking that pairs of elements in the shuffle mask represent the same index
5772 // in each vector, incrementing the expected index by 2 at each step.
5773 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5774 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5775 //  v2={e,f,g,h}
5776 // WhichResult gives the offset for each element in the mask based on which
5777 // of the two results it belongs to.
5778 //
5779 // The transpose can be represented either as:
5780 // result1 = shufflevector v1, v2, result1_shuffle_mask
5781 // result2 = shufflevector v1, v2, result2_shuffle_mask
5782 // where v1/v2 and the shuffle masks have the same number of elements
5783 // (here WhichResult (see below) indicates which result is being checked)
5784 //
5785 // or as:
5786 // results = shufflevector v1, v2, shuffle_mask
5787 // where both results are returned in one vector and the shuffle mask has twice
5788 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5789 // want to check the low half and high half of the shuffle mask as if it were
5790 // the other case
5791 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5792   unsigned EltSz = VT.getScalarSizeInBits();
5793   if (EltSz == 64)
5794     return false;
5795 
5796   unsigned NumElts = VT.getVectorNumElements();
5797   if (M.size() != NumElts && M.size() != NumElts*2)
5798     return false;
5799 
5800   // If the mask is twice as long as the input vector then we need to check the
5801   // upper and lower parts of the mask with a matching value for WhichResult
5802   // FIXME: A mask with only even values will be rejected in case the first
5803   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5804   // M[0] is used to determine WhichResult
5805   for (unsigned i = 0; i < M.size(); i += NumElts) {
5806     if (M.size() == NumElts * 2)
5807       WhichResult = i / NumElts;
5808     else
5809       WhichResult = M[i] == 0 ? 0 : 1;
5810     for (unsigned j = 0; j < NumElts; j += 2) {
5811       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5812           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5813         return false;
5814     }
5815   }
5816 
5817   if (M.size() == NumElts*2)
5818     WhichResult = 0;
5819 
5820   return true;
5821 }
5822 
5823 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5824 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5825 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5826 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5827   unsigned EltSz = VT.getScalarSizeInBits();
5828   if (EltSz == 64)
5829     return false;
5830 
5831   unsigned NumElts = VT.getVectorNumElements();
5832   if (M.size() != NumElts && M.size() != NumElts*2)
5833     return false;
5834 
5835   for (unsigned i = 0; i < M.size(); i += NumElts) {
5836     if (M.size() == NumElts * 2)
5837       WhichResult = i / NumElts;
5838     else
5839       WhichResult = M[i] == 0 ? 0 : 1;
5840     for (unsigned j = 0; j < NumElts; j += 2) {
5841       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5842           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5843         return false;
5844     }
5845   }
5846 
5847   if (M.size() == NumElts*2)
5848     WhichResult = 0;
5849 
5850   return true;
5851 }
5852 
5853 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5854 // that the mask elements are either all even and in steps of size 2 or all odd
5855 // and in steps of size 2.
5856 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5857 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5858 //  v2={e,f,g,h}
5859 // Requires similar checks to that of isVTRNMask with
5860 // respect the how results are returned.
5861 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5862   unsigned EltSz = VT.getScalarSizeInBits();
5863   if (EltSz == 64)
5864     return false;
5865 
5866   unsigned NumElts = VT.getVectorNumElements();
5867   if (M.size() != NumElts && M.size() != NumElts*2)
5868     return false;
5869 
5870   for (unsigned i = 0; i < M.size(); i += NumElts) {
5871     WhichResult = M[i] == 0 ? 0 : 1;
5872     for (unsigned j = 0; j < NumElts; ++j) {
5873       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5874         return false;
5875     }
5876   }
5877 
5878   if (M.size() == NumElts*2)
5879     WhichResult = 0;
5880 
5881   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5882   if (VT.is64BitVector() && EltSz == 32)
5883     return false;
5884 
5885   return true;
5886 }
5887 
5888 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5889 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5890 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5891 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5892   unsigned EltSz = VT.getScalarSizeInBits();
5893   if (EltSz == 64)
5894     return false;
5895 
5896   unsigned NumElts = VT.getVectorNumElements();
5897   if (M.size() != NumElts && M.size() != NumElts*2)
5898     return false;
5899 
5900   unsigned Half = NumElts / 2;
5901   for (unsigned i = 0; i < M.size(); i += NumElts) {
5902     WhichResult = M[i] == 0 ? 0 : 1;
5903     for (unsigned j = 0; j < NumElts; j += Half) {
5904       unsigned Idx = WhichResult;
5905       for (unsigned k = 0; k < Half; ++k) {
5906         int MIdx = M[i + j + k];
5907         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5908           return false;
5909         Idx += 2;
5910       }
5911     }
5912   }
5913 
5914   if (M.size() == NumElts*2)
5915     WhichResult = 0;
5916 
5917   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5918   if (VT.is64BitVector() && EltSz == 32)
5919     return false;
5920 
5921   return true;
5922 }
5923 
5924 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5925 // that pairs of elements of the shufflemask represent the same index in each
5926 // vector incrementing sequentially through the vectors.
5927 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5928 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5929 //  v2={e,f,g,h}
5930 // Requires similar checks to that of isVTRNMask with respect the how results
5931 // are returned.
5932 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5933   unsigned EltSz = VT.getScalarSizeInBits();
5934   if (EltSz == 64)
5935     return false;
5936 
5937   unsigned NumElts = VT.getVectorNumElements();
5938   if (M.size() != NumElts && M.size() != NumElts*2)
5939     return false;
5940 
5941   for (unsigned i = 0; i < M.size(); i += NumElts) {
5942     WhichResult = M[i] == 0 ? 0 : 1;
5943     unsigned Idx = WhichResult * NumElts / 2;
5944     for (unsigned j = 0; j < NumElts; j += 2) {
5945       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5946           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5947         return false;
5948       Idx += 1;
5949     }
5950   }
5951 
5952   if (M.size() == NumElts*2)
5953     WhichResult = 0;
5954 
5955   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5956   if (VT.is64BitVector() && EltSz == 32)
5957     return false;
5958 
5959   return true;
5960 }
5961 
5962 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5963 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5964 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5965 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5966   unsigned EltSz = VT.getScalarSizeInBits();
5967   if (EltSz == 64)
5968     return false;
5969 
5970   unsigned NumElts = VT.getVectorNumElements();
5971   if (M.size() != NumElts && M.size() != NumElts*2)
5972     return false;
5973 
5974   for (unsigned i = 0; i < M.size(); i += NumElts) {
5975     WhichResult = M[i] == 0 ? 0 : 1;
5976     unsigned Idx = WhichResult * NumElts / 2;
5977     for (unsigned j = 0; j < NumElts; j += 2) {
5978       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5979           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5980         return false;
5981       Idx += 1;
5982     }
5983   }
5984 
5985   if (M.size() == NumElts*2)
5986     WhichResult = 0;
5987 
5988   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5989   if (VT.is64BitVector() && EltSz == 32)
5990     return false;
5991 
5992   return true;
5993 }
5994 
5995 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5996 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5997 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5998                                            unsigned &WhichResult,
5999                                            bool &isV_UNDEF) {
6000   isV_UNDEF = false;
6001   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6002     return ARMISD::VTRN;
6003   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6004     return ARMISD::VUZP;
6005   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6006     return ARMISD::VZIP;
6007 
6008   isV_UNDEF = true;
6009   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6010     return ARMISD::VTRN;
6011   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6012     return ARMISD::VUZP;
6013   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6014     return ARMISD::VZIP;
6015 
6016   return 0;
6017 }
6018 
6019 /// \return true if this is a reverse operation on an vector.
6020 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6021   unsigned NumElts = VT.getVectorNumElements();
6022   // Make sure the mask has the right size.
6023   if (NumElts != M.size())
6024       return false;
6025 
6026   // Look for <15, ..., 3, -1, 1, 0>.
6027   for (unsigned i = 0; i != NumElts; ++i)
6028     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6029       return false;
6030 
6031   return true;
6032 }
6033 
6034 // If N is an integer constant that can be moved into a register in one
6035 // instruction, return an SDValue of such a constant (will become a MOV
6036 // instruction).  Otherwise return null.
6037 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6038                                      const ARMSubtarget *ST, const SDLoc &dl) {
6039   uint64_t Val;
6040   if (!isa<ConstantSDNode>(N))
6041     return SDValue();
6042   Val = cast<ConstantSDNode>(N)->getZExtValue();
6043 
6044   if (ST->isThumb1Only()) {
6045     if (Val <= 255 || ~Val <= 255)
6046       return DAG.getConstant(Val, dl, MVT::i32);
6047   } else {
6048     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6049       return DAG.getConstant(Val, dl, MVT::i32);
6050   }
6051   return SDValue();
6052 }
6053 
6054 // If this is a case we can't handle, return null and let the default
6055 // expansion code take care of it.
6056 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6057                                              const ARMSubtarget *ST) const {
6058   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6059   SDLoc dl(Op);
6060   EVT VT = Op.getValueType();
6061 
6062   APInt SplatBits, SplatUndef;
6063   unsigned SplatBitSize;
6064   bool HasAnyUndefs;
6065   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6066     if (SplatUndef.isAllOnesValue())
6067       return DAG.getUNDEF(VT);
6068 
6069     if (SplatBitSize <= 64) {
6070       // Check if an immediate VMOV works.
6071       EVT VmovVT;
6072       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6073                                       SplatUndef.getZExtValue(), SplatBitSize,
6074                                       DAG, dl, VmovVT, VT.is128BitVector(),
6075                                       VMOVModImm);
6076       if (Val.getNode()) {
6077         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6078         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6079       }
6080 
6081       // Try an immediate VMVN.
6082       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6083       Val = isNEONModifiedImm(NegatedImm,
6084                                       SplatUndef.getZExtValue(), SplatBitSize,
6085                                       DAG, dl, VmovVT, VT.is128BitVector(),
6086                                       VMVNModImm);
6087       if (Val.getNode()) {
6088         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6089         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6090       }
6091 
6092       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6093       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6094         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6095         if (ImmVal != -1) {
6096           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6097           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6098         }
6099       }
6100     }
6101   }
6102 
6103   // Scan through the operands to see if only one value is used.
6104   //
6105   // As an optimisation, even if more than one value is used it may be more
6106   // profitable to splat with one value then change some lanes.
6107   //
6108   // Heuristically we decide to do this if the vector has a "dominant" value,
6109   // defined as splatted to more than half of the lanes.
6110   unsigned NumElts = VT.getVectorNumElements();
6111   bool isOnlyLowElement = true;
6112   bool usesOnlyOneValue = true;
6113   bool hasDominantValue = false;
6114   bool isConstant = true;
6115 
6116   // Map of the number of times a particular SDValue appears in the
6117   // element list.
6118   DenseMap<SDValue, unsigned> ValueCounts;
6119   SDValue Value;
6120   for (unsigned i = 0; i < NumElts; ++i) {
6121     SDValue V = Op.getOperand(i);
6122     if (V.isUndef())
6123       continue;
6124     if (i > 0)
6125       isOnlyLowElement = false;
6126     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6127       isConstant = false;
6128 
6129     ValueCounts.insert(std::make_pair(V, 0));
6130     unsigned &Count = ValueCounts[V];
6131 
6132     // Is this value dominant? (takes up more than half of the lanes)
6133     if (++Count > (NumElts / 2)) {
6134       hasDominantValue = true;
6135       Value = V;
6136     }
6137   }
6138   if (ValueCounts.size() != 1)
6139     usesOnlyOneValue = false;
6140   if (!Value.getNode() && !ValueCounts.empty())
6141     Value = ValueCounts.begin()->first;
6142 
6143   if (ValueCounts.empty())
6144     return DAG.getUNDEF(VT);
6145 
6146   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6147   // Keep going if we are hitting this case.
6148   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6149     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6150 
6151   unsigned EltSize = VT.getScalarSizeInBits();
6152 
6153   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6154   // i32 and try again.
6155   if (hasDominantValue && EltSize <= 32) {
6156     if (!isConstant) {
6157       SDValue N;
6158 
6159       // If we are VDUPing a value that comes directly from a vector, that will
6160       // cause an unnecessary move to and from a GPR, where instead we could
6161       // just use VDUPLANE. We can only do this if the lane being extracted
6162       // is at a constant index, as the VDUP from lane instructions only have
6163       // constant-index forms.
6164       ConstantSDNode *constIndex;
6165       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6166           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6167         // We need to create a new undef vector to use for the VDUPLANE if the
6168         // size of the vector from which we get the value is different than the
6169         // size of the vector that we need to create. We will insert the element
6170         // such that the register coalescer will remove unnecessary copies.
6171         if (VT != Value->getOperand(0).getValueType()) {
6172           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6173                              VT.getVectorNumElements();
6174           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6175                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6176                         Value, DAG.getConstant(index, dl, MVT::i32)),
6177                            DAG.getConstant(index, dl, MVT::i32));
6178         } else
6179           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6180                         Value->getOperand(0), Value->getOperand(1));
6181       } else
6182         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6183 
6184       if (!usesOnlyOneValue) {
6185         // The dominant value was splatted as 'N', but we now have to insert
6186         // all differing elements.
6187         for (unsigned I = 0; I < NumElts; ++I) {
6188           if (Op.getOperand(I) == Value)
6189             continue;
6190           SmallVector<SDValue, 3> Ops;
6191           Ops.push_back(N);
6192           Ops.push_back(Op.getOperand(I));
6193           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6194           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6195         }
6196       }
6197       return N;
6198     }
6199     if (VT.getVectorElementType().isFloatingPoint()) {
6200       SmallVector<SDValue, 8> Ops;
6201       for (unsigned i = 0; i < NumElts; ++i)
6202         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6203                                   Op.getOperand(i)));
6204       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6205       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6206       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6207       if (Val.getNode())
6208         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6209     }
6210     if (usesOnlyOneValue) {
6211       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6212       if (isConstant && Val.getNode())
6213         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6214     }
6215   }
6216 
6217   // If all elements are constants and the case above didn't get hit, fall back
6218   // to the default expansion, which will generate a load from the constant
6219   // pool.
6220   if (isConstant)
6221     return SDValue();
6222 
6223   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6224   if (NumElts >= 4) {
6225     SDValue shuffle = ReconstructShuffle(Op, DAG);
6226     if (shuffle != SDValue())
6227       return shuffle;
6228   }
6229 
6230   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6231     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6232     // into two 64-bit vectors; we might discover a better way to lower it.
6233     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6234     EVT ExtVT = VT.getVectorElementType();
6235     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6236     SDValue Lower =
6237         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6238     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6239       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6240     SDValue Upper = DAG.getBuildVector(
6241         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6242     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6243       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6244     if (Lower && Upper)
6245       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6246   }
6247 
6248   // Vectors with 32- or 64-bit elements can be built by directly assigning
6249   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6250   // will be legalized.
6251   if (EltSize >= 32) {
6252     // Do the expansion with floating-point types, since that is what the VFP
6253     // registers are defined to use, and since i64 is not legal.
6254     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6255     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6256     SmallVector<SDValue, 8> Ops;
6257     for (unsigned i = 0; i < NumElts; ++i)
6258       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6259     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6260     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6261   }
6262 
6263   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6264   // know the default expansion would otherwise fall back on something even
6265   // worse. For a vector with one or two non-undef values, that's
6266   // scalar_to_vector for the elements followed by a shuffle (provided the
6267   // shuffle is valid for the target) and materialization element by element
6268   // on the stack followed by a load for everything else.
6269   if (!isConstant && !usesOnlyOneValue) {
6270     SDValue Vec = DAG.getUNDEF(VT);
6271     for (unsigned i = 0 ; i < NumElts; ++i) {
6272       SDValue V = Op.getOperand(i);
6273       if (V.isUndef())
6274         continue;
6275       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6276       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6277     }
6278     return Vec;
6279   }
6280 
6281   return SDValue();
6282 }
6283 
6284 // Gather data to see if the operation can be modelled as a
6285 // shuffle in combination with VEXTs.
6286 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6287                                               SelectionDAG &DAG) const {
6288   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6289   SDLoc dl(Op);
6290   EVT VT = Op.getValueType();
6291   unsigned NumElts = VT.getVectorNumElements();
6292 
6293   struct ShuffleSourceInfo {
6294     SDValue Vec;
6295     unsigned MinElt = std::numeric_limits<unsigned>::max();
6296     unsigned MaxElt = 0;
6297 
6298     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6299     // be compatible with the shuffle we intend to construct. As a result
6300     // ShuffleVec will be some sliding window into the original Vec.
6301     SDValue ShuffleVec;
6302 
6303     // Code should guarantee that element i in Vec starts at element "WindowBase
6304     // + i * WindowScale in ShuffleVec".
6305     int WindowBase = 0;
6306     int WindowScale = 1;
6307 
6308     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6309 
6310     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6311   };
6312 
6313   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6314   // node.
6315   SmallVector<ShuffleSourceInfo, 2> Sources;
6316   for (unsigned i = 0; i < NumElts; ++i) {
6317     SDValue V = Op.getOperand(i);
6318     if (V.isUndef())
6319       continue;
6320     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6321       // A shuffle can only come from building a vector from various
6322       // elements of other vectors.
6323       return SDValue();
6324     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6325       // Furthermore, shuffles require a constant mask, whereas extractelts
6326       // accept variable indices.
6327       return SDValue();
6328     }
6329 
6330     // Add this element source to the list if it's not already there.
6331     SDValue SourceVec = V.getOperand(0);
6332     auto Source = llvm::find(Sources, SourceVec);
6333     if (Source == Sources.end())
6334       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6335 
6336     // Update the minimum and maximum lane number seen.
6337     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6338     Source->MinElt = std::min(Source->MinElt, EltNo);
6339     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6340   }
6341 
6342   // Currently only do something sane when at most two source vectors
6343   // are involved.
6344   if (Sources.size() > 2)
6345     return SDValue();
6346 
6347   // Find out the smallest element size among result and two sources, and use
6348   // it as element size to build the shuffle_vector.
6349   EVT SmallestEltTy = VT.getVectorElementType();
6350   for (auto &Source : Sources) {
6351     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6352     if (SrcEltTy.bitsLT(SmallestEltTy))
6353       SmallestEltTy = SrcEltTy;
6354   }
6355   unsigned ResMultiplier =
6356       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6357   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6358   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6359 
6360   // If the source vector is too wide or too narrow, we may nevertheless be able
6361   // to construct a compatible shuffle either by concatenating it with UNDEF or
6362   // extracting a suitable range of elements.
6363   for (auto &Src : Sources) {
6364     EVT SrcVT = Src.ShuffleVec.getValueType();
6365 
6366     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6367       continue;
6368 
6369     // This stage of the search produces a source with the same element type as
6370     // the original, but with a total width matching the BUILD_VECTOR output.
6371     EVT EltVT = SrcVT.getVectorElementType();
6372     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6373     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6374 
6375     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6376       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6377         return SDValue();
6378       // We can pad out the smaller vector for free, so if it's part of a
6379       // shuffle...
6380       Src.ShuffleVec =
6381           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6382                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6383       continue;
6384     }
6385 
6386     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6387       return SDValue();
6388 
6389     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6390       // Span too large for a VEXT to cope
6391       return SDValue();
6392     }
6393 
6394     if (Src.MinElt >= NumSrcElts) {
6395       // The extraction can just take the second half
6396       Src.ShuffleVec =
6397           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6398                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6399       Src.WindowBase = -NumSrcElts;
6400     } else if (Src.MaxElt < NumSrcElts) {
6401       // The extraction can just take the first half
6402       Src.ShuffleVec =
6403           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6404                       DAG.getConstant(0, dl, MVT::i32));
6405     } else {
6406       // An actual VEXT is needed
6407       SDValue VEXTSrc1 =
6408           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6409                       DAG.getConstant(0, dl, MVT::i32));
6410       SDValue VEXTSrc2 =
6411           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6412                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6413 
6414       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6415                                    VEXTSrc2,
6416                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6417       Src.WindowBase = -Src.MinElt;
6418     }
6419   }
6420 
6421   // Another possible incompatibility occurs from the vector element types. We
6422   // can fix this by bitcasting the source vectors to the same type we intend
6423   // for the shuffle.
6424   for (auto &Src : Sources) {
6425     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6426     if (SrcEltTy == SmallestEltTy)
6427       continue;
6428     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6429     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6430     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6431     Src.WindowBase *= Src.WindowScale;
6432   }
6433 
6434   // Final sanity check before we try to actually produce a shuffle.
6435   DEBUG(
6436     for (auto Src : Sources)
6437       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6438   );
6439 
6440   // The stars all align, our next step is to produce the mask for the shuffle.
6441   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6442   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6443   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6444     SDValue Entry = Op.getOperand(i);
6445     if (Entry.isUndef())
6446       continue;
6447 
6448     auto Src = llvm::find(Sources, Entry.getOperand(0));
6449     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6450 
6451     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6452     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6453     // segment.
6454     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6455     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6456                                VT.getScalarSizeInBits());
6457     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6458 
6459     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6460     // starting at the appropriate offset.
6461     int *LaneMask = &Mask[i * ResMultiplier];
6462 
6463     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6464     ExtractBase += NumElts * (Src - Sources.begin());
6465     for (int j = 0; j < LanesDefined; ++j)
6466       LaneMask[j] = ExtractBase + j;
6467   }
6468 
6469   // Final check before we try to produce nonsense...
6470   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6471     return SDValue();
6472 
6473   // We can't handle more than two sources. This should have already
6474   // been checked before this point.
6475   assert(Sources.size() <= 2 && "Too many sources!");
6476 
6477   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6478   for (unsigned i = 0; i < Sources.size(); ++i)
6479     ShuffleOps[i] = Sources[i].ShuffleVec;
6480 
6481   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6482                                          ShuffleOps[1], Mask);
6483   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6484 }
6485 
6486 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6487 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6488 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6489 /// are assumed to be legal.
6490 bool
6491 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6492                                       EVT VT) const {
6493   if (VT.getVectorNumElements() == 4 &&
6494       (VT.is128BitVector() || VT.is64BitVector())) {
6495     unsigned PFIndexes[4];
6496     for (unsigned i = 0; i != 4; ++i) {
6497       if (M[i] < 0)
6498         PFIndexes[i] = 8;
6499       else
6500         PFIndexes[i] = M[i];
6501     }
6502 
6503     // Compute the index in the perfect shuffle table.
6504     unsigned PFTableIndex =
6505       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6506     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6507     unsigned Cost = (PFEntry >> 30);
6508 
6509     if (Cost <= 4)
6510       return true;
6511   }
6512 
6513   bool ReverseVEXT, isV_UNDEF;
6514   unsigned Imm, WhichResult;
6515 
6516   unsigned EltSize = VT.getScalarSizeInBits();
6517   return (EltSize >= 32 ||
6518           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6519           isVREVMask(M, VT, 64) ||
6520           isVREVMask(M, VT, 32) ||
6521           isVREVMask(M, VT, 16) ||
6522           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6523           isVTBLMask(M, VT) ||
6524           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6525           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6526 }
6527 
6528 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6529 /// the specified operations to build the shuffle.
6530 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6531                                       SDValue RHS, SelectionDAG &DAG,
6532                                       const SDLoc &dl) {
6533   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6534   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6535   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6536 
6537   enum {
6538     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6539     OP_VREV,
6540     OP_VDUP0,
6541     OP_VDUP1,
6542     OP_VDUP2,
6543     OP_VDUP3,
6544     OP_VEXT1,
6545     OP_VEXT2,
6546     OP_VEXT3,
6547     OP_VUZPL, // VUZP, left result
6548     OP_VUZPR, // VUZP, right result
6549     OP_VZIPL, // VZIP, left result
6550     OP_VZIPR, // VZIP, right result
6551     OP_VTRNL, // VTRN, left result
6552     OP_VTRNR  // VTRN, right result
6553   };
6554 
6555   if (OpNum == OP_COPY) {
6556     if (LHSID == (1*9+2)*9+3) return LHS;
6557     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6558     return RHS;
6559   }
6560 
6561   SDValue OpLHS, OpRHS;
6562   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6563   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6564   EVT VT = OpLHS.getValueType();
6565 
6566   switch (OpNum) {
6567   default: llvm_unreachable("Unknown shuffle opcode!");
6568   case OP_VREV:
6569     // VREV divides the vector in half and swaps within the half.
6570     if (VT.getVectorElementType() == MVT::i32 ||
6571         VT.getVectorElementType() == MVT::f32)
6572       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6573     // vrev <4 x i16> -> VREV32
6574     if (VT.getVectorElementType() == MVT::i16)
6575       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6576     // vrev <4 x i8> -> VREV16
6577     assert(VT.getVectorElementType() == MVT::i8);
6578     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6579   case OP_VDUP0:
6580   case OP_VDUP1:
6581   case OP_VDUP2:
6582   case OP_VDUP3:
6583     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6584                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6585   case OP_VEXT1:
6586   case OP_VEXT2:
6587   case OP_VEXT3:
6588     return DAG.getNode(ARMISD::VEXT, dl, VT,
6589                        OpLHS, OpRHS,
6590                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6591   case OP_VUZPL:
6592   case OP_VUZPR:
6593     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6594                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6595   case OP_VZIPL:
6596   case OP_VZIPR:
6597     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6598                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6599   case OP_VTRNL:
6600   case OP_VTRNR:
6601     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6602                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6603   }
6604 }
6605 
6606 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6607                                        ArrayRef<int> ShuffleMask,
6608                                        SelectionDAG &DAG) {
6609   // Check to see if we can use the VTBL instruction.
6610   SDValue V1 = Op.getOperand(0);
6611   SDValue V2 = Op.getOperand(1);
6612   SDLoc DL(Op);
6613 
6614   SmallVector<SDValue, 8> VTBLMask;
6615   for (ArrayRef<int>::iterator
6616          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6617     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6618 
6619   if (V2.getNode()->isUndef())
6620     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6621                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6622 
6623   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6624                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6625 }
6626 
6627 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6628                                                       SelectionDAG &DAG) {
6629   SDLoc DL(Op);
6630   SDValue OpLHS = Op.getOperand(0);
6631   EVT VT = OpLHS.getValueType();
6632 
6633   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6634          "Expect an v8i16/v16i8 type");
6635   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6636   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6637   // extract the first 8 bytes into the top double word and the last 8 bytes
6638   // into the bottom double word. The v8i16 case is similar.
6639   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6640   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6641                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6642 }
6643 
6644 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6645   SDValue V1 = Op.getOperand(0);
6646   SDValue V2 = Op.getOperand(1);
6647   SDLoc dl(Op);
6648   EVT VT = Op.getValueType();
6649   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6650 
6651   // Convert shuffles that are directly supported on NEON to target-specific
6652   // DAG nodes, instead of keeping them as shuffles and matching them again
6653   // during code selection.  This is more efficient and avoids the possibility
6654   // of inconsistencies between legalization and selection.
6655   // FIXME: floating-point vectors should be canonicalized to integer vectors
6656   // of the same time so that they get CSEd properly.
6657   ArrayRef<int> ShuffleMask = SVN->getMask();
6658 
6659   unsigned EltSize = VT.getScalarSizeInBits();
6660   if (EltSize <= 32) {
6661     if (SVN->isSplat()) {
6662       int Lane = SVN->getSplatIndex();
6663       // If this is undef splat, generate it via "just" vdup, if possible.
6664       if (Lane == -1) Lane = 0;
6665 
6666       // Test if V1 is a SCALAR_TO_VECTOR.
6667       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6668         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6669       }
6670       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6671       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6672       // reaches it).
6673       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6674           !isa<ConstantSDNode>(V1.getOperand(0))) {
6675         bool IsScalarToVector = true;
6676         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6677           if (!V1.getOperand(i).isUndef()) {
6678             IsScalarToVector = false;
6679             break;
6680           }
6681         if (IsScalarToVector)
6682           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6683       }
6684       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6685                          DAG.getConstant(Lane, dl, MVT::i32));
6686     }
6687 
6688     bool ReverseVEXT;
6689     unsigned Imm;
6690     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6691       if (ReverseVEXT)
6692         std::swap(V1, V2);
6693       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6694                          DAG.getConstant(Imm, dl, MVT::i32));
6695     }
6696 
6697     if (isVREVMask(ShuffleMask, VT, 64))
6698       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6699     if (isVREVMask(ShuffleMask, VT, 32))
6700       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6701     if (isVREVMask(ShuffleMask, VT, 16))
6702       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6703 
6704     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6705       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6706                          DAG.getConstant(Imm, dl, MVT::i32));
6707     }
6708 
6709     // Check for Neon shuffles that modify both input vectors in place.
6710     // If both results are used, i.e., if there are two shuffles with the same
6711     // source operands and with masks corresponding to both results of one of
6712     // these operations, DAG memoization will ensure that a single node is
6713     // used for both shuffles.
6714     unsigned WhichResult;
6715     bool isV_UNDEF;
6716     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6717             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6718       if (isV_UNDEF)
6719         V2 = V1;
6720       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6721           .getValue(WhichResult);
6722     }
6723 
6724     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6725     // shuffles that produce a result larger than their operands with:
6726     //   shuffle(concat(v1, undef), concat(v2, undef))
6727     // ->
6728     //   shuffle(concat(v1, v2), undef)
6729     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6730     //
6731     // This is useful in the general case, but there are special cases where
6732     // native shuffles produce larger results: the two-result ops.
6733     //
6734     // Look through the concat when lowering them:
6735     //   shuffle(concat(v1, v2), undef)
6736     // ->
6737     //   concat(VZIP(v1, v2):0, :1)
6738     //
6739     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6740       SDValue SubV1 = V1->getOperand(0);
6741       SDValue SubV2 = V1->getOperand(1);
6742       EVT SubVT = SubV1.getValueType();
6743 
6744       // We expect these to have been canonicalized to -1.
6745       assert(llvm::all_of(ShuffleMask, [&](int i) {
6746         return i < (int)VT.getVectorNumElements();
6747       }) && "Unexpected shuffle index into UNDEF operand!");
6748 
6749       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6750               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6751         if (isV_UNDEF)
6752           SubV2 = SubV1;
6753         assert((WhichResult == 0) &&
6754                "In-place shuffle of concat can only have one result!");
6755         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6756                                   SubV1, SubV2);
6757         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6758                            Res.getValue(1));
6759       }
6760     }
6761   }
6762 
6763   // If the shuffle is not directly supported and it has 4 elements, use
6764   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6765   unsigned NumElts = VT.getVectorNumElements();
6766   if (NumElts == 4) {
6767     unsigned PFIndexes[4];
6768     for (unsigned i = 0; i != 4; ++i) {
6769       if (ShuffleMask[i] < 0)
6770         PFIndexes[i] = 8;
6771       else
6772         PFIndexes[i] = ShuffleMask[i];
6773     }
6774 
6775     // Compute the index in the perfect shuffle table.
6776     unsigned PFTableIndex =
6777       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6778     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6779     unsigned Cost = (PFEntry >> 30);
6780 
6781     if (Cost <= 4)
6782       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6783   }
6784 
6785   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6786   if (EltSize >= 32) {
6787     // Do the expansion with floating-point types, since that is what the VFP
6788     // registers are defined to use, and since i64 is not legal.
6789     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6790     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6791     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6792     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6793     SmallVector<SDValue, 8> Ops;
6794     for (unsigned i = 0; i < NumElts; ++i) {
6795       if (ShuffleMask[i] < 0)
6796         Ops.push_back(DAG.getUNDEF(EltVT));
6797       else
6798         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6799                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6800                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6801                                                   dl, MVT::i32)));
6802     }
6803     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6804     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6805   }
6806 
6807   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6808     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6809 
6810   if (VT == MVT::v8i8)
6811     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6812       return NewOp;
6813 
6814   return SDValue();
6815 }
6816 
6817 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6818   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6819   SDValue Lane = Op.getOperand(2);
6820   if (!isa<ConstantSDNode>(Lane))
6821     return SDValue();
6822 
6823   return Op;
6824 }
6825 
6826 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6827   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6828   SDValue Lane = Op.getOperand(1);
6829   if (!isa<ConstantSDNode>(Lane))
6830     return SDValue();
6831 
6832   SDValue Vec = Op.getOperand(0);
6833   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6834     SDLoc dl(Op);
6835     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6836   }
6837 
6838   return Op;
6839 }
6840 
6841 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6842   // The only time a CONCAT_VECTORS operation can have legal types is when
6843   // two 64-bit vectors are concatenated to a 128-bit vector.
6844   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6845          "unexpected CONCAT_VECTORS");
6846   SDLoc dl(Op);
6847   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6848   SDValue Op0 = Op.getOperand(0);
6849   SDValue Op1 = Op.getOperand(1);
6850   if (!Op0.isUndef())
6851     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6852                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6853                       DAG.getIntPtrConstant(0, dl));
6854   if (!Op1.isUndef())
6855     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6856                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6857                       DAG.getIntPtrConstant(1, dl));
6858   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6859 }
6860 
6861 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6862 /// element has been zero/sign-extended, depending on the isSigned parameter,
6863 /// from an integer type half its size.
6864 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6865                                    bool isSigned) {
6866   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6867   EVT VT = N->getValueType(0);
6868   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6869     SDNode *BVN = N->getOperand(0).getNode();
6870     if (BVN->getValueType(0) != MVT::v4i32 ||
6871         BVN->getOpcode() != ISD::BUILD_VECTOR)
6872       return false;
6873     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6874     unsigned HiElt = 1 - LoElt;
6875     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6876     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6877     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6878     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6879     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6880       return false;
6881     if (isSigned) {
6882       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6883           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6884         return true;
6885     } else {
6886       if (Hi0->isNullValue() && Hi1->isNullValue())
6887         return true;
6888     }
6889     return false;
6890   }
6891 
6892   if (N->getOpcode() != ISD::BUILD_VECTOR)
6893     return false;
6894 
6895   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6896     SDNode *Elt = N->getOperand(i).getNode();
6897     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6898       unsigned EltSize = VT.getScalarSizeInBits();
6899       unsigned HalfSize = EltSize / 2;
6900       if (isSigned) {
6901         if (!isIntN(HalfSize, C->getSExtValue()))
6902           return false;
6903       } else {
6904         if (!isUIntN(HalfSize, C->getZExtValue()))
6905           return false;
6906       }
6907       continue;
6908     }
6909     return false;
6910   }
6911 
6912   return true;
6913 }
6914 
6915 /// isSignExtended - Check if a node is a vector value that is sign-extended
6916 /// or a constant BUILD_VECTOR with sign-extended elements.
6917 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6918   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6919     return true;
6920   if (isExtendedBUILD_VECTOR(N, DAG, true))
6921     return true;
6922   return false;
6923 }
6924 
6925 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6926 /// or a constant BUILD_VECTOR with zero-extended elements.
6927 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6928   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6929     return true;
6930   if (isExtendedBUILD_VECTOR(N, DAG, false))
6931     return true;
6932   return false;
6933 }
6934 
6935 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6936   if (OrigVT.getSizeInBits() >= 64)
6937     return OrigVT;
6938 
6939   assert(OrigVT.isSimple() && "Expecting a simple value type");
6940 
6941   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6942   switch (OrigSimpleTy) {
6943   default: llvm_unreachable("Unexpected Vector Type");
6944   case MVT::v2i8:
6945   case MVT::v2i16:
6946      return MVT::v2i32;
6947   case MVT::v4i8:
6948     return  MVT::v4i16;
6949   }
6950 }
6951 
6952 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6953 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6954 /// We insert the required extension here to get the vector to fill a D register.
6955 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6956                                             const EVT &OrigTy,
6957                                             const EVT &ExtTy,
6958                                             unsigned ExtOpcode) {
6959   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6960   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6961   // 64-bits we need to insert a new extension so that it will be 64-bits.
6962   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6963   if (OrigTy.getSizeInBits() >= 64)
6964     return N;
6965 
6966   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6967   EVT NewVT = getExtensionTo64Bits(OrigTy);
6968 
6969   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6970 }
6971 
6972 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6973 /// does not do any sign/zero extension. If the original vector is less
6974 /// than 64 bits, an appropriate extension will be added after the load to
6975 /// reach a total size of 64 bits. We have to add the extension separately
6976 /// because ARM does not have a sign/zero extending load for vectors.
6977 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6978   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6979 
6980   // The load already has the right type.
6981   if (ExtendedTy == LD->getMemoryVT())
6982     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6983                        LD->getBasePtr(), LD->getPointerInfo(),
6984                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6985 
6986   // We need to create a zextload/sextload. We cannot just create a load
6987   // followed by a zext/zext node because LowerMUL is also run during normal
6988   // operation legalization where we can't create illegal types.
6989   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6990                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6991                         LD->getMemoryVT(), LD->getAlignment(),
6992                         LD->getMemOperand()->getFlags());
6993 }
6994 
6995 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6996 /// extending load, or BUILD_VECTOR with extended elements, return the
6997 /// unextended value. The unextended vector should be 64 bits so that it can
6998 /// be used as an operand to a VMULL instruction. If the original vector size
6999 /// before extension is less than 64 bits we add a an extension to resize
7000 /// the vector to 64 bits.
7001 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7002   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7003     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7004                                         N->getOperand(0)->getValueType(0),
7005                                         N->getValueType(0),
7006                                         N->getOpcode());
7007 
7008   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7009     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7010            "Expected extending load");
7011 
7012     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7013     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7014     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7015     SDValue extLoad =
7016         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7017     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7018 
7019     return newLoad;
7020   }
7021 
7022   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7023   // have been legalized as a BITCAST from v4i32.
7024   if (N->getOpcode() == ISD::BITCAST) {
7025     SDNode *BVN = N->getOperand(0).getNode();
7026     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7027            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7028     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7029     return DAG.getBuildVector(
7030         MVT::v2i32, SDLoc(N),
7031         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7032   }
7033   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7034   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7035   EVT VT = N->getValueType(0);
7036   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7037   unsigned NumElts = VT.getVectorNumElements();
7038   MVT TruncVT = MVT::getIntegerVT(EltSize);
7039   SmallVector<SDValue, 8> Ops;
7040   SDLoc dl(N);
7041   for (unsigned i = 0; i != NumElts; ++i) {
7042     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7043     const APInt &CInt = C->getAPIntValue();
7044     // Element types smaller than 32 bits are not legal, so use i32 elements.
7045     // The values are implicitly truncated so sext vs. zext doesn't matter.
7046     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7047   }
7048   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7049 }
7050 
7051 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7052   unsigned Opcode = N->getOpcode();
7053   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7054     SDNode *N0 = N->getOperand(0).getNode();
7055     SDNode *N1 = N->getOperand(1).getNode();
7056     return N0->hasOneUse() && N1->hasOneUse() &&
7057       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7058   }
7059   return false;
7060 }
7061 
7062 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7063   unsigned Opcode = N->getOpcode();
7064   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7065     SDNode *N0 = N->getOperand(0).getNode();
7066     SDNode *N1 = N->getOperand(1).getNode();
7067     return N0->hasOneUse() && N1->hasOneUse() &&
7068       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7069   }
7070   return false;
7071 }
7072 
7073 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7074   // Multiplications are only custom-lowered for 128-bit vectors so that
7075   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7076   EVT VT = Op.getValueType();
7077   assert(VT.is128BitVector() && VT.isInteger() &&
7078          "unexpected type for custom-lowering ISD::MUL");
7079   SDNode *N0 = Op.getOperand(0).getNode();
7080   SDNode *N1 = Op.getOperand(1).getNode();
7081   unsigned NewOpc = 0;
7082   bool isMLA = false;
7083   bool isN0SExt = isSignExtended(N0, DAG);
7084   bool isN1SExt = isSignExtended(N1, DAG);
7085   if (isN0SExt && isN1SExt)
7086     NewOpc = ARMISD::VMULLs;
7087   else {
7088     bool isN0ZExt = isZeroExtended(N0, DAG);
7089     bool isN1ZExt = isZeroExtended(N1, DAG);
7090     if (isN0ZExt && isN1ZExt)
7091       NewOpc = ARMISD::VMULLu;
7092     else if (isN1SExt || isN1ZExt) {
7093       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7094       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7095       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7096         NewOpc = ARMISD::VMULLs;
7097         isMLA = true;
7098       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7099         NewOpc = ARMISD::VMULLu;
7100         isMLA = true;
7101       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7102         std::swap(N0, N1);
7103         NewOpc = ARMISD::VMULLu;
7104         isMLA = true;
7105       }
7106     }
7107 
7108     if (!NewOpc) {
7109       if (VT == MVT::v2i64)
7110         // Fall through to expand this.  It is not legal.
7111         return SDValue();
7112       else
7113         // Other vector multiplications are legal.
7114         return Op;
7115     }
7116   }
7117 
7118   // Legalize to a VMULL instruction.
7119   SDLoc DL(Op);
7120   SDValue Op0;
7121   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7122   if (!isMLA) {
7123     Op0 = SkipExtensionForVMULL(N0, DAG);
7124     assert(Op0.getValueType().is64BitVector() &&
7125            Op1.getValueType().is64BitVector() &&
7126            "unexpected types for extended operands to VMULL");
7127     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7128   }
7129 
7130   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7131   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7132   //   vmull q0, d4, d6
7133   //   vmlal q0, d5, d6
7134   // is faster than
7135   //   vaddl q0, d4, d5
7136   //   vmovl q1, d6
7137   //   vmul  q0, q0, q1
7138   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7139   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7140   EVT Op1VT = Op1.getValueType();
7141   return DAG.getNode(N0->getOpcode(), DL, VT,
7142                      DAG.getNode(NewOpc, DL, VT,
7143                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7144                      DAG.getNode(NewOpc, DL, VT,
7145                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7146 }
7147 
7148 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7149                               SelectionDAG &DAG) {
7150   // TODO: Should this propagate fast-math-flags?
7151 
7152   // Convert to float
7153   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7154   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7155   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7156   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7157   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7158   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7159   // Get reciprocal estimate.
7160   // float4 recip = vrecpeq_f32(yf);
7161   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7162                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7163                    Y);
7164   // Because char has a smaller range than uchar, we can actually get away
7165   // without any newton steps.  This requires that we use a weird bias
7166   // of 0xb000, however (again, this has been exhaustively tested).
7167   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7168   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7169   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7170   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7171   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7172   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7173   // Convert back to short.
7174   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7175   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7176   return X;
7177 }
7178 
7179 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7180                                SelectionDAG &DAG) {
7181   // TODO: Should this propagate fast-math-flags?
7182 
7183   SDValue N2;
7184   // Convert to float.
7185   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7186   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7187   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7188   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7189   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7190   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7191 
7192   // Use reciprocal estimate and one refinement step.
7193   // float4 recip = vrecpeq_f32(yf);
7194   // recip *= vrecpsq_f32(yf, recip);
7195   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7196                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7197                    N1);
7198   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7199                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7200                    N1, N2);
7201   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7202   // Because short has a smaller range than ushort, we can actually get away
7203   // with only a single newton step.  This requires that we use a weird bias
7204   // of 89, however (again, this has been exhaustively tested).
7205   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7206   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7207   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7208   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7209   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7210   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7211   // Convert back to integer and return.
7212   // return vmovn_s32(vcvt_s32_f32(result));
7213   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7214   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7215   return N0;
7216 }
7217 
7218 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7219   EVT VT = Op.getValueType();
7220   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7221          "unexpected type for custom-lowering ISD::SDIV");
7222 
7223   SDLoc dl(Op);
7224   SDValue N0 = Op.getOperand(0);
7225   SDValue N1 = Op.getOperand(1);
7226   SDValue N2, N3;
7227 
7228   if (VT == MVT::v8i8) {
7229     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7230     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7231 
7232     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7233                      DAG.getIntPtrConstant(4, dl));
7234     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7235                      DAG.getIntPtrConstant(4, dl));
7236     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7237                      DAG.getIntPtrConstant(0, dl));
7238     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7239                      DAG.getIntPtrConstant(0, dl));
7240 
7241     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7242     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7243 
7244     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7245     N0 = LowerCONCAT_VECTORS(N0, DAG);
7246 
7247     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7248     return N0;
7249   }
7250   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7251 }
7252 
7253 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7254   // TODO: Should this propagate fast-math-flags?
7255   EVT VT = Op.getValueType();
7256   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7257          "unexpected type for custom-lowering ISD::UDIV");
7258 
7259   SDLoc dl(Op);
7260   SDValue N0 = Op.getOperand(0);
7261   SDValue N1 = Op.getOperand(1);
7262   SDValue N2, N3;
7263 
7264   if (VT == MVT::v8i8) {
7265     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7266     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7267 
7268     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7269                      DAG.getIntPtrConstant(4, dl));
7270     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7271                      DAG.getIntPtrConstant(4, dl));
7272     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7273                      DAG.getIntPtrConstant(0, dl));
7274     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7275                      DAG.getIntPtrConstant(0, dl));
7276 
7277     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7278     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7279 
7280     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7281     N0 = LowerCONCAT_VECTORS(N0, DAG);
7282 
7283     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7284                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7285                                      MVT::i32),
7286                      N0);
7287     return N0;
7288   }
7289 
7290   // v4i16 sdiv ... Convert to float.
7291   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7292   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7293   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7294   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7295   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7296   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7297 
7298   // Use reciprocal estimate and two refinement steps.
7299   // float4 recip = vrecpeq_f32(yf);
7300   // recip *= vrecpsq_f32(yf, recip);
7301   // recip *= vrecpsq_f32(yf, recip);
7302   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7303                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7304                    BN1);
7305   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7306                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7307                    BN1, N2);
7308   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7309   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7310                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7311                    BN1, N2);
7312   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7313   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7314   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7315   // and that it will never cause us to return an answer too large).
7316   // float4 result = as_float4(as_int4(xf*recip) + 2);
7317   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7318   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7319   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7320   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7321   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7322   // Convert back to integer and return.
7323   // return vmovn_u32(vcvt_s32_f32(result));
7324   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7325   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7326   return N0;
7327 }
7328 
7329 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7330   EVT VT = Op.getNode()->getValueType(0);
7331   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7332 
7333   unsigned Opc;
7334   bool ExtraOp = false;
7335   switch (Op.getOpcode()) {
7336   default: llvm_unreachable("Invalid code");
7337   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7338   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7339   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7340   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7341   }
7342 
7343   if (!ExtraOp)
7344     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7345                        Op.getOperand(1));
7346   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7347                      Op.getOperand(1), Op.getOperand(2));
7348 }
7349 
7350 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7351   assert(Subtarget->isTargetDarwin());
7352 
7353   // For iOS, we want to call an alternative entry point: __sincos_stret,
7354   // return values are passed via sret.
7355   SDLoc dl(Op);
7356   SDValue Arg = Op.getOperand(0);
7357   EVT ArgVT = Arg.getValueType();
7358   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7359   auto PtrVT = getPointerTy(DAG.getDataLayout());
7360 
7361   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7363 
7364   // Pair of floats / doubles used to pass the result.
7365   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7366   auto &DL = DAG.getDataLayout();
7367 
7368   ArgListTy Args;
7369   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7370   SDValue SRet;
7371   if (ShouldUseSRet) {
7372     // Create stack object for sret.
7373     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7374     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7375     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7376     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7377 
7378     ArgListEntry Entry;
7379     Entry.Node = SRet;
7380     Entry.Ty = RetTy->getPointerTo();
7381     Entry.IsSExt = false;
7382     Entry.IsZExt = false;
7383     Entry.IsSRet = true;
7384     Args.push_back(Entry);
7385     RetTy = Type::getVoidTy(*DAG.getContext());
7386   }
7387 
7388   ArgListEntry Entry;
7389   Entry.Node = Arg;
7390   Entry.Ty = ArgTy;
7391   Entry.IsSExt = false;
7392   Entry.IsZExt = false;
7393   Args.push_back(Entry);
7394 
7395   const char *LibcallName =
7396       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7397   RTLIB::Libcall LC =
7398       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7399   CallingConv::ID CC = getLibcallCallingConv(LC);
7400   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7401 
7402   TargetLowering::CallLoweringInfo CLI(DAG);
7403   CLI.setDebugLoc(dl)
7404       .setChain(DAG.getEntryNode())
7405       .setCallee(CC, RetTy, Callee, std::move(Args))
7406       .setDiscardResult(ShouldUseSRet);
7407   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7408 
7409   if (!ShouldUseSRet)
7410     return CallResult.first;
7411 
7412   SDValue LoadSin =
7413       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7414 
7415   // Address of cos field.
7416   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7417                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7418   SDValue LoadCos =
7419       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7420 
7421   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7422   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7423                      LoadSin.getValue(0), LoadCos.getValue(0));
7424 }
7425 
7426 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7427                                                   bool Signed,
7428                                                   SDValue &Chain) const {
7429   EVT VT = Op.getValueType();
7430   assert((VT == MVT::i32 || VT == MVT::i64) &&
7431          "unexpected type for custom lowering DIV");
7432   SDLoc dl(Op);
7433 
7434   const auto &DL = DAG.getDataLayout();
7435   const auto &TLI = DAG.getTargetLoweringInfo();
7436 
7437   const char *Name = nullptr;
7438   if (Signed)
7439     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7440   else
7441     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7442 
7443   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7444 
7445   ARMTargetLowering::ArgListTy Args;
7446 
7447   for (auto AI : {1, 0}) {
7448     ArgListEntry Arg;
7449     Arg.Node = Op.getOperand(AI);
7450     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7451     Args.push_back(Arg);
7452   }
7453 
7454   CallLoweringInfo CLI(DAG);
7455   CLI.setDebugLoc(dl)
7456     .setChain(Chain)
7457     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7458                ES, std::move(Args));
7459 
7460   return LowerCallTo(CLI).first;
7461 }
7462 
7463 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7464                                             bool Signed) const {
7465   assert(Op.getValueType() == MVT::i32 &&
7466          "unexpected type for custom lowering DIV");
7467   SDLoc dl(Op);
7468 
7469   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7470                                DAG.getEntryNode(), Op.getOperand(1));
7471 
7472   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7473 }
7474 
7475 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7476   SDLoc DL(N);
7477   SDValue Op = N->getOperand(1);
7478   if (N->getValueType(0) == MVT::i32)
7479     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7480   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7481                            DAG.getConstant(0, DL, MVT::i32));
7482   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7483                            DAG.getConstant(1, DL, MVT::i32));
7484   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7485                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7486 }
7487 
7488 void ARMTargetLowering::ExpandDIV_Windows(
7489     SDValue Op, SelectionDAG &DAG, bool Signed,
7490     SmallVectorImpl<SDValue> &Results) const {
7491   const auto &DL = DAG.getDataLayout();
7492   const auto &TLI = DAG.getTargetLoweringInfo();
7493 
7494   assert(Op.getValueType() == MVT::i64 &&
7495          "unexpected type for custom lowering DIV");
7496   SDLoc dl(Op);
7497 
7498   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7499 
7500   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7501 
7502   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7503   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7504                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7505   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7506 
7507   Results.push_back(Lower);
7508   Results.push_back(Upper);
7509 }
7510 
7511 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7512   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7513     // Acquire/Release load/store is not legal for targets without a dmb or
7514     // equivalent available.
7515     return SDValue();
7516 
7517   // Monotonic load/store is legal for all targets.
7518   return Op;
7519 }
7520 
7521 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7522                                     SmallVectorImpl<SDValue> &Results,
7523                                     SelectionDAG &DAG,
7524                                     const ARMSubtarget *Subtarget) {
7525   SDLoc DL(N);
7526   // Under Power Management extensions, the cycle-count is:
7527   //    mrc p15, #0, <Rt>, c9, c13, #0
7528   SDValue Ops[] = { N->getOperand(0), // Chain
7529                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7530                     DAG.getConstant(15, DL, MVT::i32),
7531                     DAG.getConstant(0, DL, MVT::i32),
7532                     DAG.getConstant(9, DL, MVT::i32),
7533                     DAG.getConstant(13, DL, MVT::i32),
7534                     DAG.getConstant(0, DL, MVT::i32)
7535   };
7536 
7537   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7538                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7539   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7540                                 DAG.getConstant(0, DL, MVT::i32)));
7541   Results.push_back(Cycles32.getValue(1));
7542 }
7543 
7544 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7545   SDLoc dl(V.getNode());
7546   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7547   SDValue VHi = DAG.getAnyExtOrTrunc(
7548       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7549       dl, MVT::i32);
7550   SDValue RegClass =
7551       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7552   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7553   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7554   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7555   return SDValue(
7556       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7557 }
7558 
7559 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7560                                        SmallVectorImpl<SDValue> & Results,
7561                                        SelectionDAG &DAG) {
7562   assert(N->getValueType(0) == MVT::i64 &&
7563          "AtomicCmpSwap on types less than 64 should be legal");
7564   SDValue Ops[] = {N->getOperand(1),
7565                    createGPRPairNode(DAG, N->getOperand(2)),
7566                    createGPRPairNode(DAG, N->getOperand(3)),
7567                    N->getOperand(0)};
7568   SDNode *CmpSwap = DAG.getMachineNode(
7569       ARM::CMP_SWAP_64, SDLoc(N),
7570       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7571 
7572   MachineFunction &MF = DAG.getMachineFunction();
7573   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7574   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7575   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7576 
7577   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7578                                                SDValue(CmpSwap, 0)));
7579   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7580                                                SDValue(CmpSwap, 0)));
7581   Results.push_back(SDValue(CmpSwap, 2));
7582 }
7583 
7584 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7585                           SelectionDAG &DAG) {
7586   const auto &TLI = DAG.getTargetLoweringInfo();
7587 
7588   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7589          "Custom lowering is MSVCRT specific!");
7590 
7591   SDLoc dl(Op);
7592   SDValue Val = Op.getOperand(0);
7593   MVT Ty = Val->getSimpleValueType(0);
7594   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7595   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7596                                          TLI.getPointerTy(DAG.getDataLayout()));
7597 
7598   TargetLowering::ArgListTy Args;
7599   TargetLowering::ArgListEntry Entry;
7600 
7601   Entry.Node = Val;
7602   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7603   Entry.IsZExt = true;
7604   Args.push_back(Entry);
7605 
7606   Entry.Node = Exponent;
7607   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7608   Entry.IsZExt = true;
7609   Args.push_back(Entry);
7610 
7611   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7612 
7613   // In the in-chain to the call is the entry node  If we are emitting a
7614   // tailcall, the chain will be mutated if the node has a non-entry input
7615   // chain.
7616   SDValue InChain = DAG.getEntryNode();
7617   SDValue TCChain = InChain;
7618 
7619   const auto *F = DAG.getMachineFunction().getFunction();
7620   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7621               F->getReturnType() == LCRTy;
7622   if (IsTC)
7623     InChain = TCChain;
7624 
7625   TargetLowering::CallLoweringInfo CLI(DAG);
7626   CLI.setDebugLoc(dl)
7627       .setChain(InChain)
7628       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7629       .setTailCall(IsTC);
7630   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7631 
7632   // Return the chain (the DAG root) if it is a tail call
7633   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7634 }
7635 
7636 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7637   switch (Op.getOpcode()) {
7638   default: llvm_unreachable("Don't know how to custom lower this!");
7639   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7640   case ISD::ConstantPool:
7641     if (Subtarget->genExecuteOnly())
7642       llvm_unreachable("execute-only should not generate constant pools");
7643     return LowerConstantPool(Op, DAG);
7644   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7645   case ISD::GlobalAddress:
7646     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7647     default: llvm_unreachable("unknown object format");
7648     case Triple::COFF:
7649       return LowerGlobalAddressWindows(Op, DAG);
7650     case Triple::ELF:
7651       return LowerGlobalAddressELF(Op, DAG);
7652     case Triple::MachO:
7653       return LowerGlobalAddressDarwin(Op, DAG);
7654     }
7655   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7656   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7657   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7658   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7659   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7660   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7661   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7662   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7663   case ISD::SINT_TO_FP:
7664   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7665   case ISD::FP_TO_SINT:
7666   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7667   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7668   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7669   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7670   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7671   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7672   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7673   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7674                                                                Subtarget);
7675   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7676   case ISD::SHL:
7677   case ISD::SRL:
7678   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7679   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7680   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7681   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7682   case ISD::SRL_PARTS:
7683   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7684   case ISD::CTTZ:
7685   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7686   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7687   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7688   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7689   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7690   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7691   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7692   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7693   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7694   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7695   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7696   case ISD::MUL:           return LowerMUL(Op, DAG);
7697   case ISD::SDIV:
7698     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7699       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7700     return LowerSDIV(Op, DAG);
7701   case ISD::UDIV:
7702     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7703       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7704     return LowerUDIV(Op, DAG);
7705   case ISD::ADDC:
7706   case ISD::ADDE:
7707   case ISD::SUBC:
7708   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7709   case ISD::SADDO:
7710   case ISD::UADDO:
7711   case ISD::SSUBO:
7712   case ISD::USUBO:
7713     return LowerXALUO(Op, DAG);
7714   case ISD::ATOMIC_LOAD:
7715   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7716   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7717   case ISD::SDIVREM:
7718   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7719   case ISD::DYNAMIC_STACKALLOC:
7720     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7721       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7722     llvm_unreachable("Don't know how to custom lower this!");
7723   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7724   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7725   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7726   case ARMISD::WIN__DBZCHK: return SDValue();
7727   }
7728 }
7729 
7730 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7731                                  SelectionDAG &DAG) {
7732   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7733   unsigned Opc = 0;
7734   if (IntNo == Intrinsic::arm_smlald)
7735     Opc = ARMISD::SMLALD;
7736   else if (IntNo == Intrinsic::arm_smlaldx)
7737     Opc = ARMISD::SMLALDX;
7738   else if (IntNo == Intrinsic::arm_smlsld)
7739     Opc = ARMISD::SMLSLD;
7740   else if (IntNo == Intrinsic::arm_smlsldx)
7741     Opc = ARMISD::SMLSLDX;
7742   else
7743     return;
7744 
7745   SDLoc dl(N);
7746   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7747                            N->getOperand(3),
7748                            DAG.getConstant(0, dl, MVT::i32));
7749   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7750                            N->getOperand(3),
7751                            DAG.getConstant(1, dl, MVT::i32));
7752 
7753   SDValue LongMul = DAG.getNode(Opc, dl,
7754                                 DAG.getVTList(MVT::i32, MVT::i32),
7755                                 N->getOperand(1), N->getOperand(2),
7756                                 Lo, Hi);
7757   Results.push_back(LongMul.getValue(0));
7758   Results.push_back(LongMul.getValue(1));
7759 }
7760 
7761 /// ReplaceNodeResults - Replace the results of node with an illegal result
7762 /// type with new values built out of custom code.
7763 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7764                                            SmallVectorImpl<SDValue> &Results,
7765                                            SelectionDAG &DAG) const {
7766   SDValue Res;
7767   switch (N->getOpcode()) {
7768   default:
7769     llvm_unreachable("Don't know how to custom expand this!");
7770   case ISD::READ_REGISTER:
7771     ExpandREAD_REGISTER(N, Results, DAG);
7772     break;
7773   case ISD::BITCAST:
7774     Res = ExpandBITCAST(N, DAG);
7775     break;
7776   case ISD::SRL:
7777   case ISD::SRA:
7778     Res = Expand64BitShift(N, DAG, Subtarget);
7779     break;
7780   case ISD::SREM:
7781   case ISD::UREM:
7782     Res = LowerREM(N, DAG);
7783     break;
7784   case ISD::SDIVREM:
7785   case ISD::UDIVREM:
7786     Res = LowerDivRem(SDValue(N, 0), DAG);
7787     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7788     Results.push_back(Res.getValue(0));
7789     Results.push_back(Res.getValue(1));
7790     return;
7791   case ISD::READCYCLECOUNTER:
7792     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7793     return;
7794   case ISD::UDIV:
7795   case ISD::SDIV:
7796     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7797     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7798                              Results);
7799   case ISD::ATOMIC_CMP_SWAP:
7800     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7801     return;
7802   case ISD::INTRINSIC_WO_CHAIN:
7803     return ReplaceLongIntrinsic(N, Results, DAG);
7804   }
7805   if (Res.getNode())
7806     Results.push_back(Res);
7807 }
7808 
7809 //===----------------------------------------------------------------------===//
7810 //                           ARM Scheduler Hooks
7811 //===----------------------------------------------------------------------===//
7812 
7813 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7814 /// registers the function context.
7815 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7816                                                MachineBasicBlock *MBB,
7817                                                MachineBasicBlock *DispatchBB,
7818                                                int FI) const {
7819   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7820          "ROPI/RWPI not currently supported with SjLj");
7821   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7822   DebugLoc dl = MI.getDebugLoc();
7823   MachineFunction *MF = MBB->getParent();
7824   MachineRegisterInfo *MRI = &MF->getRegInfo();
7825   MachineConstantPool *MCP = MF->getConstantPool();
7826   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7827   const Function *F = MF->getFunction();
7828 
7829   bool isThumb = Subtarget->isThumb();
7830   bool isThumb2 = Subtarget->isThumb2();
7831 
7832   unsigned PCLabelId = AFI->createPICLabelUId();
7833   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7834   ARMConstantPoolValue *CPV =
7835     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7836   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7837 
7838   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7839                                            : &ARM::GPRRegClass;
7840 
7841   // Grab constant pool and fixed stack memory operands.
7842   MachineMemOperand *CPMMO =
7843       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7844                                MachineMemOperand::MOLoad, 4, 4);
7845 
7846   MachineMemOperand *FIMMOSt =
7847       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7848                                MachineMemOperand::MOStore, 4, 4);
7849 
7850   // Load the address of the dispatch MBB into the jump buffer.
7851   if (isThumb2) {
7852     // Incoming value: jbuf
7853     //   ldr.n  r5, LCPI1_1
7854     //   orr    r5, r5, #1
7855     //   add    r5, pc
7856     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7857     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7858     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7859         .addConstantPoolIndex(CPI)
7860         .addMemOperand(CPMMO)
7861         .add(predOps(ARMCC::AL));
7862     // Set the low bit because of thumb mode.
7863     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7864     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7865         .addReg(NewVReg1, RegState::Kill)
7866         .addImm(0x01)
7867         .add(predOps(ARMCC::AL))
7868         .add(condCodeOp());
7869     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7870     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7871       .addReg(NewVReg2, RegState::Kill)
7872       .addImm(PCLabelId);
7873     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7874         .addReg(NewVReg3, RegState::Kill)
7875         .addFrameIndex(FI)
7876         .addImm(36) // &jbuf[1] :: pc
7877         .addMemOperand(FIMMOSt)
7878         .add(predOps(ARMCC::AL));
7879   } else if (isThumb) {
7880     // Incoming value: jbuf
7881     //   ldr.n  r1, LCPI1_4
7882     //   add    r1, pc
7883     //   mov    r2, #1
7884     //   orrs   r1, r2
7885     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7886     //   str    r1, [r2]
7887     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7888     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7889         .addConstantPoolIndex(CPI)
7890         .addMemOperand(CPMMO)
7891         .add(predOps(ARMCC::AL));
7892     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7893     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7894       .addReg(NewVReg1, RegState::Kill)
7895       .addImm(PCLabelId);
7896     // Set the low bit because of thumb mode.
7897     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7898     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7899         .addReg(ARM::CPSR, RegState::Define)
7900         .addImm(1)
7901         .add(predOps(ARMCC::AL));
7902     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7903     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7904         .addReg(ARM::CPSR, RegState::Define)
7905         .addReg(NewVReg2, RegState::Kill)
7906         .addReg(NewVReg3, RegState::Kill)
7907         .add(predOps(ARMCC::AL));
7908     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7909     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7910             .addFrameIndex(FI)
7911             .addImm(36); // &jbuf[1] :: pc
7912     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7913         .addReg(NewVReg4, RegState::Kill)
7914         .addReg(NewVReg5, RegState::Kill)
7915         .addImm(0)
7916         .addMemOperand(FIMMOSt)
7917         .add(predOps(ARMCC::AL));
7918   } else {
7919     // Incoming value: jbuf
7920     //   ldr  r1, LCPI1_1
7921     //   add  r1, pc, r1
7922     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7923     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7924     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7925         .addConstantPoolIndex(CPI)
7926         .addImm(0)
7927         .addMemOperand(CPMMO)
7928         .add(predOps(ARMCC::AL));
7929     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7930     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7931         .addReg(NewVReg1, RegState::Kill)
7932         .addImm(PCLabelId)
7933         .add(predOps(ARMCC::AL));
7934     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7935         .addReg(NewVReg2, RegState::Kill)
7936         .addFrameIndex(FI)
7937         .addImm(36) // &jbuf[1] :: pc
7938         .addMemOperand(FIMMOSt)
7939         .add(predOps(ARMCC::AL));
7940   }
7941 }
7942 
7943 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7944                                               MachineBasicBlock *MBB) const {
7945   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7946   DebugLoc dl = MI.getDebugLoc();
7947   MachineFunction *MF = MBB->getParent();
7948   MachineRegisterInfo *MRI = &MF->getRegInfo();
7949   MachineFrameInfo &MFI = MF->getFrameInfo();
7950   int FI = MFI.getFunctionContextIndex();
7951 
7952   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7953                                                         : &ARM::GPRnopcRegClass;
7954 
7955   // Get a mapping of the call site numbers to all of the landing pads they're
7956   // associated with.
7957   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
7958   unsigned MaxCSNum = 0;
7959   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7960        ++BB) {
7961     if (!BB->isEHPad()) continue;
7962 
7963     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7964     // pad.
7965     for (MachineBasicBlock::iterator
7966            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7967       if (!II->isEHLabel()) continue;
7968 
7969       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7970       if (!MF->hasCallSiteLandingPad(Sym)) continue;
7971 
7972       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
7973       for (SmallVectorImpl<unsigned>::iterator
7974              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7975            CSI != CSE; ++CSI) {
7976         CallSiteNumToLPad[*CSI].push_back(&*BB);
7977         MaxCSNum = std::max(MaxCSNum, *CSI);
7978       }
7979       break;
7980     }
7981   }
7982 
7983   // Get an ordered list of the machine basic blocks for the jump table.
7984   std::vector<MachineBasicBlock*> LPadList;
7985   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7986   LPadList.reserve(CallSiteNumToLPad.size());
7987   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7988     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7989     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7990            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7991       LPadList.push_back(*II);
7992       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7993     }
7994   }
7995 
7996   assert(!LPadList.empty() &&
7997          "No landing pad destinations for the dispatch jump table!");
7998 
7999   // Create the jump table and associated information.
8000   MachineJumpTableInfo *JTI =
8001     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8002   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8003 
8004   // Create the MBBs for the dispatch code.
8005 
8006   // Shove the dispatch's address into the return slot in the function context.
8007   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8008   DispatchBB->setIsEHPad();
8009 
8010   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8011   unsigned trap_opcode;
8012   if (Subtarget->isThumb())
8013     trap_opcode = ARM::tTRAP;
8014   else
8015     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8016 
8017   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8018   DispatchBB->addSuccessor(TrapBB);
8019 
8020   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8021   DispatchBB->addSuccessor(DispContBB);
8022 
8023   // Insert and MBBs.
8024   MF->insert(MF->end(), DispatchBB);
8025   MF->insert(MF->end(), DispContBB);
8026   MF->insert(MF->end(), TrapBB);
8027 
8028   // Insert code into the entry block that creates and registers the function
8029   // context.
8030   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8031 
8032   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8033       MachinePointerInfo::getFixedStack(*MF, FI),
8034       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8035 
8036   MachineInstrBuilder MIB;
8037   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8038 
8039   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8040   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8041 
8042   // Add a register mask with no preserved registers.  This results in all
8043   // registers being marked as clobbered. This can't work if the dispatch block
8044   // is in a Thumb1 function and is linked with ARM code which uses the FP
8045   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8046   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8047 
8048   bool IsPositionIndependent = isPositionIndependent();
8049   unsigned NumLPads = LPadList.size();
8050   if (Subtarget->isThumb2()) {
8051     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8052     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8053         .addFrameIndex(FI)
8054         .addImm(4)
8055         .addMemOperand(FIMMOLd)
8056         .add(predOps(ARMCC::AL));
8057 
8058     if (NumLPads < 256) {
8059       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8060           .addReg(NewVReg1)
8061           .addImm(LPadList.size())
8062           .add(predOps(ARMCC::AL));
8063     } else {
8064       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8065       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8066           .addImm(NumLPads & 0xFFFF)
8067           .add(predOps(ARMCC::AL));
8068 
8069       unsigned VReg2 = VReg1;
8070       if ((NumLPads & 0xFFFF0000) != 0) {
8071         VReg2 = MRI->createVirtualRegister(TRC);
8072         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8073             .addReg(VReg1)
8074             .addImm(NumLPads >> 16)
8075             .add(predOps(ARMCC::AL));
8076       }
8077 
8078       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8079           .addReg(NewVReg1)
8080           .addReg(VReg2)
8081           .add(predOps(ARMCC::AL));
8082     }
8083 
8084     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8085       .addMBB(TrapBB)
8086       .addImm(ARMCC::HI)
8087       .addReg(ARM::CPSR);
8088 
8089     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8090     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8091         .addJumpTableIndex(MJTI)
8092         .add(predOps(ARMCC::AL));
8093 
8094     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8095     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8096         .addReg(NewVReg3, RegState::Kill)
8097         .addReg(NewVReg1)
8098         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8099         .add(predOps(ARMCC::AL))
8100         .add(condCodeOp());
8101 
8102     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8103       .addReg(NewVReg4, RegState::Kill)
8104       .addReg(NewVReg1)
8105       .addJumpTableIndex(MJTI);
8106   } else if (Subtarget->isThumb()) {
8107     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8108     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8109         .addFrameIndex(FI)
8110         .addImm(1)
8111         .addMemOperand(FIMMOLd)
8112         .add(predOps(ARMCC::AL));
8113 
8114     if (NumLPads < 256) {
8115       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8116           .addReg(NewVReg1)
8117           .addImm(NumLPads)
8118           .add(predOps(ARMCC::AL));
8119     } else {
8120       MachineConstantPool *ConstantPool = MF->getConstantPool();
8121       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8122       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8123 
8124       // MachineConstantPool wants an explicit alignment.
8125       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8126       if (Align == 0)
8127         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8128       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8129 
8130       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8131       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8132           .addReg(VReg1, RegState::Define)
8133           .addConstantPoolIndex(Idx)
8134           .add(predOps(ARMCC::AL));
8135       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8136           .addReg(NewVReg1)
8137           .addReg(VReg1)
8138           .add(predOps(ARMCC::AL));
8139     }
8140 
8141     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8142       .addMBB(TrapBB)
8143       .addImm(ARMCC::HI)
8144       .addReg(ARM::CPSR);
8145 
8146     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8147     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8148         .addReg(ARM::CPSR, RegState::Define)
8149         .addReg(NewVReg1)
8150         .addImm(2)
8151         .add(predOps(ARMCC::AL));
8152 
8153     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8154     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8155         .addJumpTableIndex(MJTI)
8156         .add(predOps(ARMCC::AL));
8157 
8158     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8159     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8160         .addReg(ARM::CPSR, RegState::Define)
8161         .addReg(NewVReg2, RegState::Kill)
8162         .addReg(NewVReg3)
8163         .add(predOps(ARMCC::AL));
8164 
8165     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8166         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8167 
8168     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8169     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8170         .addReg(NewVReg4, RegState::Kill)
8171         .addImm(0)
8172         .addMemOperand(JTMMOLd)
8173         .add(predOps(ARMCC::AL));
8174 
8175     unsigned NewVReg6 = NewVReg5;
8176     if (IsPositionIndependent) {
8177       NewVReg6 = MRI->createVirtualRegister(TRC);
8178       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8179           .addReg(ARM::CPSR, RegState::Define)
8180           .addReg(NewVReg5, RegState::Kill)
8181           .addReg(NewVReg3)
8182           .add(predOps(ARMCC::AL));
8183     }
8184 
8185     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8186       .addReg(NewVReg6, RegState::Kill)
8187       .addJumpTableIndex(MJTI);
8188   } else {
8189     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8190     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8191         .addFrameIndex(FI)
8192         .addImm(4)
8193         .addMemOperand(FIMMOLd)
8194         .add(predOps(ARMCC::AL));
8195 
8196     if (NumLPads < 256) {
8197       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8198           .addReg(NewVReg1)
8199           .addImm(NumLPads)
8200           .add(predOps(ARMCC::AL));
8201     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8202       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8203       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8204           .addImm(NumLPads & 0xFFFF)
8205           .add(predOps(ARMCC::AL));
8206 
8207       unsigned VReg2 = VReg1;
8208       if ((NumLPads & 0xFFFF0000) != 0) {
8209         VReg2 = MRI->createVirtualRegister(TRC);
8210         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8211             .addReg(VReg1)
8212             .addImm(NumLPads >> 16)
8213             .add(predOps(ARMCC::AL));
8214       }
8215 
8216       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8217           .addReg(NewVReg1)
8218           .addReg(VReg2)
8219           .add(predOps(ARMCC::AL));
8220     } else {
8221       MachineConstantPool *ConstantPool = MF->getConstantPool();
8222       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8223       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8224 
8225       // MachineConstantPool wants an explicit alignment.
8226       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8227       if (Align == 0)
8228         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8229       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8230 
8231       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8232       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8233           .addReg(VReg1, RegState::Define)
8234           .addConstantPoolIndex(Idx)
8235           .addImm(0)
8236           .add(predOps(ARMCC::AL));
8237       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8238           .addReg(NewVReg1)
8239           .addReg(VReg1, RegState::Kill)
8240           .add(predOps(ARMCC::AL));
8241     }
8242 
8243     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8244       .addMBB(TrapBB)
8245       .addImm(ARMCC::HI)
8246       .addReg(ARM::CPSR);
8247 
8248     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8249     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8250         .addReg(NewVReg1)
8251         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8252         .add(predOps(ARMCC::AL))
8253         .add(condCodeOp());
8254     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8255     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8256         .addJumpTableIndex(MJTI)
8257         .add(predOps(ARMCC::AL));
8258 
8259     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8260         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8261     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8262     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8263         .addReg(NewVReg3, RegState::Kill)
8264         .addReg(NewVReg4)
8265         .addImm(0)
8266         .addMemOperand(JTMMOLd)
8267         .add(predOps(ARMCC::AL));
8268 
8269     if (IsPositionIndependent) {
8270       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8271         .addReg(NewVReg5, RegState::Kill)
8272         .addReg(NewVReg4)
8273         .addJumpTableIndex(MJTI);
8274     } else {
8275       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8276         .addReg(NewVReg5, RegState::Kill)
8277         .addJumpTableIndex(MJTI);
8278     }
8279   }
8280 
8281   // Add the jump table entries as successors to the MBB.
8282   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8283   for (std::vector<MachineBasicBlock*>::iterator
8284          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8285     MachineBasicBlock *CurMBB = *I;
8286     if (SeenMBBs.insert(CurMBB).second)
8287       DispContBB->addSuccessor(CurMBB);
8288   }
8289 
8290   // N.B. the order the invoke BBs are processed in doesn't matter here.
8291   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8292   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8293   for (MachineBasicBlock *BB : InvokeBBs) {
8294 
8295     // Remove the landing pad successor from the invoke block and replace it
8296     // with the new dispatch block.
8297     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8298                                                   BB->succ_end());
8299     while (!Successors.empty()) {
8300       MachineBasicBlock *SMBB = Successors.pop_back_val();
8301       if (SMBB->isEHPad()) {
8302         BB->removeSuccessor(SMBB);
8303         MBBLPads.push_back(SMBB);
8304       }
8305     }
8306 
8307     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8308     BB->normalizeSuccProbs();
8309 
8310     // Find the invoke call and mark all of the callee-saved registers as
8311     // 'implicit defined' so that they're spilled. This prevents code from
8312     // moving instructions to before the EH block, where they will never be
8313     // executed.
8314     for (MachineBasicBlock::reverse_iterator
8315            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8316       if (!II->isCall()) continue;
8317 
8318       DenseMap<unsigned, bool> DefRegs;
8319       for (MachineInstr::mop_iterator
8320              OI = II->operands_begin(), OE = II->operands_end();
8321            OI != OE; ++OI) {
8322         if (!OI->isReg()) continue;
8323         DefRegs[OI->getReg()] = true;
8324       }
8325 
8326       MachineInstrBuilder MIB(*MF, &*II);
8327 
8328       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8329         unsigned Reg = SavedRegs[i];
8330         if (Subtarget->isThumb2() &&
8331             !ARM::tGPRRegClass.contains(Reg) &&
8332             !ARM::hGPRRegClass.contains(Reg))
8333           continue;
8334         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8335           continue;
8336         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8337           continue;
8338         if (!DefRegs[Reg])
8339           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8340       }
8341 
8342       break;
8343     }
8344   }
8345 
8346   // Mark all former landing pads as non-landing pads. The dispatch is the only
8347   // landing pad now.
8348   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8349          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8350     (*I)->setIsEHPad(false);
8351 
8352   // The instruction is gone now.
8353   MI.eraseFromParent();
8354 }
8355 
8356 static
8357 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8358   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8359        E = MBB->succ_end(); I != E; ++I)
8360     if (*I != Succ)
8361       return *I;
8362   llvm_unreachable("Expecting a BB with two successors!");
8363 }
8364 
8365 /// Return the load opcode for a given load size. If load size >= 8,
8366 /// neon opcode will be returned.
8367 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8368   if (LdSize >= 8)
8369     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8370                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8371   if (IsThumb1)
8372     return LdSize == 4 ? ARM::tLDRi
8373                        : LdSize == 2 ? ARM::tLDRHi
8374                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8375   if (IsThumb2)
8376     return LdSize == 4 ? ARM::t2LDR_POST
8377                        : LdSize == 2 ? ARM::t2LDRH_POST
8378                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8379   return LdSize == 4 ? ARM::LDR_POST_IMM
8380                      : LdSize == 2 ? ARM::LDRH_POST
8381                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8382 }
8383 
8384 /// Return the store opcode for a given store size. If store size >= 8,
8385 /// neon opcode will be returned.
8386 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8387   if (StSize >= 8)
8388     return StSize == 16 ? ARM::VST1q32wb_fixed
8389                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8390   if (IsThumb1)
8391     return StSize == 4 ? ARM::tSTRi
8392                        : StSize == 2 ? ARM::tSTRHi
8393                                      : StSize == 1 ? ARM::tSTRBi : 0;
8394   if (IsThumb2)
8395     return StSize == 4 ? ARM::t2STR_POST
8396                        : StSize == 2 ? ARM::t2STRH_POST
8397                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8398   return StSize == 4 ? ARM::STR_POST_IMM
8399                      : StSize == 2 ? ARM::STRH_POST
8400                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8401 }
8402 
8403 /// Emit a post-increment load operation with given size. The instructions
8404 /// will be added to BB at Pos.
8405 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8406                        const TargetInstrInfo *TII, const DebugLoc &dl,
8407                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8408                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8409   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8410   assert(LdOpc != 0 && "Should have a load opcode");
8411   if (LdSize >= 8) {
8412     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8413         .addReg(AddrOut, RegState::Define)
8414         .addReg(AddrIn)
8415         .addImm(0)
8416         .add(predOps(ARMCC::AL));
8417   } else if (IsThumb1) {
8418     // load + update AddrIn
8419     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8420         .addReg(AddrIn)
8421         .addImm(0)
8422         .add(predOps(ARMCC::AL));
8423     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8424         .add(t1CondCodeOp())
8425         .addReg(AddrIn)
8426         .addImm(LdSize)
8427         .add(predOps(ARMCC::AL));
8428   } else if (IsThumb2) {
8429     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8430         .addReg(AddrOut, RegState::Define)
8431         .addReg(AddrIn)
8432         .addImm(LdSize)
8433         .add(predOps(ARMCC::AL));
8434   } else { // arm
8435     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8436         .addReg(AddrOut, RegState::Define)
8437         .addReg(AddrIn)
8438         .addReg(0)
8439         .addImm(LdSize)
8440         .add(predOps(ARMCC::AL));
8441   }
8442 }
8443 
8444 /// Emit a post-increment store operation with given size. The instructions
8445 /// will be added to BB at Pos.
8446 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8447                        const TargetInstrInfo *TII, const DebugLoc &dl,
8448                        unsigned StSize, unsigned Data, unsigned AddrIn,
8449                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8450   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8451   assert(StOpc != 0 && "Should have a store opcode");
8452   if (StSize >= 8) {
8453     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8454         .addReg(AddrIn)
8455         .addImm(0)
8456         .addReg(Data)
8457         .add(predOps(ARMCC::AL));
8458   } else if (IsThumb1) {
8459     // store + update AddrIn
8460     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8461         .addReg(Data)
8462         .addReg(AddrIn)
8463         .addImm(0)
8464         .add(predOps(ARMCC::AL));
8465     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8466         .add(t1CondCodeOp())
8467         .addReg(AddrIn)
8468         .addImm(StSize)
8469         .add(predOps(ARMCC::AL));
8470   } else if (IsThumb2) {
8471     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8472         .addReg(Data)
8473         .addReg(AddrIn)
8474         .addImm(StSize)
8475         .add(predOps(ARMCC::AL));
8476   } else { // arm
8477     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8478         .addReg(Data)
8479         .addReg(AddrIn)
8480         .addReg(0)
8481         .addImm(StSize)
8482         .add(predOps(ARMCC::AL));
8483   }
8484 }
8485 
8486 MachineBasicBlock *
8487 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8488                                    MachineBasicBlock *BB) const {
8489   // This pseudo instruction has 3 operands: dst, src, size
8490   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8491   // Otherwise, we will generate unrolled scalar copies.
8492   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8493   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8494   MachineFunction::iterator It = ++BB->getIterator();
8495 
8496   unsigned dest = MI.getOperand(0).getReg();
8497   unsigned src = MI.getOperand(1).getReg();
8498   unsigned SizeVal = MI.getOperand(2).getImm();
8499   unsigned Align = MI.getOperand(3).getImm();
8500   DebugLoc dl = MI.getDebugLoc();
8501 
8502   MachineFunction *MF = BB->getParent();
8503   MachineRegisterInfo &MRI = MF->getRegInfo();
8504   unsigned UnitSize = 0;
8505   const TargetRegisterClass *TRC = nullptr;
8506   const TargetRegisterClass *VecTRC = nullptr;
8507 
8508   bool IsThumb1 = Subtarget->isThumb1Only();
8509   bool IsThumb2 = Subtarget->isThumb2();
8510   bool IsThumb = Subtarget->isThumb();
8511 
8512   if (Align & 1) {
8513     UnitSize = 1;
8514   } else if (Align & 2) {
8515     UnitSize = 2;
8516   } else {
8517     // Check whether we can use NEON instructions.
8518     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8519         Subtarget->hasNEON()) {
8520       if ((Align % 16 == 0) && SizeVal >= 16)
8521         UnitSize = 16;
8522       else if ((Align % 8 == 0) && SizeVal >= 8)
8523         UnitSize = 8;
8524     }
8525     // Can't use NEON instructions.
8526     if (UnitSize == 0)
8527       UnitSize = 4;
8528   }
8529 
8530   // Select the correct opcode and register class for unit size load/store
8531   bool IsNeon = UnitSize >= 8;
8532   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8533   if (IsNeon)
8534     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8535                             : UnitSize == 8 ? &ARM::DPRRegClass
8536                                             : nullptr;
8537 
8538   unsigned BytesLeft = SizeVal % UnitSize;
8539   unsigned LoopSize = SizeVal - BytesLeft;
8540 
8541   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8542     // Use LDR and STR to copy.
8543     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8544     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8545     unsigned srcIn = src;
8546     unsigned destIn = dest;
8547     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8548       unsigned srcOut = MRI.createVirtualRegister(TRC);
8549       unsigned destOut = MRI.createVirtualRegister(TRC);
8550       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8551       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8552                  IsThumb1, IsThumb2);
8553       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8554                  IsThumb1, IsThumb2);
8555       srcIn = srcOut;
8556       destIn = destOut;
8557     }
8558 
8559     // Handle the leftover bytes with LDRB and STRB.
8560     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8561     // [destOut] = STRB_POST(scratch, destIn, 1)
8562     for (unsigned i = 0; i < BytesLeft; i++) {
8563       unsigned srcOut = MRI.createVirtualRegister(TRC);
8564       unsigned destOut = MRI.createVirtualRegister(TRC);
8565       unsigned scratch = MRI.createVirtualRegister(TRC);
8566       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8567                  IsThumb1, IsThumb2);
8568       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8569                  IsThumb1, IsThumb2);
8570       srcIn = srcOut;
8571       destIn = destOut;
8572     }
8573     MI.eraseFromParent(); // The instruction is gone now.
8574     return BB;
8575   }
8576 
8577   // Expand the pseudo op to a loop.
8578   // thisMBB:
8579   //   ...
8580   //   movw varEnd, # --> with thumb2
8581   //   movt varEnd, #
8582   //   ldrcp varEnd, idx --> without thumb2
8583   //   fallthrough --> loopMBB
8584   // loopMBB:
8585   //   PHI varPhi, varEnd, varLoop
8586   //   PHI srcPhi, src, srcLoop
8587   //   PHI destPhi, dst, destLoop
8588   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8589   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8590   //   subs varLoop, varPhi, #UnitSize
8591   //   bne loopMBB
8592   //   fallthrough --> exitMBB
8593   // exitMBB:
8594   //   epilogue to handle left-over bytes
8595   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8596   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8597   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8598   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8599   MF->insert(It, loopMBB);
8600   MF->insert(It, exitMBB);
8601 
8602   // Transfer the remainder of BB and its successor edges to exitMBB.
8603   exitMBB->splice(exitMBB->begin(), BB,
8604                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8605   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8606 
8607   // Load an immediate to varEnd.
8608   unsigned varEnd = MRI.createVirtualRegister(TRC);
8609   if (Subtarget->useMovt(*MF)) {
8610     unsigned Vtmp = varEnd;
8611     if ((LoopSize & 0xFFFF0000) != 0)
8612       Vtmp = MRI.createVirtualRegister(TRC);
8613     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8614         .addImm(LoopSize & 0xFFFF)
8615         .add(predOps(ARMCC::AL));
8616 
8617     if ((LoopSize & 0xFFFF0000) != 0)
8618       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8619           .addReg(Vtmp)
8620           .addImm(LoopSize >> 16)
8621           .add(predOps(ARMCC::AL));
8622   } else {
8623     MachineConstantPool *ConstantPool = MF->getConstantPool();
8624     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8625     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8626 
8627     // MachineConstantPool wants an explicit alignment.
8628     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8629     if (Align == 0)
8630       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8631     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8632 
8633     if (IsThumb)
8634       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8635           .addReg(varEnd, RegState::Define)
8636           .addConstantPoolIndex(Idx)
8637           .add(predOps(ARMCC::AL));
8638     else
8639       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8640           .addReg(varEnd, RegState::Define)
8641           .addConstantPoolIndex(Idx)
8642           .addImm(0)
8643           .add(predOps(ARMCC::AL));
8644   }
8645   BB->addSuccessor(loopMBB);
8646 
8647   // Generate the loop body:
8648   //   varPhi = PHI(varLoop, varEnd)
8649   //   srcPhi = PHI(srcLoop, src)
8650   //   destPhi = PHI(destLoop, dst)
8651   MachineBasicBlock *entryBB = BB;
8652   BB = loopMBB;
8653   unsigned varLoop = MRI.createVirtualRegister(TRC);
8654   unsigned varPhi = MRI.createVirtualRegister(TRC);
8655   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8656   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8657   unsigned destLoop = MRI.createVirtualRegister(TRC);
8658   unsigned destPhi = MRI.createVirtualRegister(TRC);
8659 
8660   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8661     .addReg(varLoop).addMBB(loopMBB)
8662     .addReg(varEnd).addMBB(entryBB);
8663   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8664     .addReg(srcLoop).addMBB(loopMBB)
8665     .addReg(src).addMBB(entryBB);
8666   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8667     .addReg(destLoop).addMBB(loopMBB)
8668     .addReg(dest).addMBB(entryBB);
8669 
8670   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8671   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8672   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8673   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8674              IsThumb1, IsThumb2);
8675   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8676              IsThumb1, IsThumb2);
8677 
8678   // Decrement loop variable by UnitSize.
8679   if (IsThumb1) {
8680     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8681         .add(t1CondCodeOp())
8682         .addReg(varPhi)
8683         .addImm(UnitSize)
8684         .add(predOps(ARMCC::AL));
8685   } else {
8686     MachineInstrBuilder MIB =
8687         BuildMI(*BB, BB->end(), dl,
8688                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8689     MIB.addReg(varPhi)
8690         .addImm(UnitSize)
8691         .add(predOps(ARMCC::AL))
8692         .add(condCodeOp());
8693     MIB->getOperand(5).setReg(ARM::CPSR);
8694     MIB->getOperand(5).setIsDef(true);
8695   }
8696   BuildMI(*BB, BB->end(), dl,
8697           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8698       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8699 
8700   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8701   BB->addSuccessor(loopMBB);
8702   BB->addSuccessor(exitMBB);
8703 
8704   // Add epilogue to handle BytesLeft.
8705   BB = exitMBB;
8706   auto StartOfExit = exitMBB->begin();
8707 
8708   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8709   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8710   unsigned srcIn = srcLoop;
8711   unsigned destIn = destLoop;
8712   for (unsigned i = 0; i < BytesLeft; i++) {
8713     unsigned srcOut = MRI.createVirtualRegister(TRC);
8714     unsigned destOut = MRI.createVirtualRegister(TRC);
8715     unsigned scratch = MRI.createVirtualRegister(TRC);
8716     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8717                IsThumb1, IsThumb2);
8718     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8719                IsThumb1, IsThumb2);
8720     srcIn = srcOut;
8721     destIn = destOut;
8722   }
8723 
8724   MI.eraseFromParent(); // The instruction is gone now.
8725   return BB;
8726 }
8727 
8728 MachineBasicBlock *
8729 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8730                                        MachineBasicBlock *MBB) const {
8731   const TargetMachine &TM = getTargetMachine();
8732   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8733   DebugLoc DL = MI.getDebugLoc();
8734 
8735   assert(Subtarget->isTargetWindows() &&
8736          "__chkstk is only supported on Windows");
8737   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8738 
8739   // __chkstk takes the number of words to allocate on the stack in R4, and
8740   // returns the stack adjustment in number of bytes in R4.  This will not
8741   // clober any other registers (other than the obvious lr).
8742   //
8743   // Although, technically, IP should be considered a register which may be
8744   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8745   // thumb-2 environment, so there is no interworking required.  As a result, we
8746   // do not expect a veneer to be emitted by the linker, clobbering IP.
8747   //
8748   // Each module receives its own copy of __chkstk, so no import thunk is
8749   // required, again, ensuring that IP is not clobbered.
8750   //
8751   // Finally, although some linkers may theoretically provide a trampoline for
8752   // out of range calls (which is quite common due to a 32M range limitation of
8753   // branches for Thumb), we can generate the long-call version via
8754   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8755   // IP.
8756 
8757   switch (TM.getCodeModel()) {
8758   case CodeModel::Small:
8759   case CodeModel::Medium:
8760   case CodeModel::Default:
8761   case CodeModel::Kernel:
8762     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8763         .add(predOps(ARMCC::AL))
8764         .addExternalSymbol("__chkstk")
8765         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8766         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8767         .addReg(ARM::R12,
8768                 RegState::Implicit | RegState::Define | RegState::Dead);
8769     break;
8770   case CodeModel::Large:
8771   case CodeModel::JITDefault: {
8772     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8773     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8774 
8775     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8776       .addExternalSymbol("__chkstk");
8777     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8778         .add(predOps(ARMCC::AL))
8779         .addReg(Reg, RegState::Kill)
8780         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8781         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8782         .addReg(ARM::R12,
8783                 RegState::Implicit | RegState::Define | RegState::Dead);
8784     break;
8785   }
8786   }
8787 
8788   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8789       .addReg(ARM::SP, RegState::Kill)
8790       .addReg(ARM::R4, RegState::Kill)
8791       .setMIFlags(MachineInstr::FrameSetup)
8792       .add(predOps(ARMCC::AL))
8793       .add(condCodeOp());
8794 
8795   MI.eraseFromParent();
8796   return MBB;
8797 }
8798 
8799 MachineBasicBlock *
8800 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8801                                        MachineBasicBlock *MBB) const {
8802   DebugLoc DL = MI.getDebugLoc();
8803   MachineFunction *MF = MBB->getParent();
8804   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8805 
8806   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8807   MF->insert(++MBB->getIterator(), ContBB);
8808   ContBB->splice(ContBB->begin(), MBB,
8809                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8810   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8811   MBB->addSuccessor(ContBB);
8812 
8813   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8814   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8815   MF->push_back(TrapBB);
8816   MBB->addSuccessor(TrapBB);
8817 
8818   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8819       .addReg(MI.getOperand(0).getReg())
8820       .addImm(0)
8821       .add(predOps(ARMCC::AL));
8822   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8823       .addMBB(TrapBB)
8824       .addImm(ARMCC::EQ)
8825       .addReg(ARM::CPSR);
8826 
8827   MI.eraseFromParent();
8828   return ContBB;
8829 }
8830 
8831 MachineBasicBlock *
8832 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8833                                                MachineBasicBlock *BB) const {
8834   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8835   DebugLoc dl = MI.getDebugLoc();
8836   bool isThumb2 = Subtarget->isThumb2();
8837   switch (MI.getOpcode()) {
8838   default: {
8839     MI.print(errs());
8840     llvm_unreachable("Unexpected instr type to insert");
8841   }
8842 
8843   // Thumb1 post-indexed loads are really just single-register LDMs.
8844   case ARM::tLDR_postidx: {
8845     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8846         .add(MI.getOperand(1))  // Rn_wb
8847         .add(MI.getOperand(2))  // Rn
8848         .add(MI.getOperand(3))  // PredImm
8849         .add(MI.getOperand(4))  // PredReg
8850         .add(MI.getOperand(0)); // Rt
8851     MI.eraseFromParent();
8852     return BB;
8853   }
8854 
8855   // The Thumb2 pre-indexed stores have the same MI operands, they just
8856   // define them differently in the .td files from the isel patterns, so
8857   // they need pseudos.
8858   case ARM::t2STR_preidx:
8859     MI.setDesc(TII->get(ARM::t2STR_PRE));
8860     return BB;
8861   case ARM::t2STRB_preidx:
8862     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8863     return BB;
8864   case ARM::t2STRH_preidx:
8865     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8866     return BB;
8867 
8868   case ARM::STRi_preidx:
8869   case ARM::STRBi_preidx: {
8870     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8871                                                          : ARM::STRB_PRE_IMM;
8872     // Decode the offset.
8873     unsigned Offset = MI.getOperand(4).getImm();
8874     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8875     Offset = ARM_AM::getAM2Offset(Offset);
8876     if (isSub)
8877       Offset = -Offset;
8878 
8879     MachineMemOperand *MMO = *MI.memoperands_begin();
8880     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8881         .add(MI.getOperand(0)) // Rn_wb
8882         .add(MI.getOperand(1)) // Rt
8883         .add(MI.getOperand(2)) // Rn
8884         .addImm(Offset)        // offset (skip GPR==zero_reg)
8885         .add(MI.getOperand(5)) // pred
8886         .add(MI.getOperand(6))
8887         .addMemOperand(MMO);
8888     MI.eraseFromParent();
8889     return BB;
8890   }
8891   case ARM::STRr_preidx:
8892   case ARM::STRBr_preidx:
8893   case ARM::STRH_preidx: {
8894     unsigned NewOpc;
8895     switch (MI.getOpcode()) {
8896     default: llvm_unreachable("unexpected opcode!");
8897     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8898     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8899     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8900     }
8901     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8902     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8903       MIB.add(MI.getOperand(i));
8904     MI.eraseFromParent();
8905     return BB;
8906   }
8907 
8908   case ARM::tMOVCCr_pseudo: {
8909     // To "insert" a SELECT_CC instruction, we actually have to insert the
8910     // diamond control-flow pattern.  The incoming instruction knows the
8911     // destination vreg to set, the condition code register to branch on, the
8912     // true/false values to select between, and a branch opcode to use.
8913     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8914     MachineFunction::iterator It = ++BB->getIterator();
8915 
8916     //  thisMBB:
8917     //  ...
8918     //   TrueVal = ...
8919     //   cmpTY ccX, r1, r2
8920     //   bCC copy1MBB
8921     //   fallthrough --> copy0MBB
8922     MachineBasicBlock *thisMBB  = BB;
8923     MachineFunction *F = BB->getParent();
8924     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8925     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8926     F->insert(It, copy0MBB);
8927     F->insert(It, sinkMBB);
8928 
8929     // Transfer the remainder of BB and its successor edges to sinkMBB.
8930     sinkMBB->splice(sinkMBB->begin(), BB,
8931                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8932     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8933 
8934     BB->addSuccessor(copy0MBB);
8935     BB->addSuccessor(sinkMBB);
8936 
8937     BuildMI(BB, dl, TII->get(ARM::tBcc))
8938         .addMBB(sinkMBB)
8939         .addImm(MI.getOperand(3).getImm())
8940         .addReg(MI.getOperand(4).getReg());
8941 
8942     //  copy0MBB:
8943     //   %FalseValue = ...
8944     //   # fallthrough to sinkMBB
8945     BB = copy0MBB;
8946 
8947     // Update machine-CFG edges
8948     BB->addSuccessor(sinkMBB);
8949 
8950     //  sinkMBB:
8951     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8952     //  ...
8953     BB = sinkMBB;
8954     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8955         .addReg(MI.getOperand(1).getReg())
8956         .addMBB(copy0MBB)
8957         .addReg(MI.getOperand(2).getReg())
8958         .addMBB(thisMBB);
8959 
8960     MI.eraseFromParent(); // The pseudo instruction is gone now.
8961     return BB;
8962   }
8963 
8964   case ARM::BCCi64:
8965   case ARM::BCCZi64: {
8966     // If there is an unconditional branch to the other successor, remove it.
8967     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8968 
8969     // Compare both parts that make up the double comparison separately for
8970     // equality.
8971     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8972 
8973     unsigned LHS1 = MI.getOperand(1).getReg();
8974     unsigned LHS2 = MI.getOperand(2).getReg();
8975     if (RHSisZero) {
8976       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8977           .addReg(LHS1)
8978           .addImm(0)
8979           .add(predOps(ARMCC::AL));
8980       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8981         .addReg(LHS2).addImm(0)
8982         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8983     } else {
8984       unsigned RHS1 = MI.getOperand(3).getReg();
8985       unsigned RHS2 = MI.getOperand(4).getReg();
8986       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8987           .addReg(LHS1)
8988           .addReg(RHS1)
8989           .add(predOps(ARMCC::AL));
8990       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8991         .addReg(LHS2).addReg(RHS2)
8992         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8993     }
8994 
8995     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8996     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8997     if (MI.getOperand(0).getImm() == ARMCC::NE)
8998       std::swap(destMBB, exitMBB);
8999 
9000     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9001       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9002     if (isThumb2)
9003       BuildMI(BB, dl, TII->get(ARM::t2B))
9004           .addMBB(exitMBB)
9005           .add(predOps(ARMCC::AL));
9006     else
9007       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9008 
9009     MI.eraseFromParent(); // The pseudo instruction is gone now.
9010     return BB;
9011   }
9012 
9013   case ARM::Int_eh_sjlj_setjmp:
9014   case ARM::Int_eh_sjlj_setjmp_nofp:
9015   case ARM::tInt_eh_sjlj_setjmp:
9016   case ARM::t2Int_eh_sjlj_setjmp:
9017   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9018     return BB;
9019 
9020   case ARM::Int_eh_sjlj_setup_dispatch:
9021     EmitSjLjDispatchBlock(MI, BB);
9022     return BB;
9023 
9024   case ARM::ABS:
9025   case ARM::t2ABS: {
9026     // To insert an ABS instruction, we have to insert the
9027     // diamond control-flow pattern.  The incoming instruction knows the
9028     // source vreg to test against 0, the destination vreg to set,
9029     // the condition code register to branch on, the
9030     // true/false values to select between, and a branch opcode to use.
9031     // It transforms
9032     //     V1 = ABS V0
9033     // into
9034     //     V2 = MOVS V0
9035     //     BCC                      (branch to SinkBB if V0 >= 0)
9036     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9037     //     SinkBB: V1 = PHI(V2, V3)
9038     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9039     MachineFunction::iterator BBI = ++BB->getIterator();
9040     MachineFunction *Fn = BB->getParent();
9041     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9042     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9043     Fn->insert(BBI, RSBBB);
9044     Fn->insert(BBI, SinkBB);
9045 
9046     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9047     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9048     bool ABSSrcKIll = MI.getOperand(1).isKill();
9049     bool isThumb2 = Subtarget->isThumb2();
9050     MachineRegisterInfo &MRI = Fn->getRegInfo();
9051     // In Thumb mode S must not be specified if source register is the SP or
9052     // PC and if destination register is the SP, so restrict register class
9053     unsigned NewRsbDstReg =
9054       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9055 
9056     // Transfer the remainder of BB and its successor edges to sinkMBB.
9057     SinkBB->splice(SinkBB->begin(), BB,
9058                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9059     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9060 
9061     BB->addSuccessor(RSBBB);
9062     BB->addSuccessor(SinkBB);
9063 
9064     // fall through to SinkMBB
9065     RSBBB->addSuccessor(SinkBB);
9066 
9067     // insert a cmp at the end of BB
9068     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9069         .addReg(ABSSrcReg)
9070         .addImm(0)
9071         .add(predOps(ARMCC::AL));
9072 
9073     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9074     BuildMI(BB, dl,
9075       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9076       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9077 
9078     // insert rsbri in RSBBB
9079     // Note: BCC and rsbri will be converted into predicated rsbmi
9080     // by if-conversion pass
9081     BuildMI(*RSBBB, RSBBB->begin(), dl,
9082             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9083         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9084         .addImm(0)
9085         .add(predOps(ARMCC::AL))
9086         .add(condCodeOp());
9087 
9088     // insert PHI in SinkBB,
9089     // reuse ABSDstReg to not change uses of ABS instruction
9090     BuildMI(*SinkBB, SinkBB->begin(), dl,
9091       TII->get(ARM::PHI), ABSDstReg)
9092       .addReg(NewRsbDstReg).addMBB(RSBBB)
9093       .addReg(ABSSrcReg).addMBB(BB);
9094 
9095     // remove ABS instruction
9096     MI.eraseFromParent();
9097 
9098     // return last added BB
9099     return SinkBB;
9100   }
9101   case ARM::COPY_STRUCT_BYVAL_I32:
9102     ++NumLoopByVals;
9103     return EmitStructByval(MI, BB);
9104   case ARM::WIN__CHKSTK:
9105     return EmitLowered__chkstk(MI, BB);
9106   case ARM::WIN__DBZCHK:
9107     return EmitLowered__dbzchk(MI, BB);
9108   }
9109 }
9110 
9111 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9112 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9113 /// instead of as a custom inserter because we need the use list from the SDNode.
9114 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9115                                     MachineInstr &MI, const SDNode *Node) {
9116   bool isThumb1 = Subtarget->isThumb1Only();
9117 
9118   DebugLoc DL = MI.getDebugLoc();
9119   MachineFunction *MF = MI.getParent()->getParent();
9120   MachineRegisterInfo &MRI = MF->getRegInfo();
9121   MachineInstrBuilder MIB(*MF, MI);
9122 
9123   // If the new dst/src is unused mark it as dead.
9124   if (!Node->hasAnyUseOfValue(0)) {
9125     MI.getOperand(0).setIsDead(true);
9126   }
9127   if (!Node->hasAnyUseOfValue(1)) {
9128     MI.getOperand(1).setIsDead(true);
9129   }
9130 
9131   // The MEMCPY both defines and kills the scratch registers.
9132   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9133     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9134                                                          : &ARM::GPRRegClass);
9135     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9136   }
9137 }
9138 
9139 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9140                                                       SDNode *Node) const {
9141   if (MI.getOpcode() == ARM::MEMCPY) {
9142     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9143     return;
9144   }
9145 
9146   const MCInstrDesc *MCID = &MI.getDesc();
9147   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9148   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9149   // operand is still set to noreg. If needed, set the optional operand's
9150   // register to CPSR, and remove the redundant implicit def.
9151   //
9152   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9153 
9154   // Rename pseudo opcodes.
9155   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9156   unsigned ccOutIdx;
9157   if (NewOpc) {
9158     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9159     MCID = &TII->get(NewOpc);
9160 
9161     assert(MCID->getNumOperands() ==
9162            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9163         && "converted opcode should be the same except for cc_out"
9164            " (and, on Thumb1, pred)");
9165 
9166     MI.setDesc(*MCID);
9167 
9168     // Add the optional cc_out operand
9169     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9170 
9171     // On Thumb1, move all input operands to the end, then add the predicate
9172     if (Subtarget->isThumb1Only()) {
9173       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9174         MI.addOperand(MI.getOperand(1));
9175         MI.RemoveOperand(1);
9176       }
9177 
9178       // Restore the ties
9179       for (unsigned i = MI.getNumOperands(); i--;) {
9180         const MachineOperand& op = MI.getOperand(i);
9181         if (op.isReg() && op.isUse()) {
9182           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9183           if (DefIdx != -1)
9184             MI.tieOperands(DefIdx, i);
9185         }
9186       }
9187 
9188       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9189       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9190       ccOutIdx = 1;
9191     } else
9192       ccOutIdx = MCID->getNumOperands() - 1;
9193   } else
9194     ccOutIdx = MCID->getNumOperands() - 1;
9195 
9196   // Any ARM instruction that sets the 's' bit should specify an optional
9197   // "cc_out" operand in the last operand position.
9198   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9199     assert(!NewOpc && "Optional cc_out operand required");
9200     return;
9201   }
9202   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9203   // since we already have an optional CPSR def.
9204   bool definesCPSR = false;
9205   bool deadCPSR = false;
9206   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9207        ++i) {
9208     const MachineOperand &MO = MI.getOperand(i);
9209     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9210       definesCPSR = true;
9211       if (MO.isDead())
9212         deadCPSR = true;
9213       MI.RemoveOperand(i);
9214       break;
9215     }
9216   }
9217   if (!definesCPSR) {
9218     assert(!NewOpc && "Optional cc_out operand required");
9219     return;
9220   }
9221   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9222   if (deadCPSR) {
9223     assert(!MI.getOperand(ccOutIdx).getReg() &&
9224            "expect uninitialized optional cc_out operand");
9225     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9226     if (!Subtarget->isThumb1Only())
9227       return;
9228   }
9229 
9230   // If this instruction was defined with an optional CPSR def and its dag node
9231   // had a live implicit CPSR def, then activate the optional CPSR def.
9232   MachineOperand &MO = MI.getOperand(ccOutIdx);
9233   MO.setReg(ARM::CPSR);
9234   MO.setIsDef(true);
9235 }
9236 
9237 //===----------------------------------------------------------------------===//
9238 //                           ARM Optimization Hooks
9239 //===----------------------------------------------------------------------===//
9240 
9241 // Helper function that checks if N is a null or all ones constant.
9242 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9243   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9244 }
9245 
9246 // Return true if N is conditionally 0 or all ones.
9247 // Detects these expressions where cc is an i1 value:
9248 //
9249 //   (select cc 0, y)   [AllOnes=0]
9250 //   (select cc y, 0)   [AllOnes=0]
9251 //   (zext cc)          [AllOnes=0]
9252 //   (sext cc)          [AllOnes=0/1]
9253 //   (select cc -1, y)  [AllOnes=1]
9254 //   (select cc y, -1)  [AllOnes=1]
9255 //
9256 // Invert is set when N is the null/all ones constant when CC is false.
9257 // OtherOp is set to the alternative value of N.
9258 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9259                                        SDValue &CC, bool &Invert,
9260                                        SDValue &OtherOp,
9261                                        SelectionDAG &DAG) {
9262   switch (N->getOpcode()) {
9263   default: return false;
9264   case ISD::SELECT: {
9265     CC = N->getOperand(0);
9266     SDValue N1 = N->getOperand(1);
9267     SDValue N2 = N->getOperand(2);
9268     if (isZeroOrAllOnes(N1, AllOnes)) {
9269       Invert = false;
9270       OtherOp = N2;
9271       return true;
9272     }
9273     if (isZeroOrAllOnes(N2, AllOnes)) {
9274       Invert = true;
9275       OtherOp = N1;
9276       return true;
9277     }
9278     return false;
9279   }
9280   case ISD::ZERO_EXTEND:
9281     // (zext cc) can never be the all ones value.
9282     if (AllOnes)
9283       return false;
9284     LLVM_FALLTHROUGH;
9285   case ISD::SIGN_EXTEND: {
9286     SDLoc dl(N);
9287     EVT VT = N->getValueType(0);
9288     CC = N->getOperand(0);
9289     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9290       return false;
9291     Invert = !AllOnes;
9292     if (AllOnes)
9293       // When looking for an AllOnes constant, N is an sext, and the 'other'
9294       // value is 0.
9295       OtherOp = DAG.getConstant(0, dl, VT);
9296     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9297       // When looking for a 0 constant, N can be zext or sext.
9298       OtherOp = DAG.getConstant(1, dl, VT);
9299     else
9300       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9301                                 VT);
9302     return true;
9303   }
9304   }
9305 }
9306 
9307 // Combine a constant select operand into its use:
9308 //
9309 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9310 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9311 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9312 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9313 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9314 //
9315 // The transform is rejected if the select doesn't have a constant operand that
9316 // is null, or all ones when AllOnes is set.
9317 //
9318 // Also recognize sext/zext from i1:
9319 //
9320 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9321 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9322 //
9323 // These transformations eventually create predicated instructions.
9324 //
9325 // @param N       The node to transform.
9326 // @param Slct    The N operand that is a select.
9327 // @param OtherOp The other N operand (x above).
9328 // @param DCI     Context.
9329 // @param AllOnes Require the select constant to be all ones instead of null.
9330 // @returns The new node, or SDValue() on failure.
9331 static
9332 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9333                             TargetLowering::DAGCombinerInfo &DCI,
9334                             bool AllOnes = false) {
9335   SelectionDAG &DAG = DCI.DAG;
9336   EVT VT = N->getValueType(0);
9337   SDValue NonConstantVal;
9338   SDValue CCOp;
9339   bool SwapSelectOps;
9340   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9341                                   NonConstantVal, DAG))
9342     return SDValue();
9343 
9344   // Slct is now know to be the desired identity constant when CC is true.
9345   SDValue TrueVal = OtherOp;
9346   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9347                                  OtherOp, NonConstantVal);
9348   // Unless SwapSelectOps says CC should be false.
9349   if (SwapSelectOps)
9350     std::swap(TrueVal, FalseVal);
9351 
9352   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9353                      CCOp, TrueVal, FalseVal);
9354 }
9355 
9356 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9357 static
9358 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9359                                        TargetLowering::DAGCombinerInfo &DCI) {
9360   SDValue N0 = N->getOperand(0);
9361   SDValue N1 = N->getOperand(1);
9362   if (N0.getNode()->hasOneUse())
9363     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9364       return Result;
9365   if (N1.getNode()->hasOneUse())
9366     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9367       return Result;
9368   return SDValue();
9369 }
9370 
9371 static bool IsVUZPShuffleNode(SDNode *N) {
9372   // VUZP shuffle node.
9373   if (N->getOpcode() == ARMISD::VUZP)
9374     return true;
9375 
9376   // "VUZP" on i32 is an alias for VTRN.
9377   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9378     return true;
9379 
9380   return false;
9381 }
9382 
9383 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9384                                  TargetLowering::DAGCombinerInfo &DCI,
9385                                  const ARMSubtarget *Subtarget) {
9386   // Look for ADD(VUZP.0, VUZP.1).
9387   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9388       N0 == N1)
9389    return SDValue();
9390 
9391   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9392   if (!N->getValueType(0).is64BitVector())
9393     return SDValue();
9394 
9395   // Generate vpadd.
9396   SelectionDAG &DAG = DCI.DAG;
9397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9398   SDLoc dl(N);
9399   SDNode *Unzip = N0.getNode();
9400   EVT VT = N->getValueType(0);
9401 
9402   SmallVector<SDValue, 8> Ops;
9403   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9404                                 TLI.getPointerTy(DAG.getDataLayout())));
9405   Ops.push_back(Unzip->getOperand(0));
9406   Ops.push_back(Unzip->getOperand(1));
9407 
9408   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9409 }
9410 
9411 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9412                                       TargetLowering::DAGCombinerInfo &DCI,
9413                                       const ARMSubtarget *Subtarget) {
9414   // Check for two extended operands.
9415   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9416         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9417       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9418         N1.getOpcode() == ISD::ZERO_EXTEND))
9419     return SDValue();
9420 
9421   SDValue N00 = N0.getOperand(0);
9422   SDValue N10 = N1.getOperand(0);
9423 
9424   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9425   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9426       N00 == N10)
9427     return SDValue();
9428 
9429   // We only recognize Q register paddl here; this can't be reached until
9430   // after type legalization.
9431   if (!N00.getValueType().is64BitVector() ||
9432       !N0.getValueType().is128BitVector())
9433     return SDValue();
9434 
9435   // Generate vpaddl.
9436   SelectionDAG &DAG = DCI.DAG;
9437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9438   SDLoc dl(N);
9439   EVT VT = N->getValueType(0);
9440 
9441   SmallVector<SDValue, 8> Ops;
9442   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9443   unsigned Opcode;
9444   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9445     Opcode = Intrinsic::arm_neon_vpaddls;
9446   else
9447     Opcode = Intrinsic::arm_neon_vpaddlu;
9448   Ops.push_back(DAG.getConstant(Opcode, dl,
9449                                 TLI.getPointerTy(DAG.getDataLayout())));
9450   EVT ElemTy = N00.getValueType().getVectorElementType();
9451   unsigned NumElts = VT.getVectorNumElements();
9452   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9453   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9454                                N00.getOperand(0), N00.getOperand(1));
9455   Ops.push_back(Concat);
9456 
9457   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9458 }
9459 
9460 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9461 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9462 // much easier to match.
9463 static SDValue
9464 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9465                                TargetLowering::DAGCombinerInfo &DCI,
9466                                const ARMSubtarget *Subtarget) {
9467   // Only perform optimization if after legalize, and if NEON is available. We
9468   // also expected both operands to be BUILD_VECTORs.
9469   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9470       || N0.getOpcode() != ISD::BUILD_VECTOR
9471       || N1.getOpcode() != ISD::BUILD_VECTOR)
9472     return SDValue();
9473 
9474   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9475   EVT VT = N->getValueType(0);
9476   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9477     return SDValue();
9478 
9479   // Check that the vector operands are of the right form.
9480   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9481   // operands, where N is the size of the formed vector.
9482   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9483   // index such that we have a pair wise add pattern.
9484 
9485   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9486   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9487     return SDValue();
9488   SDValue Vec = N0->getOperand(0)->getOperand(0);
9489   SDNode *V = Vec.getNode();
9490   unsigned nextIndex = 0;
9491 
9492   // For each operands to the ADD which are BUILD_VECTORs,
9493   // check to see if each of their operands are an EXTRACT_VECTOR with
9494   // the same vector and appropriate index.
9495   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9496     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9497         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9498 
9499       SDValue ExtVec0 = N0->getOperand(i);
9500       SDValue ExtVec1 = N1->getOperand(i);
9501 
9502       // First operand is the vector, verify its the same.
9503       if (V != ExtVec0->getOperand(0).getNode() ||
9504           V != ExtVec1->getOperand(0).getNode())
9505         return SDValue();
9506 
9507       // Second is the constant, verify its correct.
9508       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9509       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9510 
9511       // For the constant, we want to see all the even or all the odd.
9512       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9513           || C1->getZExtValue() != nextIndex+1)
9514         return SDValue();
9515 
9516       // Increment index.
9517       nextIndex+=2;
9518     } else
9519       return SDValue();
9520   }
9521 
9522   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9523   // we're using the entire input vector, otherwise there's a size/legality
9524   // mismatch somewhere.
9525   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9526       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9527     return SDValue();
9528 
9529   // Create VPADDL node.
9530   SelectionDAG &DAG = DCI.DAG;
9531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9532 
9533   SDLoc dl(N);
9534 
9535   // Build operand list.
9536   SmallVector<SDValue, 8> Ops;
9537   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9538                                 TLI.getPointerTy(DAG.getDataLayout())));
9539 
9540   // Input is the vector.
9541   Ops.push_back(Vec);
9542 
9543   // Get widened type and narrowed type.
9544   MVT widenType;
9545   unsigned numElem = VT.getVectorNumElements();
9546 
9547   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9548   switch (inputLaneType.getSimpleVT().SimpleTy) {
9549     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9550     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9551     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9552     default:
9553       llvm_unreachable("Invalid vector element type for padd optimization.");
9554   }
9555 
9556   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9557   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9558   return DAG.getNode(ExtOp, dl, VT, tmp);
9559 }
9560 
9561 static SDValue findMUL_LOHI(SDValue V) {
9562   if (V->getOpcode() == ISD::UMUL_LOHI ||
9563       V->getOpcode() == ISD::SMUL_LOHI)
9564     return V;
9565   return SDValue();
9566 }
9567 
9568 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9569                                         TargetLowering::DAGCombinerInfo &DCI,
9570                                         const ARMSubtarget *Subtarget) {
9571 
9572   if (Subtarget->isThumb()) {
9573     if (!Subtarget->hasDSP())
9574       return SDValue();
9575   } else if (!Subtarget->hasV5TEOps())
9576     return SDValue();
9577 
9578   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9579   // accumulates the product into a 64-bit value. The 16-bit values will
9580   // be sign extended somehow or SRA'd into 32-bit values
9581   // (addc (adde (mul 16bit, 16bit), lo), hi)
9582   SDValue Mul = AddcNode->getOperand(0);
9583   SDValue Lo = AddcNode->getOperand(1);
9584   if (Mul.getOpcode() != ISD::MUL) {
9585     Lo = AddcNode->getOperand(0);
9586     Mul = AddcNode->getOperand(1);
9587     if (Mul.getOpcode() != ISD::MUL)
9588       return SDValue();
9589   }
9590 
9591   SDValue SRA = AddeNode->getOperand(0);
9592   SDValue Hi = AddeNode->getOperand(1);
9593   if (SRA.getOpcode() != ISD::SRA) {
9594     SRA = AddeNode->getOperand(1);
9595     Hi = AddeNode->getOperand(0);
9596     if (SRA.getOpcode() != ISD::SRA)
9597       return SDValue();
9598   }
9599   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9600     if (Const->getZExtValue() != 31)
9601       return SDValue();
9602   } else
9603     return SDValue();
9604 
9605   if (SRA.getOperand(0) != Mul)
9606     return SDValue();
9607 
9608   SelectionDAG &DAG = DCI.DAG;
9609   SDLoc dl(AddcNode);
9610   unsigned Opcode = 0;
9611   SDValue Op0;
9612   SDValue Op1;
9613 
9614   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9615     Opcode = ARMISD::SMLALBB;
9616     Op0 = Mul.getOperand(0);
9617     Op1 = Mul.getOperand(1);
9618   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9619     Opcode = ARMISD::SMLALBT;
9620     Op0 = Mul.getOperand(0);
9621     Op1 = Mul.getOperand(1).getOperand(0);
9622   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9623     Opcode = ARMISD::SMLALTB;
9624     Op0 = Mul.getOperand(0).getOperand(0);
9625     Op1 = Mul.getOperand(1);
9626   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9627     Opcode = ARMISD::SMLALTT;
9628     Op0 = Mul->getOperand(0).getOperand(0);
9629     Op1 = Mul->getOperand(1).getOperand(0);
9630   }
9631 
9632   if (!Op0 || !Op1)
9633     return SDValue();
9634 
9635   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9636                               Op0, Op1, Lo, Hi);
9637   // Replace the ADDs' nodes uses by the MLA node's values.
9638   SDValue HiMLALResult(SMLAL.getNode(), 1);
9639   SDValue LoMLALResult(SMLAL.getNode(), 0);
9640 
9641   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9642   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9643 
9644   // Return original node to notify the driver to stop replacing.
9645   SDValue resNode(AddcNode, 0);
9646   return resNode;
9647 }
9648 
9649 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9650                                      TargetLowering::DAGCombinerInfo &DCI,
9651                                      const ARMSubtarget *Subtarget) {
9652   // Look for multiply add opportunities.
9653   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9654   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9655   // a glue link from the first add to the second add.
9656   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9657   // a S/UMLAL instruction.
9658   //                  UMUL_LOHI
9659   //                 / :lo    \ :hi
9660   //                /          \          [no multiline comment]
9661   //    loAdd ->  ADDE         |
9662   //                 \ :glue  /
9663   //                  \      /
9664   //                    ADDC   <- hiAdd
9665   //
9666   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9667 
9668   assert(AddeNode->getNumOperands() == 3 &&
9669          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9670          "ADDE node has the wrong inputs");
9671 
9672   // Check that we have a glued ADDC node.
9673   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9674   if (AddcNode->getOpcode() != ARMISD::ADDC)
9675     return SDValue();
9676 
9677   SDValue AddcOp0 = AddcNode->getOperand(0);
9678   SDValue AddcOp1 = AddcNode->getOperand(1);
9679 
9680   // Check if the two operands are from the same mul_lohi node.
9681   if (AddcOp0.getNode() == AddcOp1.getNode())
9682     return SDValue();
9683 
9684   assert(AddcNode->getNumValues() == 2 &&
9685          AddcNode->getValueType(0) == MVT::i32 &&
9686          "Expect ADDC with two result values. First: i32");
9687 
9688   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9689   // maybe a SMLAL which multiplies two 16-bit values.
9690   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9691       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9692       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9693       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9694     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9695 
9696   // Check for the triangle shape.
9697   SDValue AddeOp0 = AddeNode->getOperand(0);
9698   SDValue AddeOp1 = AddeNode->getOperand(1);
9699 
9700   // Make sure that the ADDE operands are not coming from the same node.
9701   if (AddeOp0.getNode() == AddeOp1.getNode())
9702     return SDValue();
9703 
9704   // Find the MUL_LOHI node walking up ADDE's operands.
9705   bool IsLeftOperandMUL = false;
9706   SDValue MULOp = findMUL_LOHI(AddeOp0);
9707   if (MULOp == SDValue())
9708    MULOp = findMUL_LOHI(AddeOp1);
9709   else
9710     IsLeftOperandMUL = true;
9711   if (MULOp == SDValue())
9712     return SDValue();
9713 
9714   // Figure out the right opcode.
9715   unsigned Opc = MULOp->getOpcode();
9716   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9717 
9718   // Figure out the high and low input values to the MLAL node.
9719   SDValue* HiAdd = nullptr;
9720   SDValue* LoMul = nullptr;
9721   SDValue* LowAdd = nullptr;
9722 
9723   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9724   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9725     return SDValue();
9726 
9727   if (IsLeftOperandMUL)
9728     HiAdd = &AddeOp1;
9729   else
9730     HiAdd = &AddeOp0;
9731 
9732 
9733   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9734   // whose low result is fed to the ADDC we are checking.
9735 
9736   if (AddcOp0 == MULOp.getValue(0)) {
9737     LoMul = &AddcOp0;
9738     LowAdd = &AddcOp1;
9739   }
9740   if (AddcOp1 == MULOp.getValue(0)) {
9741     LoMul = &AddcOp1;
9742     LowAdd = &AddcOp0;
9743   }
9744 
9745   if (!LoMul)
9746     return SDValue();
9747 
9748   // Create the merged node.
9749   SelectionDAG &DAG = DCI.DAG;
9750 
9751   // Build operand list.
9752   SmallVector<SDValue, 8> Ops;
9753   Ops.push_back(LoMul->getOperand(0));
9754   Ops.push_back(LoMul->getOperand(1));
9755   Ops.push_back(*LowAdd);
9756   Ops.push_back(*HiAdd);
9757 
9758   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9759                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9760 
9761   // Replace the ADDs' nodes uses by the MLA node's values.
9762   SDValue HiMLALResult(MLALNode.getNode(), 1);
9763   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9764 
9765   SDValue LoMLALResult(MLALNode.getNode(), 0);
9766   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9767 
9768   // Return original node to notify the driver to stop replacing.
9769   return SDValue(AddeNode, 0);
9770 }
9771 
9772 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9773                                       TargetLowering::DAGCombinerInfo &DCI,
9774                                       const ARMSubtarget *Subtarget) {
9775   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9776   // While trying to combine for the other MLAL nodes, first search for the
9777   // chance to use UMAAL. Check if Addc uses a node which has already
9778   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9779   // as the addend, and it's handled in PerformUMLALCombine.
9780 
9781   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9782     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9783 
9784   // Check that we have a glued ADDC node.
9785   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9786   if (AddcNode->getOpcode() != ARMISD::ADDC)
9787     return SDValue();
9788 
9789   // Find the converted UMAAL or quit if it doesn't exist.
9790   SDNode *UmlalNode = nullptr;
9791   SDValue AddHi;
9792   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9793     UmlalNode = AddcNode->getOperand(0).getNode();
9794     AddHi = AddcNode->getOperand(1);
9795   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9796     UmlalNode = AddcNode->getOperand(1).getNode();
9797     AddHi = AddcNode->getOperand(0);
9798   } else {
9799     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9800   }
9801 
9802   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9803   // the ADDC as well as Zero.
9804   if (!isNullConstant(UmlalNode->getOperand(3)))
9805     return SDValue();
9806 
9807   if ((isNullConstant(AddeNode->getOperand(0)) &&
9808        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9809       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9810        isNullConstant(AddeNode->getOperand(1)))) {
9811 
9812     SelectionDAG &DAG = DCI.DAG;
9813     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9814                       UmlalNode->getOperand(2), AddHi };
9815     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9816                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9817 
9818     // Replace the ADDs' nodes uses by the UMAAL node's values.
9819     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9820     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9821 
9822     // Return original node to notify the driver to stop replacing.
9823     return SDValue(AddeNode, 0);
9824   }
9825   return SDValue();
9826 }
9827 
9828 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9829                                    const ARMSubtarget *Subtarget) {
9830   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9831     return SDValue();
9832 
9833   // Check that we have a pair of ADDC and ADDE as operands.
9834   // Both addends of the ADDE must be zero.
9835   SDNode* AddcNode = N->getOperand(2).getNode();
9836   SDNode* AddeNode = N->getOperand(3).getNode();
9837   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9838       (AddeNode->getOpcode() == ARMISD::ADDE) &&
9839       isNullConstant(AddeNode->getOperand(0)) &&
9840       isNullConstant(AddeNode->getOperand(1)) &&
9841       (AddeNode->getOperand(2).getNode() == AddcNode))
9842     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9843                        DAG.getVTList(MVT::i32, MVT::i32),
9844                        {N->getOperand(0), N->getOperand(1),
9845                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
9846   else
9847     return SDValue();
9848 }
9849 
9850 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG,
9851                                       const ARMSubtarget *Subtarget) {
9852   if (Subtarget->isThumb1Only()) {
9853     SDValue RHS = N->getOperand(1);
9854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9855       int32_t imm = C->getSExtValue();
9856       if (imm < 0 && imm > INT_MIN) {
9857         SDLoc DL(N);
9858         RHS = DAG.getConstant(-imm, DL, MVT::i32);
9859         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
9860                                                            : ARMISD::ADDC;
9861         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
9862       }
9863     }
9864   }
9865   return SDValue();
9866 }
9867 
9868 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
9869                                       const ARMSubtarget *Subtarget) {
9870   if (Subtarget->isThumb1Only()) {
9871     SDValue RHS = N->getOperand(1);
9872     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9873       int64_t imm = C->getSExtValue();
9874       if (imm < 0) {
9875         SDLoc DL(N);
9876 
9877         // The with-carry-in form matches bitwise not instead of the negation.
9878         // Effectively, the inverse interpretation of the carry flag already
9879         // accounts for part of the negation.
9880         RHS = DAG.getConstant(~imm, DL, MVT::i32);
9881 
9882         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
9883                                                            : ARMISD::ADDE;
9884         return DAG.getNode(Opcode, DL, N->getVTList(),
9885                            N->getOperand(0), RHS, N->getOperand(2));
9886       }
9887     }
9888   }
9889   return SDValue();
9890 }
9891 
9892 /// PerformADDECombine - Target-specific dag combine transform from
9893 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
9894 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9895 static SDValue PerformADDECombine(SDNode *N,
9896                                   TargetLowering::DAGCombinerInfo &DCI,
9897                                   const ARMSubtarget *Subtarget) {
9898   // Only ARM and Thumb2 support UMLAL/SMLAL.
9899   if (Subtarget->isThumb1Only())
9900     return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
9901 
9902   // Only perform the checks after legalize when the pattern is available.
9903   if (DCI.isBeforeLegalize()) return SDValue();
9904 
9905   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9906 }
9907 
9908 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9909 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9910 /// called with the default operands, and if that fails, with commuted
9911 /// operands.
9912 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9913                                           TargetLowering::DAGCombinerInfo &DCI,
9914                                           const ARMSubtarget *Subtarget){
9915   // Attempt to create vpadd for this add.
9916   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
9917     return Result;
9918 
9919   // Attempt to create vpaddl for this add.
9920   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
9921     return Result;
9922   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
9923                                                       Subtarget))
9924     return Result;
9925 
9926   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9927   if (N0.getNode()->hasOneUse())
9928     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9929       return Result;
9930   return SDValue();
9931 }
9932 
9933 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9934 ///
9935 static SDValue PerformADDCombine(SDNode *N,
9936                                  TargetLowering::DAGCombinerInfo &DCI,
9937                                  const ARMSubtarget *Subtarget) {
9938   SDValue N0 = N->getOperand(0);
9939   SDValue N1 = N->getOperand(1);
9940 
9941   // First try with the default operand order.
9942   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9943     return Result;
9944 
9945   // If that didn't work, try again with the operands commuted.
9946   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9947 }
9948 
9949 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9950 ///
9951 static SDValue PerformSUBCombine(SDNode *N,
9952                                  TargetLowering::DAGCombinerInfo &DCI) {
9953   SDValue N0 = N->getOperand(0);
9954   SDValue N1 = N->getOperand(1);
9955 
9956   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9957   if (N1.getNode()->hasOneUse())
9958     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9959       return Result;
9960 
9961   return SDValue();
9962 }
9963 
9964 /// PerformVMULCombine
9965 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9966 /// special multiplier accumulator forwarding.
9967 ///   vmul d3, d0, d2
9968 ///   vmla d3, d1, d2
9969 /// is faster than
9970 ///   vadd d3, d0, d1
9971 ///   vmul d3, d3, d2
9972 //  However, for (A + B) * (A + B),
9973 //    vadd d2, d0, d1
9974 //    vmul d3, d0, d2
9975 //    vmla d3, d1, d2
9976 //  is slower than
9977 //    vadd d2, d0, d1
9978 //    vmul d3, d2, d2
9979 static SDValue PerformVMULCombine(SDNode *N,
9980                                   TargetLowering::DAGCombinerInfo &DCI,
9981                                   const ARMSubtarget *Subtarget) {
9982   if (!Subtarget->hasVMLxForwarding())
9983     return SDValue();
9984 
9985   SelectionDAG &DAG = DCI.DAG;
9986   SDValue N0 = N->getOperand(0);
9987   SDValue N1 = N->getOperand(1);
9988   unsigned Opcode = N0.getOpcode();
9989   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9990       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9991     Opcode = N1.getOpcode();
9992     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9993         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9994       return SDValue();
9995     std::swap(N0, N1);
9996   }
9997 
9998   if (N0 == N1)
9999     return SDValue();
10000 
10001   EVT VT = N->getValueType(0);
10002   SDLoc DL(N);
10003   SDValue N00 = N0->getOperand(0);
10004   SDValue N01 = N0->getOperand(1);
10005   return DAG.getNode(Opcode, DL, VT,
10006                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10007                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10008 }
10009 
10010 static SDValue PerformMULCombine(SDNode *N,
10011                                  TargetLowering::DAGCombinerInfo &DCI,
10012                                  const ARMSubtarget *Subtarget) {
10013   SelectionDAG &DAG = DCI.DAG;
10014 
10015   if (Subtarget->isThumb1Only())
10016     return SDValue();
10017 
10018   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10019     return SDValue();
10020 
10021   EVT VT = N->getValueType(0);
10022   if (VT.is64BitVector() || VT.is128BitVector())
10023     return PerformVMULCombine(N, DCI, Subtarget);
10024   if (VT != MVT::i32)
10025     return SDValue();
10026 
10027   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10028   if (!C)
10029     return SDValue();
10030 
10031   int64_t MulAmt = C->getSExtValue();
10032   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10033 
10034   ShiftAmt = ShiftAmt & (32 - 1);
10035   SDValue V = N->getOperand(0);
10036   SDLoc DL(N);
10037 
10038   SDValue Res;
10039   MulAmt >>= ShiftAmt;
10040 
10041   if (MulAmt >= 0) {
10042     if (isPowerOf2_32(MulAmt - 1)) {
10043       // (mul x, 2^N + 1) => (add (shl x, N), x)
10044       Res = DAG.getNode(ISD::ADD, DL, VT,
10045                         V,
10046                         DAG.getNode(ISD::SHL, DL, VT,
10047                                     V,
10048                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10049                                                     MVT::i32)));
10050     } else if (isPowerOf2_32(MulAmt + 1)) {
10051       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10052       Res = DAG.getNode(ISD::SUB, DL, VT,
10053                         DAG.getNode(ISD::SHL, DL, VT,
10054                                     V,
10055                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10056                                                     MVT::i32)),
10057                         V);
10058     } else
10059       return SDValue();
10060   } else {
10061     uint64_t MulAmtAbs = -MulAmt;
10062     if (isPowerOf2_32(MulAmtAbs + 1)) {
10063       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10064       Res = DAG.getNode(ISD::SUB, DL, VT,
10065                         V,
10066                         DAG.getNode(ISD::SHL, DL, VT,
10067                                     V,
10068                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10069                                                     MVT::i32)));
10070     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10071       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10072       Res = DAG.getNode(ISD::ADD, DL, VT,
10073                         V,
10074                         DAG.getNode(ISD::SHL, DL, VT,
10075                                     V,
10076                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10077                                                     MVT::i32)));
10078       Res = DAG.getNode(ISD::SUB, DL, VT,
10079                         DAG.getConstant(0, DL, MVT::i32), Res);
10080 
10081     } else
10082       return SDValue();
10083   }
10084 
10085   if (ShiftAmt != 0)
10086     Res = DAG.getNode(ISD::SHL, DL, VT,
10087                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10088 
10089   // Do not add new nodes to DAG combiner worklist.
10090   DCI.CombineTo(N, Res, false);
10091   return SDValue();
10092 }
10093 
10094 static SDValue PerformANDCombine(SDNode *N,
10095                                  TargetLowering::DAGCombinerInfo &DCI,
10096                                  const ARMSubtarget *Subtarget) {
10097   // Attempt to use immediate-form VBIC
10098   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10099   SDLoc dl(N);
10100   EVT VT = N->getValueType(0);
10101   SelectionDAG &DAG = DCI.DAG;
10102 
10103   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10104     return SDValue();
10105 
10106   APInt SplatBits, SplatUndef;
10107   unsigned SplatBitSize;
10108   bool HasAnyUndefs;
10109   if (BVN &&
10110       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10111     if (SplatBitSize <= 64) {
10112       EVT VbicVT;
10113       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10114                                       SplatUndef.getZExtValue(), SplatBitSize,
10115                                       DAG, dl, VbicVT, VT.is128BitVector(),
10116                                       OtherModImm);
10117       if (Val.getNode()) {
10118         SDValue Input =
10119           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10120         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10121         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10122       }
10123     }
10124   }
10125 
10126   if (!Subtarget->isThumb1Only()) {
10127     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10128     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10129       return Result;
10130   }
10131 
10132   return SDValue();
10133 }
10134 
10135 // Try combining OR nodes to SMULWB, SMULWT.
10136 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10137                                          TargetLowering::DAGCombinerInfo &DCI,
10138                                          const ARMSubtarget *Subtarget) {
10139   if (!Subtarget->hasV6Ops() ||
10140       (Subtarget->isThumb() &&
10141        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10142     return SDValue();
10143 
10144   SDValue SRL = OR->getOperand(0);
10145   SDValue SHL = OR->getOperand(1);
10146 
10147   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10148     SRL = OR->getOperand(1);
10149     SHL = OR->getOperand(0);
10150   }
10151   if (!isSRL16(SRL) || !isSHL16(SHL))
10152     return SDValue();
10153 
10154   // The first operands to the shifts need to be the two results from the
10155   // same smul_lohi node.
10156   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10157        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10158     return SDValue();
10159 
10160   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10161   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10162       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10163     return SDValue();
10164 
10165   // Now we have:
10166   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10167   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10168   // For SMUWB the 16-bit value will signed extended somehow.
10169   // For SMULWT only the SRA is required.
10170   // Check both sides of SMUL_LOHI
10171   SDValue OpS16 = SMULLOHI->getOperand(0);
10172   SDValue OpS32 = SMULLOHI->getOperand(1);
10173 
10174   SelectionDAG &DAG = DCI.DAG;
10175   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10176     OpS16 = OpS32;
10177     OpS32 = SMULLOHI->getOperand(0);
10178   }
10179 
10180   SDLoc dl(OR);
10181   unsigned Opcode = 0;
10182   if (isS16(OpS16, DAG))
10183     Opcode = ARMISD::SMULWB;
10184   else if (isSRA16(OpS16)) {
10185     Opcode = ARMISD::SMULWT;
10186     OpS16 = OpS16->getOperand(0);
10187   }
10188   else
10189     return SDValue();
10190 
10191   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10192   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10193   return SDValue(OR, 0);
10194 }
10195 
10196 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10197 static SDValue PerformORCombine(SDNode *N,
10198                                 TargetLowering::DAGCombinerInfo &DCI,
10199                                 const ARMSubtarget *Subtarget) {
10200   // Attempt to use immediate-form VORR
10201   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10202   SDLoc dl(N);
10203   EVT VT = N->getValueType(0);
10204   SelectionDAG &DAG = DCI.DAG;
10205 
10206   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10207     return SDValue();
10208 
10209   APInt SplatBits, SplatUndef;
10210   unsigned SplatBitSize;
10211   bool HasAnyUndefs;
10212   if (BVN && Subtarget->hasNEON() &&
10213       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10214     if (SplatBitSize <= 64) {
10215       EVT VorrVT;
10216       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10217                                       SplatUndef.getZExtValue(), SplatBitSize,
10218                                       DAG, dl, VorrVT, VT.is128BitVector(),
10219                                       OtherModImm);
10220       if (Val.getNode()) {
10221         SDValue Input =
10222           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10223         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10224         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10225       }
10226     }
10227   }
10228 
10229   if (!Subtarget->isThumb1Only()) {
10230     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10231     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10232       return Result;
10233     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10234       return Result;
10235   }
10236 
10237   // The code below optimizes (or (and X, Y), Z).
10238   // The AND operand needs to have a single user to make these optimizations
10239   // profitable.
10240   SDValue N0 = N->getOperand(0);
10241   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10242     return SDValue();
10243   SDValue N1 = N->getOperand(1);
10244 
10245   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10246   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10247       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10248     APInt SplatUndef;
10249     unsigned SplatBitSize;
10250     bool HasAnyUndefs;
10251 
10252     APInt SplatBits0, SplatBits1;
10253     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10254     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10255     // Ensure that the second operand of both ands are constants
10256     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10257                                       HasAnyUndefs) && !HasAnyUndefs) {
10258         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10259                                           HasAnyUndefs) && !HasAnyUndefs) {
10260             // Ensure that the bit width of the constants are the same and that
10261             // the splat arguments are logical inverses as per the pattern we
10262             // are trying to simplify.
10263             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10264                 SplatBits0 == ~SplatBits1) {
10265                 // Canonicalize the vector type to make instruction selection
10266                 // simpler.
10267                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10268                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10269                                              N0->getOperand(1),
10270                                              N0->getOperand(0),
10271                                              N1->getOperand(0));
10272                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10273             }
10274         }
10275     }
10276   }
10277 
10278   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10279   // reasonable.
10280 
10281   // BFI is only available on V6T2+
10282   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10283     return SDValue();
10284 
10285   SDLoc DL(N);
10286   // 1) or (and A, mask), val => ARMbfi A, val, mask
10287   //      iff (val & mask) == val
10288   //
10289   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10290   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10291   //          && mask == ~mask2
10292   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10293   //          && ~mask == mask2
10294   //  (i.e., copy a bitfield value into another bitfield of the same width)
10295 
10296   if (VT != MVT::i32)
10297     return SDValue();
10298 
10299   SDValue N00 = N0.getOperand(0);
10300 
10301   // The value and the mask need to be constants so we can verify this is
10302   // actually a bitfield set. If the mask is 0xffff, we can do better
10303   // via a movt instruction, so don't use BFI in that case.
10304   SDValue MaskOp = N0.getOperand(1);
10305   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10306   if (!MaskC)
10307     return SDValue();
10308   unsigned Mask = MaskC->getZExtValue();
10309   if (Mask == 0xffff)
10310     return SDValue();
10311   SDValue Res;
10312   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10313   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10314   if (N1C) {
10315     unsigned Val = N1C->getZExtValue();
10316     if ((Val & ~Mask) != Val)
10317       return SDValue();
10318 
10319     if (ARM::isBitFieldInvertedMask(Mask)) {
10320       Val >>= countTrailingZeros(~Mask);
10321 
10322       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10323                         DAG.getConstant(Val, DL, MVT::i32),
10324                         DAG.getConstant(Mask, DL, MVT::i32));
10325 
10326       // Do not add new nodes to DAG combiner worklist.
10327       DCI.CombineTo(N, Res, false);
10328       return SDValue();
10329     }
10330   } else if (N1.getOpcode() == ISD::AND) {
10331     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10332     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10333     if (!N11C)
10334       return SDValue();
10335     unsigned Mask2 = N11C->getZExtValue();
10336 
10337     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10338     // as is to match.
10339     if (ARM::isBitFieldInvertedMask(Mask) &&
10340         (Mask == ~Mask2)) {
10341       // The pack halfword instruction works better for masks that fit it,
10342       // so use that when it's available.
10343       if (Subtarget->hasDSP() &&
10344           (Mask == 0xffff || Mask == 0xffff0000))
10345         return SDValue();
10346       // 2a
10347       unsigned amt = countTrailingZeros(Mask2);
10348       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10349                         DAG.getConstant(amt, DL, MVT::i32));
10350       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10351                         DAG.getConstant(Mask, DL, MVT::i32));
10352       // Do not add new nodes to DAG combiner worklist.
10353       DCI.CombineTo(N, Res, false);
10354       return SDValue();
10355     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10356                (~Mask == Mask2)) {
10357       // The pack halfword instruction works better for masks that fit it,
10358       // so use that when it's available.
10359       if (Subtarget->hasDSP() &&
10360           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10361         return SDValue();
10362       // 2b
10363       unsigned lsb = countTrailingZeros(Mask);
10364       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10365                         DAG.getConstant(lsb, DL, MVT::i32));
10366       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10367                         DAG.getConstant(Mask2, DL, MVT::i32));
10368       // Do not add new nodes to DAG combiner worklist.
10369       DCI.CombineTo(N, Res, false);
10370       return SDValue();
10371     }
10372   }
10373 
10374   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10375       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10376       ARM::isBitFieldInvertedMask(~Mask)) {
10377     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10378     // where lsb(mask) == #shamt and masked bits of B are known zero.
10379     SDValue ShAmt = N00.getOperand(1);
10380     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10381     unsigned LSB = countTrailingZeros(Mask);
10382     if (ShAmtC != LSB)
10383       return SDValue();
10384 
10385     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10386                       DAG.getConstant(~Mask, DL, MVT::i32));
10387 
10388     // Do not add new nodes to DAG combiner worklist.
10389     DCI.CombineTo(N, Res, false);
10390   }
10391 
10392   return SDValue();
10393 }
10394 
10395 static SDValue PerformXORCombine(SDNode *N,
10396                                  TargetLowering::DAGCombinerInfo &DCI,
10397                                  const ARMSubtarget *Subtarget) {
10398   EVT VT = N->getValueType(0);
10399   SelectionDAG &DAG = DCI.DAG;
10400 
10401   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10402     return SDValue();
10403 
10404   if (!Subtarget->isThumb1Only()) {
10405     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10406     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10407       return Result;
10408   }
10409 
10410   return SDValue();
10411 }
10412 
10413 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10414 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10415 // their position in "to" (Rd).
10416 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10417   assert(N->getOpcode() == ARMISD::BFI);
10418 
10419   SDValue From = N->getOperand(1);
10420   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10421   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10422 
10423   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10424   // #C in the base of the SHR.
10425   if (From->getOpcode() == ISD::SRL &&
10426       isa<ConstantSDNode>(From->getOperand(1))) {
10427     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10428     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10429     FromMask <<= Shift.getLimitedValue(31);
10430     From = From->getOperand(0);
10431   }
10432 
10433   return From;
10434 }
10435 
10436 // If A and B contain one contiguous set of bits, does A | B == A . B?
10437 //
10438 // Neither A nor B must be zero.
10439 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10440   unsigned LastActiveBitInA =  A.countTrailingZeros();
10441   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10442   return LastActiveBitInA - 1 == FirstActiveBitInB;
10443 }
10444 
10445 static SDValue FindBFIToCombineWith(SDNode *N) {
10446   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10447   // if one exists.
10448   APInt ToMask, FromMask;
10449   SDValue From = ParseBFI(N, ToMask, FromMask);
10450   SDValue To = N->getOperand(0);
10451 
10452   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10453   // aren't compatible, but not if they set the same bit in their destination as
10454   // we do (or that of any BFI we're going to combine with).
10455   SDValue V = To;
10456   APInt CombinedToMask = ToMask;
10457   while (V.getOpcode() == ARMISD::BFI) {
10458     APInt NewToMask, NewFromMask;
10459     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10460     if (NewFrom != From) {
10461       // This BFI has a different base. Keep going.
10462       CombinedToMask |= NewToMask;
10463       V = V.getOperand(0);
10464       continue;
10465     }
10466 
10467     // Do the written bits conflict with any we've seen so far?
10468     if ((NewToMask & CombinedToMask).getBoolValue())
10469       // Conflicting bits - bail out because going further is unsafe.
10470       return SDValue();
10471 
10472     // Are the new bits contiguous when combined with the old bits?
10473     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10474         BitsProperlyConcatenate(FromMask, NewFromMask))
10475       return V;
10476     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10477         BitsProperlyConcatenate(NewFromMask, FromMask))
10478       return V;
10479 
10480     // We've seen a write to some bits, so track it.
10481     CombinedToMask |= NewToMask;
10482     // Keep going...
10483     V = V.getOperand(0);
10484   }
10485 
10486   return SDValue();
10487 }
10488 
10489 static SDValue PerformBFICombine(SDNode *N,
10490                                  TargetLowering::DAGCombinerInfo &DCI) {
10491   SDValue N1 = N->getOperand(1);
10492   if (N1.getOpcode() == ISD::AND) {
10493     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10494     // the bits being cleared by the AND are not demanded by the BFI.
10495     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10496     if (!N11C)
10497       return SDValue();
10498     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10499     unsigned LSB = countTrailingZeros(~InvMask);
10500     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10501     assert(Width <
10502                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10503            "undefined behavior");
10504     unsigned Mask = (1u << Width) - 1;
10505     unsigned Mask2 = N11C->getZExtValue();
10506     if ((Mask & (~Mask2)) == 0)
10507       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10508                              N->getOperand(0), N1.getOperand(0),
10509                              N->getOperand(2));
10510   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10511     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10512     // Keep track of any consecutive bits set that all come from the same base
10513     // value. We can combine these together into a single BFI.
10514     SDValue CombineBFI = FindBFIToCombineWith(N);
10515     if (CombineBFI == SDValue())
10516       return SDValue();
10517 
10518     // We've found a BFI.
10519     APInt ToMask1, FromMask1;
10520     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10521 
10522     APInt ToMask2, FromMask2;
10523     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10524     assert(From1 == From2);
10525     (void)From2;
10526 
10527     // First, unlink CombineBFI.
10528     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10529     // Then create a new BFI, combining the two together.
10530     APInt NewFromMask = FromMask1 | FromMask2;
10531     APInt NewToMask = ToMask1 | ToMask2;
10532 
10533     EVT VT = N->getValueType(0);
10534     SDLoc dl(N);
10535 
10536     if (NewFromMask[0] == 0)
10537       From1 = DCI.DAG.getNode(
10538         ISD::SRL, dl, VT, From1,
10539         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10540     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10541                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10542   }
10543   return SDValue();
10544 }
10545 
10546 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10547 /// ARMISD::VMOVRRD.
10548 static SDValue PerformVMOVRRDCombine(SDNode *N,
10549                                      TargetLowering::DAGCombinerInfo &DCI,
10550                                      const ARMSubtarget *Subtarget) {
10551   // vmovrrd(vmovdrr x, y) -> x,y
10552   SDValue InDouble = N->getOperand(0);
10553   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10554     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10555 
10556   // vmovrrd(load f64) -> (load i32), (load i32)
10557   SDNode *InNode = InDouble.getNode();
10558   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10559       InNode->getValueType(0) == MVT::f64 &&
10560       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10561       !cast<LoadSDNode>(InNode)->isVolatile()) {
10562     // TODO: Should this be done for non-FrameIndex operands?
10563     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10564 
10565     SelectionDAG &DAG = DCI.DAG;
10566     SDLoc DL(LD);
10567     SDValue BasePtr = LD->getBasePtr();
10568     SDValue NewLD1 =
10569         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10570                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10571 
10572     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10573                                     DAG.getConstant(4, DL, MVT::i32));
10574     SDValue NewLD2 = DAG.getLoad(
10575         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10576         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10577 
10578     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10579     if (DCI.DAG.getDataLayout().isBigEndian())
10580       std::swap (NewLD1, NewLD2);
10581     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10582     return Result;
10583   }
10584 
10585   return SDValue();
10586 }
10587 
10588 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10589 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10590 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10591   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10592   SDValue Op0 = N->getOperand(0);
10593   SDValue Op1 = N->getOperand(1);
10594   if (Op0.getOpcode() == ISD::BITCAST)
10595     Op0 = Op0.getOperand(0);
10596   if (Op1.getOpcode() == ISD::BITCAST)
10597     Op1 = Op1.getOperand(0);
10598   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10599       Op0.getNode() == Op1.getNode() &&
10600       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10601     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10602                        N->getValueType(0), Op0.getOperand(0));
10603   return SDValue();
10604 }
10605 
10606 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10607 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10608 /// i64 vector to have f64 elements, since the value can then be loaded
10609 /// directly into a VFP register.
10610 static bool hasNormalLoadOperand(SDNode *N) {
10611   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10612   for (unsigned i = 0; i < NumElts; ++i) {
10613     SDNode *Elt = N->getOperand(i).getNode();
10614     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10615       return true;
10616   }
10617   return false;
10618 }
10619 
10620 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10621 /// ISD::BUILD_VECTOR.
10622 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10623                                           TargetLowering::DAGCombinerInfo &DCI,
10624                                           const ARMSubtarget *Subtarget) {
10625   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10626   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10627   // into a pair of GPRs, which is fine when the value is used as a scalar,
10628   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10629   SelectionDAG &DAG = DCI.DAG;
10630   if (N->getNumOperands() == 2)
10631     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10632       return RV;
10633 
10634   // Load i64 elements as f64 values so that type legalization does not split
10635   // them up into i32 values.
10636   EVT VT = N->getValueType(0);
10637   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10638     return SDValue();
10639   SDLoc dl(N);
10640   SmallVector<SDValue, 8> Ops;
10641   unsigned NumElts = VT.getVectorNumElements();
10642   for (unsigned i = 0; i < NumElts; ++i) {
10643     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10644     Ops.push_back(V);
10645     // Make the DAGCombiner fold the bitcast.
10646     DCI.AddToWorklist(V.getNode());
10647   }
10648   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10649   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10650   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10651 }
10652 
10653 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10654 static SDValue
10655 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10656   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10657   // At that time, we may have inserted bitcasts from integer to float.
10658   // If these bitcasts have survived DAGCombine, change the lowering of this
10659   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10660   // force to use floating point types.
10661 
10662   // Make sure we can change the type of the vector.
10663   // This is possible iff:
10664   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10665   //    1.1. Vector is used only once.
10666   //    1.2. Use is a bit convert to an integer type.
10667   // 2. The size of its operands are 32-bits (64-bits are not legal).
10668   EVT VT = N->getValueType(0);
10669   EVT EltVT = VT.getVectorElementType();
10670 
10671   // Check 1.1. and 2.
10672   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10673     return SDValue();
10674 
10675   // By construction, the input type must be float.
10676   assert(EltVT == MVT::f32 && "Unexpected type!");
10677 
10678   // Check 1.2.
10679   SDNode *Use = *N->use_begin();
10680   if (Use->getOpcode() != ISD::BITCAST ||
10681       Use->getValueType(0).isFloatingPoint())
10682     return SDValue();
10683 
10684   // Check profitability.
10685   // Model is, if more than half of the relevant operands are bitcast from
10686   // i32, turn the build_vector into a sequence of insert_vector_elt.
10687   // Relevant operands are everything that is not statically
10688   // (i.e., at compile time) bitcasted.
10689   unsigned NumOfBitCastedElts = 0;
10690   unsigned NumElts = VT.getVectorNumElements();
10691   unsigned NumOfRelevantElts = NumElts;
10692   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10693     SDValue Elt = N->getOperand(Idx);
10694     if (Elt->getOpcode() == ISD::BITCAST) {
10695       // Assume only bit cast to i32 will go away.
10696       if (Elt->getOperand(0).getValueType() == MVT::i32)
10697         ++NumOfBitCastedElts;
10698     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10699       // Constants are statically casted, thus do not count them as
10700       // relevant operands.
10701       --NumOfRelevantElts;
10702   }
10703 
10704   // Check if more than half of the elements require a non-free bitcast.
10705   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10706     return SDValue();
10707 
10708   SelectionDAG &DAG = DCI.DAG;
10709   // Create the new vector type.
10710   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10711   // Check if the type is legal.
10712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10713   if (!TLI.isTypeLegal(VecVT))
10714     return SDValue();
10715 
10716   // Combine:
10717   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10718   // => BITCAST INSERT_VECTOR_ELT
10719   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10720   //                      (BITCAST EN), N.
10721   SDValue Vec = DAG.getUNDEF(VecVT);
10722   SDLoc dl(N);
10723   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10724     SDValue V = N->getOperand(Idx);
10725     if (V.isUndef())
10726       continue;
10727     if (V.getOpcode() == ISD::BITCAST &&
10728         V->getOperand(0).getValueType() == MVT::i32)
10729       // Fold obvious case.
10730       V = V.getOperand(0);
10731     else {
10732       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10733       // Make the DAGCombiner fold the bitcasts.
10734       DCI.AddToWorklist(V.getNode());
10735     }
10736     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10737     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10738   }
10739   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10740   // Make the DAGCombiner fold the bitcasts.
10741   DCI.AddToWorklist(Vec.getNode());
10742   return Vec;
10743 }
10744 
10745 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10746 /// ISD::INSERT_VECTOR_ELT.
10747 static SDValue PerformInsertEltCombine(SDNode *N,
10748                                        TargetLowering::DAGCombinerInfo &DCI) {
10749   // Bitcast an i64 load inserted into a vector to f64.
10750   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10751   EVT VT = N->getValueType(0);
10752   SDNode *Elt = N->getOperand(1).getNode();
10753   if (VT.getVectorElementType() != MVT::i64 ||
10754       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10755     return SDValue();
10756 
10757   SelectionDAG &DAG = DCI.DAG;
10758   SDLoc dl(N);
10759   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10760                                  VT.getVectorNumElements());
10761   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10762   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10763   // Make the DAGCombiner fold the bitcasts.
10764   DCI.AddToWorklist(Vec.getNode());
10765   DCI.AddToWorklist(V.getNode());
10766   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10767                                Vec, V, N->getOperand(2));
10768   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10769 }
10770 
10771 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10772 /// ISD::VECTOR_SHUFFLE.
10773 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10774   // The LLVM shufflevector instruction does not require the shuffle mask
10775   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10776   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10777   // operands do not match the mask length, they are extended by concatenating
10778   // them with undef vectors.  That is probably the right thing for other
10779   // targets, but for NEON it is better to concatenate two double-register
10780   // size vector operands into a single quad-register size vector.  Do that
10781   // transformation here:
10782   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10783   //   shuffle(concat(v1, v2), undef)
10784   SDValue Op0 = N->getOperand(0);
10785   SDValue Op1 = N->getOperand(1);
10786   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10787       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10788       Op0.getNumOperands() != 2 ||
10789       Op1.getNumOperands() != 2)
10790     return SDValue();
10791   SDValue Concat0Op1 = Op0.getOperand(1);
10792   SDValue Concat1Op1 = Op1.getOperand(1);
10793   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10794     return SDValue();
10795   // Skip the transformation if any of the types are illegal.
10796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10797   EVT VT = N->getValueType(0);
10798   if (!TLI.isTypeLegal(VT) ||
10799       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10800       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10801     return SDValue();
10802 
10803   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10804                                   Op0.getOperand(0), Op1.getOperand(0));
10805   // Translate the shuffle mask.
10806   SmallVector<int, 16> NewMask;
10807   unsigned NumElts = VT.getVectorNumElements();
10808   unsigned HalfElts = NumElts/2;
10809   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10810   for (unsigned n = 0; n < NumElts; ++n) {
10811     int MaskElt = SVN->getMaskElt(n);
10812     int NewElt = -1;
10813     if (MaskElt < (int)HalfElts)
10814       NewElt = MaskElt;
10815     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10816       NewElt = HalfElts + MaskElt - NumElts;
10817     NewMask.push_back(NewElt);
10818   }
10819   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10820                               DAG.getUNDEF(VT), NewMask);
10821 }
10822 
10823 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10824 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10825 /// base address updates.
10826 /// For generic load/stores, the memory type is assumed to be a vector.
10827 /// The caller is assumed to have checked legality.
10828 static SDValue CombineBaseUpdate(SDNode *N,
10829                                  TargetLowering::DAGCombinerInfo &DCI) {
10830   SelectionDAG &DAG = DCI.DAG;
10831   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10832                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10833   const bool isStore = N->getOpcode() == ISD::STORE;
10834   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10835   SDValue Addr = N->getOperand(AddrOpIdx);
10836   MemSDNode *MemN = cast<MemSDNode>(N);
10837   SDLoc dl(N);
10838 
10839   // Search for a use of the address operand that is an increment.
10840   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10841          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10842     SDNode *User = *UI;
10843     if (User->getOpcode() != ISD::ADD ||
10844         UI.getUse().getResNo() != Addr.getResNo())
10845       continue;
10846 
10847     // Check that the add is independent of the load/store.  Otherwise, folding
10848     // it would create a cycle.
10849     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10850       continue;
10851 
10852     // Find the new opcode for the updating load/store.
10853     bool isLoadOp = true;
10854     bool isLaneOp = false;
10855     unsigned NewOpc = 0;
10856     unsigned NumVecs = 0;
10857     if (isIntrinsic) {
10858       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10859       switch (IntNo) {
10860       default: llvm_unreachable("unexpected intrinsic for Neon base update");
10861       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
10862         NumVecs = 1; break;
10863       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
10864         NumVecs = 2; break;
10865       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
10866         NumVecs = 3; break;
10867       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
10868         NumVecs = 4; break;
10869       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10870         NumVecs = 2; isLaneOp = true; break;
10871       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10872         NumVecs = 3; isLaneOp = true; break;
10873       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10874         NumVecs = 4; isLaneOp = true; break;
10875       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
10876         NumVecs = 1; isLoadOp = false; break;
10877       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
10878         NumVecs = 2; isLoadOp = false; break;
10879       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
10880         NumVecs = 3; isLoadOp = false; break;
10881       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
10882         NumVecs = 4; isLoadOp = false; break;
10883       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10884         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10885       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10886         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10887       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10888         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10889       }
10890     } else {
10891       isLaneOp = true;
10892       switch (N->getOpcode()) {
10893       default: llvm_unreachable("unexpected opcode for Neon base update");
10894       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
10895       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10896       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10897       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10898       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
10899         NumVecs = 1; isLaneOp = false; break;
10900       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
10901         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10902       }
10903     }
10904 
10905     // Find the size of memory referenced by the load/store.
10906     EVT VecTy;
10907     if (isLoadOp) {
10908       VecTy = N->getValueType(0);
10909     } else if (isIntrinsic) {
10910       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10911     } else {
10912       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10913       VecTy = N->getOperand(1).getValueType();
10914     }
10915 
10916     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10917     if (isLaneOp)
10918       NumBytes /= VecTy.getVectorNumElements();
10919 
10920     // If the increment is a constant, it must match the memory ref size.
10921     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10922     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
10923     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
10924       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10925       // separate instructions that make it harder to use a non-constant update.
10926       continue;
10927     }
10928 
10929     // OK, we found an ADD we can fold into the base update.
10930     // Now, create a _UPD node, taking care of not breaking alignment.
10931 
10932     EVT AlignedVecTy = VecTy;
10933     unsigned Alignment = MemN->getAlignment();
10934 
10935     // If this is a less-than-standard-aligned load/store, change the type to
10936     // match the standard alignment.
10937     // The alignment is overlooked when selecting _UPD variants; and it's
10938     // easier to introduce bitcasts here than fix that.
10939     // There are 3 ways to get to this base-update combine:
10940     // - intrinsics: they are assumed to be properly aligned (to the standard
10941     //   alignment of the memory type), so we don't need to do anything.
10942     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10943     //   intrinsics, so, likewise, there's nothing to do.
10944     // - generic load/store instructions: the alignment is specified as an
10945     //   explicit operand, rather than implicitly as the standard alignment
10946     //   of the memory type (like the intrisics).  We need to change the
10947     //   memory type to match the explicit alignment.  That way, we don't
10948     //   generate non-standard-aligned ARMISD::VLDx nodes.
10949     if (isa<LSBaseSDNode>(N)) {
10950       if (Alignment == 0)
10951         Alignment = 1;
10952       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10953         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10954         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10955         assert(!isLaneOp && "Unexpected generic load/store lane.");
10956         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10957         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10958       }
10959       // Don't set an explicit alignment on regular load/stores that we want
10960       // to transform to VLD/VST 1_UPD nodes.
10961       // This matches the behavior of regular load/stores, which only get an
10962       // explicit alignment if the MMO alignment is larger than the standard
10963       // alignment of the memory type.
10964       // Intrinsics, however, always get an explicit alignment, set to the
10965       // alignment of the MMO.
10966       Alignment = 1;
10967     }
10968 
10969     // Create the new updating load/store node.
10970     // First, create an SDVTList for the new updating node's results.
10971     EVT Tys[6];
10972     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10973     unsigned n;
10974     for (n = 0; n < NumResultVecs; ++n)
10975       Tys[n] = AlignedVecTy;
10976     Tys[n++] = MVT::i32;
10977     Tys[n] = MVT::Other;
10978     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10979 
10980     // Then, gather the new node's operands.
10981     SmallVector<SDValue, 8> Ops;
10982     Ops.push_back(N->getOperand(0)); // incoming chain
10983     Ops.push_back(N->getOperand(AddrOpIdx));
10984     Ops.push_back(Inc);
10985 
10986     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10987       // Try to match the intrinsic's signature
10988       Ops.push_back(StN->getValue());
10989     } else {
10990       // Loads (and of course intrinsics) match the intrinsics' signature,
10991       // so just add all but the alignment operand.
10992       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10993         Ops.push_back(N->getOperand(i));
10994     }
10995 
10996     // For all node types, the alignment operand is always the last one.
10997     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10998 
10999     // If this is a non-standard-aligned STORE, the penultimate operand is the
11000     // stored value.  Bitcast it to the aligned type.
11001     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11002       SDValue &StVal = Ops[Ops.size()-2];
11003       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11004     }
11005 
11006     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11007     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11008                                            MemN->getMemOperand());
11009 
11010     // Update the uses.
11011     SmallVector<SDValue, 5> NewResults;
11012     for (unsigned i = 0; i < NumResultVecs; ++i)
11013       NewResults.push_back(SDValue(UpdN.getNode(), i));
11014 
11015     // If this is an non-standard-aligned LOAD, the first result is the loaded
11016     // value.  Bitcast it to the expected result type.
11017     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11018       SDValue &LdVal = NewResults[0];
11019       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11020     }
11021 
11022     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11023     DCI.CombineTo(N, NewResults);
11024     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11025 
11026     break;
11027   }
11028   return SDValue();
11029 }
11030 
11031 static SDValue PerformVLDCombine(SDNode *N,
11032                                  TargetLowering::DAGCombinerInfo &DCI) {
11033   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11034     return SDValue();
11035 
11036   return CombineBaseUpdate(N, DCI);
11037 }
11038 
11039 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11040 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11041 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11042 /// return true.
11043 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11044   SelectionDAG &DAG = DCI.DAG;
11045   EVT VT = N->getValueType(0);
11046   // vldN-dup instructions only support 64-bit vectors for N > 1.
11047   if (!VT.is64BitVector())
11048     return false;
11049 
11050   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11051   SDNode *VLD = N->getOperand(0).getNode();
11052   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11053     return false;
11054   unsigned NumVecs = 0;
11055   unsigned NewOpc = 0;
11056   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11057   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11058     NumVecs = 2;
11059     NewOpc = ARMISD::VLD2DUP;
11060   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11061     NumVecs = 3;
11062     NewOpc = ARMISD::VLD3DUP;
11063   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11064     NumVecs = 4;
11065     NewOpc = ARMISD::VLD4DUP;
11066   } else {
11067     return false;
11068   }
11069 
11070   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11071   // numbers match the load.
11072   unsigned VLDLaneNo =
11073     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11074   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11075        UI != UE; ++UI) {
11076     // Ignore uses of the chain result.
11077     if (UI.getUse().getResNo() == NumVecs)
11078       continue;
11079     SDNode *User = *UI;
11080     if (User->getOpcode() != ARMISD::VDUPLANE ||
11081         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11082       return false;
11083   }
11084 
11085   // Create the vldN-dup node.
11086   EVT Tys[5];
11087   unsigned n;
11088   for (n = 0; n < NumVecs; ++n)
11089     Tys[n] = VT;
11090   Tys[n] = MVT::Other;
11091   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11092   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11093   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11094   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11095                                            Ops, VLDMemInt->getMemoryVT(),
11096                                            VLDMemInt->getMemOperand());
11097 
11098   // Update the uses.
11099   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11100        UI != UE; ++UI) {
11101     unsigned ResNo = UI.getUse().getResNo();
11102     // Ignore uses of the chain result.
11103     if (ResNo == NumVecs)
11104       continue;
11105     SDNode *User = *UI;
11106     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11107   }
11108 
11109   // Now the vldN-lane intrinsic is dead except for its chain result.
11110   // Update uses of the chain.
11111   std::vector<SDValue> VLDDupResults;
11112   for (unsigned n = 0; n < NumVecs; ++n)
11113     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11114   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11115   DCI.CombineTo(VLD, VLDDupResults);
11116 
11117   return true;
11118 }
11119 
11120 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11121 /// ARMISD::VDUPLANE.
11122 static SDValue PerformVDUPLANECombine(SDNode *N,
11123                                       TargetLowering::DAGCombinerInfo &DCI) {
11124   SDValue Op = N->getOperand(0);
11125 
11126   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11127   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11128   if (CombineVLDDUP(N, DCI))
11129     return SDValue(N, 0);
11130 
11131   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11132   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11133   while (Op.getOpcode() == ISD::BITCAST)
11134     Op = Op.getOperand(0);
11135   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11136     return SDValue();
11137 
11138   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11139   unsigned EltSize = Op.getScalarValueSizeInBits();
11140   // The canonical VMOV for a zero vector uses a 32-bit element size.
11141   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11142   unsigned EltBits;
11143   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11144     EltSize = 8;
11145   EVT VT = N->getValueType(0);
11146   if (EltSize > VT.getScalarSizeInBits())
11147     return SDValue();
11148 
11149   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11150 }
11151 
11152 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11153 static SDValue PerformVDUPCombine(SDNode *N,
11154                                   TargetLowering::DAGCombinerInfo &DCI) {
11155   SelectionDAG &DAG = DCI.DAG;
11156   SDValue Op = N->getOperand(0);
11157 
11158   // Match VDUP(LOAD) -> VLD1DUP.
11159   // We match this pattern here rather than waiting for isel because the
11160   // transform is only legal for unindexed loads.
11161   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11162   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11163       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11164     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11165                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11166     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11167     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11168                                              Ops, LD->getMemoryVT(),
11169                                              LD->getMemOperand());
11170     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11171     return VLDDup;
11172   }
11173 
11174   return SDValue();
11175 }
11176 
11177 static SDValue PerformLOADCombine(SDNode *N,
11178                                   TargetLowering::DAGCombinerInfo &DCI) {
11179   EVT VT = N->getValueType(0);
11180 
11181   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11182   if (ISD::isNormalLoad(N) && VT.isVector() &&
11183       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11184     return CombineBaseUpdate(N, DCI);
11185 
11186   return SDValue();
11187 }
11188 
11189 /// PerformSTORECombine - Target-specific dag combine xforms for
11190 /// ISD::STORE.
11191 static SDValue PerformSTORECombine(SDNode *N,
11192                                    TargetLowering::DAGCombinerInfo &DCI) {
11193   StoreSDNode *St = cast<StoreSDNode>(N);
11194   if (St->isVolatile())
11195     return SDValue();
11196 
11197   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11198   // pack all of the elements in one place.  Next, store to memory in fewer
11199   // chunks.
11200   SDValue StVal = St->getValue();
11201   EVT VT = StVal.getValueType();
11202   if (St->isTruncatingStore() && VT.isVector()) {
11203     SelectionDAG &DAG = DCI.DAG;
11204     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11205     EVT StVT = St->getMemoryVT();
11206     unsigned NumElems = VT.getVectorNumElements();
11207     assert(StVT != VT && "Cannot truncate to the same type");
11208     unsigned FromEltSz = VT.getScalarSizeInBits();
11209     unsigned ToEltSz = StVT.getScalarSizeInBits();
11210 
11211     // From, To sizes and ElemCount must be pow of two
11212     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11213 
11214     // We are going to use the original vector elt for storing.
11215     // Accumulated smaller vector elements must be a multiple of the store size.
11216     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11217 
11218     unsigned SizeRatio  = FromEltSz / ToEltSz;
11219     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11220 
11221     // Create a type on which we perform the shuffle.
11222     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11223                                      NumElems*SizeRatio);
11224     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11225 
11226     SDLoc DL(St);
11227     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11228     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11229     for (unsigned i = 0; i < NumElems; ++i)
11230       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11231                           ? (i + 1) * SizeRatio - 1
11232                           : i * SizeRatio;
11233 
11234     // Can't shuffle using an illegal type.
11235     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11236 
11237     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11238                                 DAG.getUNDEF(WideVec.getValueType()),
11239                                 ShuffleVec);
11240     // At this point all of the data is stored at the bottom of the
11241     // register. We now need to save it to mem.
11242 
11243     // Find the largest store unit
11244     MVT StoreType = MVT::i8;
11245     for (MVT Tp : MVT::integer_valuetypes()) {
11246       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11247         StoreType = Tp;
11248     }
11249     // Didn't find a legal store type.
11250     if (!TLI.isTypeLegal(StoreType))
11251       return SDValue();
11252 
11253     // Bitcast the original vector into a vector of store-size units
11254     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11255             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11256     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11257     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11258     SmallVector<SDValue, 8> Chains;
11259     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11260                                         TLI.getPointerTy(DAG.getDataLayout()));
11261     SDValue BasePtr = St->getBasePtr();
11262 
11263     // Perform one or more big stores into memory.
11264     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11265     for (unsigned I = 0; I < E; I++) {
11266       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11267                                    StoreType, ShuffWide,
11268                                    DAG.getIntPtrConstant(I, DL));
11269       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11270                                 St->getPointerInfo(), St->getAlignment(),
11271                                 St->getMemOperand()->getFlags());
11272       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11273                             Increment);
11274       Chains.push_back(Ch);
11275     }
11276     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11277   }
11278 
11279   if (!ISD::isNormalStore(St))
11280     return SDValue();
11281 
11282   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11283   // ARM stores of arguments in the same cache line.
11284   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11285       StVal.getNode()->hasOneUse()) {
11286     SelectionDAG  &DAG = DCI.DAG;
11287     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11288     SDLoc DL(St);
11289     SDValue BasePtr = St->getBasePtr();
11290     SDValue NewST1 = DAG.getStore(
11291         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11292         BasePtr, St->getPointerInfo(), St->getAlignment(),
11293         St->getMemOperand()->getFlags());
11294 
11295     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11296                                     DAG.getConstant(4, DL, MVT::i32));
11297     return DAG.getStore(NewST1.getValue(0), DL,
11298                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11299                         OffsetPtr, St->getPointerInfo(),
11300                         std::min(4U, St->getAlignment() / 2),
11301                         St->getMemOperand()->getFlags());
11302   }
11303 
11304   if (StVal.getValueType() == MVT::i64 &&
11305       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11306 
11307     // Bitcast an i64 store extracted from a vector to f64.
11308     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11309     SelectionDAG &DAG = DCI.DAG;
11310     SDLoc dl(StVal);
11311     SDValue IntVec = StVal.getOperand(0);
11312     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11313                                    IntVec.getValueType().getVectorNumElements());
11314     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11315     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11316                                  Vec, StVal.getOperand(1));
11317     dl = SDLoc(N);
11318     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11319     // Make the DAGCombiner fold the bitcasts.
11320     DCI.AddToWorklist(Vec.getNode());
11321     DCI.AddToWorklist(ExtElt.getNode());
11322     DCI.AddToWorklist(V.getNode());
11323     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11324                         St->getPointerInfo(), St->getAlignment(),
11325                         St->getMemOperand()->getFlags(), St->getAAInfo());
11326   }
11327 
11328   // If this is a legal vector store, try to combine it into a VST1_UPD.
11329   if (ISD::isNormalStore(N) && VT.isVector() &&
11330       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11331     return CombineBaseUpdate(N, DCI);
11332 
11333   return SDValue();
11334 }
11335 
11336 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11337 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11338 /// when the VMUL has a constant operand that is a power of 2.
11339 ///
11340 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11341 ///  vmul.f32        d16, d17, d16
11342 ///  vcvt.s32.f32    d16, d16
11343 /// becomes:
11344 ///  vcvt.s32.f32    d16, d16, #3
11345 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11346                                   const ARMSubtarget *Subtarget) {
11347   if (!Subtarget->hasNEON())
11348     return SDValue();
11349 
11350   SDValue Op = N->getOperand(0);
11351   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11352       Op.getOpcode() != ISD::FMUL)
11353     return SDValue();
11354 
11355   SDValue ConstVec = Op->getOperand(1);
11356   if (!isa<BuildVectorSDNode>(ConstVec))
11357     return SDValue();
11358 
11359   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11360   uint32_t FloatBits = FloatTy.getSizeInBits();
11361   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11362   uint32_t IntBits = IntTy.getSizeInBits();
11363   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11364   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11365     // These instructions only exist converting from f32 to i32. We can handle
11366     // smaller integers by generating an extra truncate, but larger ones would
11367     // be lossy. We also can't handle more then 4 lanes, since these intructions
11368     // only support v2i32/v4i32 types.
11369     return SDValue();
11370   }
11371 
11372   BitVector UndefElements;
11373   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11374   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11375   if (C == -1 || C == 0 || C > 32)
11376     return SDValue();
11377 
11378   SDLoc dl(N);
11379   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11380   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11381     Intrinsic::arm_neon_vcvtfp2fxu;
11382   SDValue FixConv = DAG.getNode(
11383       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11384       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11385       DAG.getConstant(C, dl, MVT::i32));
11386 
11387   if (IntBits < FloatBits)
11388     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11389 
11390   return FixConv;
11391 }
11392 
11393 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11394 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11395 /// when the VDIV has a constant operand that is a power of 2.
11396 ///
11397 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11398 ///  vcvt.f32.s32    d16, d16
11399 ///  vdiv.f32        d16, d17, d16
11400 /// becomes:
11401 ///  vcvt.f32.s32    d16, d16, #3
11402 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11403                                   const ARMSubtarget *Subtarget) {
11404   if (!Subtarget->hasNEON())
11405     return SDValue();
11406 
11407   SDValue Op = N->getOperand(0);
11408   unsigned OpOpcode = Op.getNode()->getOpcode();
11409   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11410       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11411     return SDValue();
11412 
11413   SDValue ConstVec = N->getOperand(1);
11414   if (!isa<BuildVectorSDNode>(ConstVec))
11415     return SDValue();
11416 
11417   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11418   uint32_t FloatBits = FloatTy.getSizeInBits();
11419   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11420   uint32_t IntBits = IntTy.getSizeInBits();
11421   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11422   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11423     // These instructions only exist converting from i32 to f32. We can handle
11424     // smaller integers by generating an extra extend, but larger ones would
11425     // be lossy. We also can't handle more then 4 lanes, since these intructions
11426     // only support v2i32/v4i32 types.
11427     return SDValue();
11428   }
11429 
11430   BitVector UndefElements;
11431   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11432   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11433   if (C == -1 || C == 0 || C > 32)
11434     return SDValue();
11435 
11436   SDLoc dl(N);
11437   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11438   SDValue ConvInput = Op.getOperand(0);
11439   if (IntBits < FloatBits)
11440     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11441                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11442                             ConvInput);
11443 
11444   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11445     Intrinsic::arm_neon_vcvtfxu2fp;
11446   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11447                      Op.getValueType(),
11448                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11449                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11450 }
11451 
11452 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11453 /// operand of a vector shift operation, where all the elements of the
11454 /// build_vector must have the same constant integer value.
11455 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11456   // Ignore bit_converts.
11457   while (Op.getOpcode() == ISD::BITCAST)
11458     Op = Op.getOperand(0);
11459   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11460   APInt SplatBits, SplatUndef;
11461   unsigned SplatBitSize;
11462   bool HasAnyUndefs;
11463   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11464                                       HasAnyUndefs, ElementBits) ||
11465       SplatBitSize > ElementBits)
11466     return false;
11467   Cnt = SplatBits.getSExtValue();
11468   return true;
11469 }
11470 
11471 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11472 /// operand of a vector shift left operation.  That value must be in the range:
11473 ///   0 <= Value < ElementBits for a left shift; or
11474 ///   0 <= Value <= ElementBits for a long left shift.
11475 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11476   assert(VT.isVector() && "vector shift count is not a vector type");
11477   int64_t ElementBits = VT.getScalarSizeInBits();
11478   if (! getVShiftImm(Op, ElementBits, Cnt))
11479     return false;
11480   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11481 }
11482 
11483 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11484 /// operand of a vector shift right operation.  For a shift opcode, the value
11485 /// is positive, but for an intrinsic the value count must be negative. The
11486 /// absolute value must be in the range:
11487 ///   1 <= |Value| <= ElementBits for a right shift; or
11488 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11489 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11490                          int64_t &Cnt) {
11491   assert(VT.isVector() && "vector shift count is not a vector type");
11492   int64_t ElementBits = VT.getScalarSizeInBits();
11493   if (! getVShiftImm(Op, ElementBits, Cnt))
11494     return false;
11495   if (!isIntrinsic)
11496     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11497   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11498     Cnt = -Cnt;
11499     return true;
11500   }
11501   return false;
11502 }
11503 
11504 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11505 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11506   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11507   switch (IntNo) {
11508   default:
11509     // Don't do anything for most intrinsics.
11510     break;
11511 
11512   // Vector shifts: check for immediate versions and lower them.
11513   // Note: This is done during DAG combining instead of DAG legalizing because
11514   // the build_vectors for 64-bit vector element shift counts are generally
11515   // not legal, and it is hard to see their values after they get legalized to
11516   // loads from a constant pool.
11517   case Intrinsic::arm_neon_vshifts:
11518   case Intrinsic::arm_neon_vshiftu:
11519   case Intrinsic::arm_neon_vrshifts:
11520   case Intrinsic::arm_neon_vrshiftu:
11521   case Intrinsic::arm_neon_vrshiftn:
11522   case Intrinsic::arm_neon_vqshifts:
11523   case Intrinsic::arm_neon_vqshiftu:
11524   case Intrinsic::arm_neon_vqshiftsu:
11525   case Intrinsic::arm_neon_vqshiftns:
11526   case Intrinsic::arm_neon_vqshiftnu:
11527   case Intrinsic::arm_neon_vqshiftnsu:
11528   case Intrinsic::arm_neon_vqrshiftns:
11529   case Intrinsic::arm_neon_vqrshiftnu:
11530   case Intrinsic::arm_neon_vqrshiftnsu: {
11531     EVT VT = N->getOperand(1).getValueType();
11532     int64_t Cnt;
11533     unsigned VShiftOpc = 0;
11534 
11535     switch (IntNo) {
11536     case Intrinsic::arm_neon_vshifts:
11537     case Intrinsic::arm_neon_vshiftu:
11538       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11539         VShiftOpc = ARMISD::VSHL;
11540         break;
11541       }
11542       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11543         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11544                      ARMISD::VSHRs : ARMISD::VSHRu);
11545         break;
11546       }
11547       return SDValue();
11548 
11549     case Intrinsic::arm_neon_vrshifts:
11550     case Intrinsic::arm_neon_vrshiftu:
11551       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11552         break;
11553       return SDValue();
11554 
11555     case Intrinsic::arm_neon_vqshifts:
11556     case Intrinsic::arm_neon_vqshiftu:
11557       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11558         break;
11559       return SDValue();
11560 
11561     case Intrinsic::arm_neon_vqshiftsu:
11562       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11563         break;
11564       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11565 
11566     case Intrinsic::arm_neon_vrshiftn:
11567     case Intrinsic::arm_neon_vqshiftns:
11568     case Intrinsic::arm_neon_vqshiftnu:
11569     case Intrinsic::arm_neon_vqshiftnsu:
11570     case Intrinsic::arm_neon_vqrshiftns:
11571     case Intrinsic::arm_neon_vqrshiftnu:
11572     case Intrinsic::arm_neon_vqrshiftnsu:
11573       // Narrowing shifts require an immediate right shift.
11574       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11575         break;
11576       llvm_unreachable("invalid shift count for narrowing vector shift "
11577                        "intrinsic");
11578 
11579     default:
11580       llvm_unreachable("unhandled vector shift");
11581     }
11582 
11583     switch (IntNo) {
11584     case Intrinsic::arm_neon_vshifts:
11585     case Intrinsic::arm_neon_vshiftu:
11586       // Opcode already set above.
11587       break;
11588     case Intrinsic::arm_neon_vrshifts:
11589       VShiftOpc = ARMISD::VRSHRs; break;
11590     case Intrinsic::arm_neon_vrshiftu:
11591       VShiftOpc = ARMISD::VRSHRu; break;
11592     case Intrinsic::arm_neon_vrshiftn:
11593       VShiftOpc = ARMISD::VRSHRN; break;
11594     case Intrinsic::arm_neon_vqshifts:
11595       VShiftOpc = ARMISD::VQSHLs; break;
11596     case Intrinsic::arm_neon_vqshiftu:
11597       VShiftOpc = ARMISD::VQSHLu; break;
11598     case Intrinsic::arm_neon_vqshiftsu:
11599       VShiftOpc = ARMISD::VQSHLsu; break;
11600     case Intrinsic::arm_neon_vqshiftns:
11601       VShiftOpc = ARMISD::VQSHRNs; break;
11602     case Intrinsic::arm_neon_vqshiftnu:
11603       VShiftOpc = ARMISD::VQSHRNu; break;
11604     case Intrinsic::arm_neon_vqshiftnsu:
11605       VShiftOpc = ARMISD::VQSHRNsu; break;
11606     case Intrinsic::arm_neon_vqrshiftns:
11607       VShiftOpc = ARMISD::VQRSHRNs; break;
11608     case Intrinsic::arm_neon_vqrshiftnu:
11609       VShiftOpc = ARMISD::VQRSHRNu; break;
11610     case Intrinsic::arm_neon_vqrshiftnsu:
11611       VShiftOpc = ARMISD::VQRSHRNsu; break;
11612     }
11613 
11614     SDLoc dl(N);
11615     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11616                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11617   }
11618 
11619   case Intrinsic::arm_neon_vshiftins: {
11620     EVT VT = N->getOperand(1).getValueType();
11621     int64_t Cnt;
11622     unsigned VShiftOpc = 0;
11623 
11624     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11625       VShiftOpc = ARMISD::VSLI;
11626     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11627       VShiftOpc = ARMISD::VSRI;
11628     else {
11629       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11630     }
11631 
11632     SDLoc dl(N);
11633     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11634                        N->getOperand(1), N->getOperand(2),
11635                        DAG.getConstant(Cnt, dl, MVT::i32));
11636   }
11637 
11638   case Intrinsic::arm_neon_vqrshifts:
11639   case Intrinsic::arm_neon_vqrshiftu:
11640     // No immediate versions of these to check for.
11641     break;
11642   }
11643 
11644   return SDValue();
11645 }
11646 
11647 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11648 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11649 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11650 /// vector element shift counts are generally not legal, and it is hard to see
11651 /// their values after they get legalized to loads from a constant pool.
11652 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11653                                    const ARMSubtarget *ST) {
11654   EVT VT = N->getValueType(0);
11655   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11656     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11657     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11658     SDValue N1 = N->getOperand(1);
11659     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11660       SDValue N0 = N->getOperand(0);
11661       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11662           DAG.MaskedValueIsZero(N0.getOperand(0),
11663                                 APInt::getHighBitsSet(32, 16)))
11664         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11665     }
11666   }
11667 
11668   // Nothing to be done for scalar shifts.
11669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11670   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11671     return SDValue();
11672 
11673   assert(ST->hasNEON() && "unexpected vector shift");
11674   int64_t Cnt;
11675 
11676   switch (N->getOpcode()) {
11677   default: llvm_unreachable("unexpected shift opcode");
11678 
11679   case ISD::SHL:
11680     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11681       SDLoc dl(N);
11682       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11683                          DAG.getConstant(Cnt, dl, MVT::i32));
11684     }
11685     break;
11686 
11687   case ISD::SRA:
11688   case ISD::SRL:
11689     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11690       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11691                             ARMISD::VSHRs : ARMISD::VSHRu);
11692       SDLoc dl(N);
11693       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11694                          DAG.getConstant(Cnt, dl, MVT::i32));
11695     }
11696   }
11697   return SDValue();
11698 }
11699 
11700 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11701 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11702 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11703                                     const ARMSubtarget *ST) {
11704   SDValue N0 = N->getOperand(0);
11705 
11706   // Check for sign- and zero-extensions of vector extract operations of 8-
11707   // and 16-bit vector elements.  NEON supports these directly.  They are
11708   // handled during DAG combining because type legalization will promote them
11709   // to 32-bit types and it is messy to recognize the operations after that.
11710   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11711     SDValue Vec = N0.getOperand(0);
11712     SDValue Lane = N0.getOperand(1);
11713     EVT VT = N->getValueType(0);
11714     EVT EltVT = N0.getValueType();
11715     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11716 
11717     if (VT == MVT::i32 &&
11718         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11719         TLI.isTypeLegal(Vec.getValueType()) &&
11720         isa<ConstantSDNode>(Lane)) {
11721 
11722       unsigned Opc = 0;
11723       switch (N->getOpcode()) {
11724       default: llvm_unreachable("unexpected opcode");
11725       case ISD::SIGN_EXTEND:
11726         Opc = ARMISD::VGETLANEs;
11727         break;
11728       case ISD::ZERO_EXTEND:
11729       case ISD::ANY_EXTEND:
11730         Opc = ARMISD::VGETLANEu;
11731         break;
11732       }
11733       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11734     }
11735   }
11736 
11737   return SDValue();
11738 }
11739 
11740 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11741   // If we have a CMOV, OR and AND combination such as:
11742   //   if (x & CN)
11743   //     y |= CM;
11744   //
11745   // And:
11746   //   * CN is a single bit;
11747   //   * All bits covered by CM are known zero in y
11748   //
11749   // Then we can convert this into a sequence of BFI instructions. This will
11750   // always be a win if CM is a single bit, will always be no worse than the
11751   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11752   // three bits (due to the extra IT instruction).
11753 
11754   SDValue Op0 = CMOV->getOperand(0);
11755   SDValue Op1 = CMOV->getOperand(1);
11756   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11757   auto CC = CCNode->getAPIntValue().getLimitedValue();
11758   SDValue CmpZ = CMOV->getOperand(4);
11759 
11760   // The compare must be against zero.
11761   if (!isNullConstant(CmpZ->getOperand(1)))
11762     return SDValue();
11763 
11764   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11765   SDValue And = CmpZ->getOperand(0);
11766   if (And->getOpcode() != ISD::AND)
11767     return SDValue();
11768   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11769   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11770     return SDValue();
11771   SDValue X = And->getOperand(0);
11772 
11773   if (CC == ARMCC::EQ) {
11774     // We're performing an "equal to zero" compare. Swap the operands so we
11775     // canonicalize on a "not equal to zero" compare.
11776     std::swap(Op0, Op1);
11777   } else {
11778     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11779   }
11780 
11781   if (Op1->getOpcode() != ISD::OR)
11782     return SDValue();
11783 
11784   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11785   if (!OrC)
11786     return SDValue();
11787   SDValue Y = Op1->getOperand(0);
11788 
11789   if (Op0 != Y)
11790     return SDValue();
11791 
11792   // Now, is it profitable to continue?
11793   APInt OrCI = OrC->getAPIntValue();
11794   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11795   if (OrCI.countPopulation() > Heuristic)
11796     return SDValue();
11797 
11798   // Lastly, can we determine that the bits defined by OrCI
11799   // are zero in Y?
11800   KnownBits Known;
11801   DAG.computeKnownBits(Y, Known);
11802   if ((OrCI & Known.Zero) != OrCI)
11803     return SDValue();
11804 
11805   // OK, we can do the combine.
11806   SDValue V = Y;
11807   SDLoc dl(X);
11808   EVT VT = X.getValueType();
11809   unsigned BitInX = AndC->getAPIntValue().logBase2();
11810 
11811   if (BitInX != 0) {
11812     // We must shift X first.
11813     X = DAG.getNode(ISD::SRL, dl, VT, X,
11814                     DAG.getConstant(BitInX, dl, VT));
11815   }
11816 
11817   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11818        BitInY < NumActiveBits; ++BitInY) {
11819     if (OrCI[BitInY] == 0)
11820       continue;
11821     APInt Mask(VT.getSizeInBits(), 0);
11822     Mask.setBit(BitInY);
11823     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11824                     // Confusingly, the operand is an *inverted* mask.
11825                     DAG.getConstant(~Mask, dl, VT));
11826   }
11827 
11828   return V;
11829 }
11830 
11831 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11832 SDValue
11833 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11834   SDValue Cmp = N->getOperand(4);
11835   if (Cmp.getOpcode() != ARMISD::CMPZ)
11836     // Only looking at NE cases.
11837     return SDValue();
11838 
11839   EVT VT = N->getValueType(0);
11840   SDLoc dl(N);
11841   SDValue LHS = Cmp.getOperand(0);
11842   SDValue RHS = Cmp.getOperand(1);
11843   SDValue Chain = N->getOperand(0);
11844   SDValue BB = N->getOperand(1);
11845   SDValue ARMcc = N->getOperand(2);
11846   ARMCC::CondCodes CC =
11847     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11848 
11849   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11850   // -> (brcond Chain BB CC CPSR Cmp)
11851   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11852       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11853       LHS->getOperand(0)->hasOneUse()) {
11854     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11855     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11856     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11857     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11858     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11859         (LHS01C && LHS01C->getZExtValue() == 1) &&
11860         (LHS1C && LHS1C->getZExtValue() == 1) &&
11861         (RHSC && RHSC->getZExtValue() == 0)) {
11862       return DAG.getNode(
11863           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11864           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11865     }
11866   }
11867 
11868   return SDValue();
11869 }
11870 
11871 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11872 SDValue
11873 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11874   SDValue Cmp = N->getOperand(4);
11875   if (Cmp.getOpcode() != ARMISD::CMPZ)
11876     // Only looking at EQ and NE cases.
11877     return SDValue();
11878 
11879   EVT VT = N->getValueType(0);
11880   SDLoc dl(N);
11881   SDValue LHS = Cmp.getOperand(0);
11882   SDValue RHS = Cmp.getOperand(1);
11883   SDValue FalseVal = N->getOperand(0);
11884   SDValue TrueVal = N->getOperand(1);
11885   SDValue ARMcc = N->getOperand(2);
11886   ARMCC::CondCodes CC =
11887     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11888 
11889   // BFI is only available on V6T2+.
11890   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11891     SDValue R = PerformCMOVToBFICombine(N, DAG);
11892     if (R)
11893       return R;
11894   }
11895 
11896   // Simplify
11897   //   mov     r1, r0
11898   //   cmp     r1, x
11899   //   mov     r0, y
11900   //   moveq   r0, x
11901   // to
11902   //   cmp     r0, x
11903   //   movne   r0, y
11904   //
11905   //   mov     r1, r0
11906   //   cmp     r1, x
11907   //   mov     r0, x
11908   //   movne   r0, y
11909   // to
11910   //   cmp     r0, x
11911   //   movne   r0, y
11912   /// FIXME: Turn this into a target neutral optimization?
11913   SDValue Res;
11914   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11915     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11916                       N->getOperand(3), Cmp);
11917   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11918     SDValue ARMcc;
11919     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11920     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11921                       N->getOperand(3), NewCmp);
11922   }
11923 
11924   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11925   // -> (cmov F T CC CPSR Cmp)
11926   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11927     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11928     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11929     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11930     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11931         (LHS1C && LHS1C->getZExtValue() == 1) &&
11932         (RHSC && RHSC->getZExtValue() == 0)) {
11933       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11934                          LHS->getOperand(2), LHS->getOperand(3),
11935                          LHS->getOperand(4));
11936     }
11937   }
11938 
11939   if (Res.getNode()) {
11940     KnownBits Known;
11941     DAG.computeKnownBits(SDValue(N,0), Known);
11942     // Capture demanded bits information that would be otherwise lost.
11943     if (Known.Zero == 0xfffffffe)
11944       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11945                         DAG.getValueType(MVT::i1));
11946     else if (Known.Zero == 0xffffff00)
11947       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11948                         DAG.getValueType(MVT::i8));
11949     else if (Known.Zero == 0xffff0000)
11950       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11951                         DAG.getValueType(MVT::i16));
11952   }
11953 
11954   return Res;
11955 }
11956 
11957 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11958                                              DAGCombinerInfo &DCI) const {
11959   switch (N->getOpcode()) {
11960   default: break;
11961   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
11962   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
11963   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11964   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11965   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11966   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11967   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11968   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11969   case ARMISD::ADDC:
11970   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI.DAG, Subtarget);
11971   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
11972   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11973   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11974   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11975   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11976   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11977   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11978   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11979   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11980   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
11981   case ISD::FP_TO_SINT:
11982   case ISD::FP_TO_UINT:
11983     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11984   case ISD::FDIV:
11985     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11986   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11987   case ISD::SHL:
11988   case ISD::SRA:
11989   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11990   case ISD::SIGN_EXTEND:
11991   case ISD::ZERO_EXTEND:
11992   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11993   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11994   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11995   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11996   case ARMISD::VLD1DUP:
11997   case ARMISD::VLD2DUP:
11998   case ARMISD::VLD3DUP:
11999   case ARMISD::VLD4DUP:
12000     return PerformVLDCombine(N, DCI);
12001   case ARMISD::BUILD_VECTOR:
12002     return PerformARMBUILD_VECTORCombine(N, DCI);
12003   case ARMISD::SMULWB: {
12004     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12005     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12006     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12007       return SDValue();
12008     break;
12009   }
12010   case ARMISD::SMULWT: {
12011     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12012     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12013     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12014       return SDValue();
12015     break;
12016   }
12017   case ARMISD::SMLALBB: {
12018     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12019     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12020     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12021         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12022       return SDValue();
12023     break;
12024   }
12025   case ARMISD::SMLALBT: {
12026     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12027     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12028     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12029     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12030     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12031         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12032       return SDValue();
12033     break;
12034   }
12035   case ARMISD::SMLALTB: {
12036     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12037     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12038     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12039     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12040     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12041         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12042       return SDValue();
12043     break;
12044   }
12045   case ARMISD::SMLALTT: {
12046     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12047     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12048     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12049         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12050       return SDValue();
12051     break;
12052   }
12053   case ISD::INTRINSIC_VOID:
12054   case ISD::INTRINSIC_W_CHAIN:
12055     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12056     case Intrinsic::arm_neon_vld1:
12057     case Intrinsic::arm_neon_vld2:
12058     case Intrinsic::arm_neon_vld3:
12059     case Intrinsic::arm_neon_vld4:
12060     case Intrinsic::arm_neon_vld2lane:
12061     case Intrinsic::arm_neon_vld3lane:
12062     case Intrinsic::arm_neon_vld4lane:
12063     case Intrinsic::arm_neon_vst1:
12064     case Intrinsic::arm_neon_vst2:
12065     case Intrinsic::arm_neon_vst3:
12066     case Intrinsic::arm_neon_vst4:
12067     case Intrinsic::arm_neon_vst2lane:
12068     case Intrinsic::arm_neon_vst3lane:
12069     case Intrinsic::arm_neon_vst4lane:
12070       return PerformVLDCombine(N, DCI);
12071     default: break;
12072     }
12073     break;
12074   }
12075   return SDValue();
12076 }
12077 
12078 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12079                                                           EVT VT) const {
12080   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12081 }
12082 
12083 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12084                                                        unsigned,
12085                                                        unsigned,
12086                                                        bool *Fast) const {
12087   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12088   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12089 
12090   switch (VT.getSimpleVT().SimpleTy) {
12091   default:
12092     return false;
12093   case MVT::i8:
12094   case MVT::i16:
12095   case MVT::i32: {
12096     // Unaligned access can use (for example) LRDB, LRDH, LDR
12097     if (AllowsUnaligned) {
12098       if (Fast)
12099         *Fast = Subtarget->hasV7Ops();
12100       return true;
12101     }
12102     return false;
12103   }
12104   case MVT::f64:
12105   case MVT::v2f64: {
12106     // For any little-endian targets with neon, we can support unaligned ld/st
12107     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12108     // A big-endian target may also explicitly support unaligned accesses
12109     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12110       if (Fast)
12111         *Fast = true;
12112       return true;
12113     }
12114     return false;
12115   }
12116   }
12117 }
12118 
12119 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12120                        unsigned AlignCheck) {
12121   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12122           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12123 }
12124 
12125 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12126                                            unsigned DstAlign, unsigned SrcAlign,
12127                                            bool IsMemset, bool ZeroMemset,
12128                                            bool MemcpyStrSrc,
12129                                            MachineFunction &MF) const {
12130   const Function *F = MF.getFunction();
12131 
12132   // See if we can use NEON instructions for this...
12133   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12134       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12135     bool Fast;
12136     if (Size >= 16 &&
12137         (memOpAlign(SrcAlign, DstAlign, 16) ||
12138          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12139       return MVT::v2f64;
12140     } else if (Size >= 8 &&
12141                (memOpAlign(SrcAlign, DstAlign, 8) ||
12142                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12143                  Fast))) {
12144       return MVT::f64;
12145     }
12146   }
12147 
12148   // Lowering to i32/i16 if the size permits.
12149   if (Size >= 4)
12150     return MVT::i32;
12151   else if (Size >= 2)
12152     return MVT::i16;
12153 
12154   // Let the target-independent logic figure it out.
12155   return MVT::Other;
12156 }
12157 
12158 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12159   if (Val.getOpcode() != ISD::LOAD)
12160     return false;
12161 
12162   EVT VT1 = Val.getValueType();
12163   if (!VT1.isSimple() || !VT1.isInteger() ||
12164       !VT2.isSimple() || !VT2.isInteger())
12165     return false;
12166 
12167   switch (VT1.getSimpleVT().SimpleTy) {
12168   default: break;
12169   case MVT::i1:
12170   case MVT::i8:
12171   case MVT::i16:
12172     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12173     return true;
12174   }
12175 
12176   return false;
12177 }
12178 
12179 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12180   EVT VT = ExtVal.getValueType();
12181 
12182   if (!isTypeLegal(VT))
12183     return false;
12184 
12185   // Don't create a loadext if we can fold the extension into a wide/long
12186   // instruction.
12187   // If there's more than one user instruction, the loadext is desirable no
12188   // matter what.  There can be two uses by the same instruction.
12189   if (ExtVal->use_empty() ||
12190       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12191     return true;
12192 
12193   SDNode *U = *ExtVal->use_begin();
12194   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12195        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12196     return false;
12197 
12198   return true;
12199 }
12200 
12201 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12202   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12203     return false;
12204 
12205   if (!isTypeLegal(EVT::getEVT(Ty1)))
12206     return false;
12207 
12208   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12209 
12210   // Assuming the caller doesn't have a zeroext or signext return parameter,
12211   // truncation all the way down to i1 is valid.
12212   return true;
12213 }
12214 
12215 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12216                                                 const AddrMode &AM, Type *Ty,
12217                                                 unsigned AS) const {
12218   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12219     if (Subtarget->hasFPAO())
12220       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12221     return 0;
12222   }
12223   return -1;
12224 }
12225 
12226 
12227 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12228   if (V < 0)
12229     return false;
12230 
12231   unsigned Scale = 1;
12232   switch (VT.getSimpleVT().SimpleTy) {
12233   default: return false;
12234   case MVT::i1:
12235   case MVT::i8:
12236     // Scale == 1;
12237     break;
12238   case MVT::i16:
12239     // Scale == 2;
12240     Scale = 2;
12241     break;
12242   case MVT::i32:
12243     // Scale == 4;
12244     Scale = 4;
12245     break;
12246   }
12247 
12248   if ((V & (Scale - 1)) != 0)
12249     return false;
12250   V /= Scale;
12251   return V == (V & ((1LL << 5) - 1));
12252 }
12253 
12254 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12255                                       const ARMSubtarget *Subtarget) {
12256   bool isNeg = false;
12257   if (V < 0) {
12258     isNeg = true;
12259     V = - V;
12260   }
12261 
12262   switch (VT.getSimpleVT().SimpleTy) {
12263   default: return false;
12264   case MVT::i1:
12265   case MVT::i8:
12266   case MVT::i16:
12267   case MVT::i32:
12268     // + imm12 or - imm8
12269     if (isNeg)
12270       return V == (V & ((1LL << 8) - 1));
12271     return V == (V & ((1LL << 12) - 1));
12272   case MVT::f32:
12273   case MVT::f64:
12274     // Same as ARM mode. FIXME: NEON?
12275     if (!Subtarget->hasVFP2())
12276       return false;
12277     if ((V & 3) != 0)
12278       return false;
12279     V >>= 2;
12280     return V == (V & ((1LL << 8) - 1));
12281   }
12282 }
12283 
12284 /// isLegalAddressImmediate - Return true if the integer value can be used
12285 /// as the offset of the target addressing mode for load / store of the
12286 /// given type.
12287 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12288                                     const ARMSubtarget *Subtarget) {
12289   if (V == 0)
12290     return true;
12291 
12292   if (!VT.isSimple())
12293     return false;
12294 
12295   if (Subtarget->isThumb1Only())
12296     return isLegalT1AddressImmediate(V, VT);
12297   else if (Subtarget->isThumb2())
12298     return isLegalT2AddressImmediate(V, VT, Subtarget);
12299 
12300   // ARM mode.
12301   if (V < 0)
12302     V = - V;
12303   switch (VT.getSimpleVT().SimpleTy) {
12304   default: return false;
12305   case MVT::i1:
12306   case MVT::i8:
12307   case MVT::i32:
12308     // +- imm12
12309     return V == (V & ((1LL << 12) - 1));
12310   case MVT::i16:
12311     // +- imm8
12312     return V == (V & ((1LL << 8) - 1));
12313   case MVT::f32:
12314   case MVT::f64:
12315     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12316       return false;
12317     if ((V & 3) != 0)
12318       return false;
12319     V >>= 2;
12320     return V == (V & ((1LL << 8) - 1));
12321   }
12322 }
12323 
12324 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12325                                                       EVT VT) const {
12326   int Scale = AM.Scale;
12327   if (Scale < 0)
12328     return false;
12329 
12330   switch (VT.getSimpleVT().SimpleTy) {
12331   default: return false;
12332   case MVT::i1:
12333   case MVT::i8:
12334   case MVT::i16:
12335   case MVT::i32:
12336     if (Scale == 1)
12337       return true;
12338     // r + r << imm
12339     Scale = Scale & ~1;
12340     return Scale == 2 || Scale == 4 || Scale == 8;
12341   case MVT::i64:
12342     // r + r
12343     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12344       return true;
12345     return false;
12346   case MVT::isVoid:
12347     // Note, we allow "void" uses (basically, uses that aren't loads or
12348     // stores), because arm allows folding a scale into many arithmetic
12349     // operations.  This should be made more precise and revisited later.
12350 
12351     // Allow r << imm, but the imm has to be a multiple of two.
12352     if (Scale & 1) return false;
12353     return isPowerOf2_32(Scale);
12354   }
12355 }
12356 
12357 /// isLegalAddressingMode - Return true if the addressing mode represented
12358 /// by AM is legal for this target, for a load/store of the specified type.
12359 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12360                                               const AddrMode &AM, Type *Ty,
12361                                               unsigned AS) const {
12362   EVT VT = getValueType(DL, Ty, true);
12363   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12364     return false;
12365 
12366   // Can never fold addr of global into load/store.
12367   if (AM.BaseGV)
12368     return false;
12369 
12370   switch (AM.Scale) {
12371   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12372     break;
12373   case 1:
12374     if (Subtarget->isThumb1Only())
12375       return false;
12376     LLVM_FALLTHROUGH;
12377   default:
12378     // ARM doesn't support any R+R*scale+imm addr modes.
12379     if (AM.BaseOffs)
12380       return false;
12381 
12382     if (!VT.isSimple())
12383       return false;
12384 
12385     if (Subtarget->isThumb2())
12386       return isLegalT2ScaledAddressingMode(AM, VT);
12387 
12388     int Scale = AM.Scale;
12389     switch (VT.getSimpleVT().SimpleTy) {
12390     default: return false;
12391     case MVT::i1:
12392     case MVT::i8:
12393     case MVT::i32:
12394       if (Scale < 0) Scale = -Scale;
12395       if (Scale == 1)
12396         return true;
12397       // r + r << imm
12398       return isPowerOf2_32(Scale & ~1);
12399     case MVT::i16:
12400     case MVT::i64:
12401       // r + r
12402       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12403         return true;
12404       return false;
12405 
12406     case MVT::isVoid:
12407       // Note, we allow "void" uses (basically, uses that aren't loads or
12408       // stores), because arm allows folding a scale into many arithmetic
12409       // operations.  This should be made more precise and revisited later.
12410 
12411       // Allow r << imm, but the imm has to be a multiple of two.
12412       if (Scale & 1) return false;
12413       return isPowerOf2_32(Scale);
12414     }
12415   }
12416   return true;
12417 }
12418 
12419 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12420 /// icmp immediate, that is the target has icmp instructions which can compare
12421 /// a register against the immediate without having to materialize the
12422 /// immediate into a register.
12423 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12424   // Thumb2 and ARM modes can use cmn for negative immediates.
12425   if (!Subtarget->isThumb())
12426     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12427   if (Subtarget->isThumb2())
12428     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12429   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12430   return Imm >= 0 && Imm <= 255;
12431 }
12432 
12433 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12434 /// *or sub* immediate, that is the target has add or sub instructions which can
12435 /// add a register with the immediate without having to materialize the
12436 /// immediate into a register.
12437 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12438   // Same encoding for add/sub, just flip the sign.
12439   int64_t AbsImm = std::abs(Imm);
12440   if (!Subtarget->isThumb())
12441     return ARM_AM::getSOImmVal(AbsImm) != -1;
12442   if (Subtarget->isThumb2())
12443     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12444   // Thumb1 only has 8-bit unsigned immediate.
12445   return AbsImm >= 0 && AbsImm <= 255;
12446 }
12447 
12448 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12449                                       bool isSEXTLoad, SDValue &Base,
12450                                       SDValue &Offset, bool &isInc,
12451                                       SelectionDAG &DAG) {
12452   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12453     return false;
12454 
12455   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12456     // AddressingMode 3
12457     Base = Ptr->getOperand(0);
12458     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12459       int RHSC = (int)RHS->getZExtValue();
12460       if (RHSC < 0 && RHSC > -256) {
12461         assert(Ptr->getOpcode() == ISD::ADD);
12462         isInc = false;
12463         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12464         return true;
12465       }
12466     }
12467     isInc = (Ptr->getOpcode() == ISD::ADD);
12468     Offset = Ptr->getOperand(1);
12469     return true;
12470   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12471     // AddressingMode 2
12472     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12473       int RHSC = (int)RHS->getZExtValue();
12474       if (RHSC < 0 && RHSC > -0x1000) {
12475         assert(Ptr->getOpcode() == ISD::ADD);
12476         isInc = false;
12477         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12478         Base = Ptr->getOperand(0);
12479         return true;
12480       }
12481     }
12482 
12483     if (Ptr->getOpcode() == ISD::ADD) {
12484       isInc = true;
12485       ARM_AM::ShiftOpc ShOpcVal=
12486         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12487       if (ShOpcVal != ARM_AM::no_shift) {
12488         Base = Ptr->getOperand(1);
12489         Offset = Ptr->getOperand(0);
12490       } else {
12491         Base = Ptr->getOperand(0);
12492         Offset = Ptr->getOperand(1);
12493       }
12494       return true;
12495     }
12496 
12497     isInc = (Ptr->getOpcode() == ISD::ADD);
12498     Base = Ptr->getOperand(0);
12499     Offset = Ptr->getOperand(1);
12500     return true;
12501   }
12502 
12503   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12504   return false;
12505 }
12506 
12507 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12508                                      bool isSEXTLoad, SDValue &Base,
12509                                      SDValue &Offset, bool &isInc,
12510                                      SelectionDAG &DAG) {
12511   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12512     return false;
12513 
12514   Base = Ptr->getOperand(0);
12515   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12516     int RHSC = (int)RHS->getZExtValue();
12517     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12518       assert(Ptr->getOpcode() == ISD::ADD);
12519       isInc = false;
12520       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12521       return true;
12522     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12523       isInc = Ptr->getOpcode() == ISD::ADD;
12524       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12525       return true;
12526     }
12527   }
12528 
12529   return false;
12530 }
12531 
12532 /// getPreIndexedAddressParts - returns true by value, base pointer and
12533 /// offset pointer and addressing mode by reference if the node's address
12534 /// can be legally represented as pre-indexed load / store address.
12535 bool
12536 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12537                                              SDValue &Offset,
12538                                              ISD::MemIndexedMode &AM,
12539                                              SelectionDAG &DAG) const {
12540   if (Subtarget->isThumb1Only())
12541     return false;
12542 
12543   EVT VT;
12544   SDValue Ptr;
12545   bool isSEXTLoad = false;
12546   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12547     Ptr = LD->getBasePtr();
12548     VT  = LD->getMemoryVT();
12549     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12550   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12551     Ptr = ST->getBasePtr();
12552     VT  = ST->getMemoryVT();
12553   } else
12554     return false;
12555 
12556   bool isInc;
12557   bool isLegal = false;
12558   if (Subtarget->isThumb2())
12559     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12560                                        Offset, isInc, DAG);
12561   else
12562     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12563                                         Offset, isInc, DAG);
12564   if (!isLegal)
12565     return false;
12566 
12567   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12568   return true;
12569 }
12570 
12571 /// getPostIndexedAddressParts - returns true by value, base pointer and
12572 /// offset pointer and addressing mode by reference if this node can be
12573 /// combined with a load / store to form a post-indexed load / store.
12574 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12575                                                    SDValue &Base,
12576                                                    SDValue &Offset,
12577                                                    ISD::MemIndexedMode &AM,
12578                                                    SelectionDAG &DAG) const {
12579   EVT VT;
12580   SDValue Ptr;
12581   bool isSEXTLoad = false, isNonExt;
12582   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12583     VT  = LD->getMemoryVT();
12584     Ptr = LD->getBasePtr();
12585     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12586     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12587   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12588     VT  = ST->getMemoryVT();
12589     Ptr = ST->getBasePtr();
12590     isNonExt = !ST->isTruncatingStore();
12591   } else
12592     return false;
12593 
12594   if (Subtarget->isThumb1Only()) {
12595     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12596     // must be non-extending/truncating, i32, with an offset of 4.
12597     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12598     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12599       return false;
12600     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12601     if (!RHS || RHS->getZExtValue() != 4)
12602       return false;
12603 
12604     Offset = Op->getOperand(1);
12605     Base = Op->getOperand(0);
12606     AM = ISD::POST_INC;
12607     return true;
12608   }
12609 
12610   bool isInc;
12611   bool isLegal = false;
12612   if (Subtarget->isThumb2())
12613     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12614                                        isInc, DAG);
12615   else
12616     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12617                                         isInc, DAG);
12618   if (!isLegal)
12619     return false;
12620 
12621   if (Ptr != Base) {
12622     // Swap base ptr and offset to catch more post-index load / store when
12623     // it's legal. In Thumb2 mode, offset must be an immediate.
12624     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12625         !Subtarget->isThumb2())
12626       std::swap(Base, Offset);
12627 
12628     // Post-indexed load / store update the base pointer.
12629     if (Ptr != Base)
12630       return false;
12631   }
12632 
12633   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12634   return true;
12635 }
12636 
12637 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12638                                                       KnownBits &Known,
12639                                                       const APInt &DemandedElts,
12640                                                       const SelectionDAG &DAG,
12641                                                       unsigned Depth) const {
12642   unsigned BitWidth = Known.getBitWidth();
12643   Known.resetAll();
12644   switch (Op.getOpcode()) {
12645   default: break;
12646   case ARMISD::ADDC:
12647   case ARMISD::ADDE:
12648   case ARMISD::SUBC:
12649   case ARMISD::SUBE:
12650     // These nodes' second result is a boolean
12651     if (Op.getResNo() == 0)
12652       break;
12653     Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12654     break;
12655   case ARMISD::CMOV: {
12656     // Bits are known zero/one if known on the LHS and RHS.
12657     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
12658     if (Known.isUnknown())
12659       return;
12660 
12661     KnownBits KnownRHS;
12662     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
12663     Known.Zero &= KnownRHS.Zero;
12664     Known.One  &= KnownRHS.One;
12665     return;
12666   }
12667   case ISD::INTRINSIC_W_CHAIN: {
12668     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12669     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12670     switch (IntID) {
12671     default: return;
12672     case Intrinsic::arm_ldaex:
12673     case Intrinsic::arm_ldrex: {
12674       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12675       unsigned MemBits = VT.getScalarSizeInBits();
12676       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12677       return;
12678     }
12679     }
12680   }
12681   case ARMISD::BFI: {
12682     // Conservatively, we can recurse down the first operand
12683     // and just mask out all affected bits.
12684     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
12685 
12686     // The operand to BFI is already a mask suitable for removing the bits it
12687     // sets.
12688     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
12689     const APInt &Mask = CI->getAPIntValue();
12690     Known.Zero &= Mask;
12691     Known.One &= Mask;
12692     return;
12693   }
12694   }
12695 }
12696 
12697 //===----------------------------------------------------------------------===//
12698 //                           ARM Inline Assembly Support
12699 //===----------------------------------------------------------------------===//
12700 
12701 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12702   // Looking for "rev" which is V6+.
12703   if (!Subtarget->hasV6Ops())
12704     return false;
12705 
12706   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12707   std::string AsmStr = IA->getAsmString();
12708   SmallVector<StringRef, 4> AsmPieces;
12709   SplitString(AsmStr, AsmPieces, ";\n");
12710 
12711   switch (AsmPieces.size()) {
12712   default: return false;
12713   case 1:
12714     AsmStr = AsmPieces[0];
12715     AsmPieces.clear();
12716     SplitString(AsmStr, AsmPieces, " \t,");
12717 
12718     // rev $0, $1
12719     if (AsmPieces.size() == 3 &&
12720         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12721         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12722       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12723       if (Ty && Ty->getBitWidth() == 32)
12724         return IntrinsicLowering::LowerToByteSwap(CI);
12725     }
12726     break;
12727   }
12728 
12729   return false;
12730 }
12731 
12732 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12733   // At this point, we have to lower this constraint to something else, so we
12734   // lower it to an "r" or "w". However, by doing this we will force the result
12735   // to be in register, while the X constraint is much more permissive.
12736   //
12737   // Although we are correct (we are free to emit anything, without
12738   // constraints), we might break use cases that would expect us to be more
12739   // efficient and emit something else.
12740   if (!Subtarget->hasVFP2())
12741     return "r";
12742   if (ConstraintVT.isFloatingPoint())
12743     return "w";
12744   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12745      (ConstraintVT.getSizeInBits() == 64 ||
12746       ConstraintVT.getSizeInBits() == 128))
12747     return "w";
12748 
12749   return "r";
12750 }
12751 
12752 /// getConstraintType - Given a constraint letter, return the type of
12753 /// constraint it is for this target.
12754 ARMTargetLowering::ConstraintType
12755 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12756   if (Constraint.size() == 1) {
12757     switch (Constraint[0]) {
12758     default:  break;
12759     case 'l': return C_RegisterClass;
12760     case 'w': return C_RegisterClass;
12761     case 'h': return C_RegisterClass;
12762     case 'x': return C_RegisterClass;
12763     case 't': return C_RegisterClass;
12764     case 'j': return C_Other; // Constant for movw.
12765       // An address with a single base register. Due to the way we
12766       // currently handle addresses it is the same as an 'r' memory constraint.
12767     case 'Q': return C_Memory;
12768     }
12769   } else if (Constraint.size() == 2) {
12770     switch (Constraint[0]) {
12771     default: break;
12772     // All 'U+' constraints are addresses.
12773     case 'U': return C_Memory;
12774     }
12775   }
12776   return TargetLowering::getConstraintType(Constraint);
12777 }
12778 
12779 /// Examine constraint type and operand type and determine a weight value.
12780 /// This object must already have been set up with the operand type
12781 /// and the current alternative constraint selected.
12782 TargetLowering::ConstraintWeight
12783 ARMTargetLowering::getSingleConstraintMatchWeight(
12784     AsmOperandInfo &info, const char *constraint) const {
12785   ConstraintWeight weight = CW_Invalid;
12786   Value *CallOperandVal = info.CallOperandVal;
12787     // If we don't have a value, we can't do a match,
12788     // but allow it at the lowest weight.
12789   if (!CallOperandVal)
12790     return CW_Default;
12791   Type *type = CallOperandVal->getType();
12792   // Look at the constraint type.
12793   switch (*constraint) {
12794   default:
12795     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12796     break;
12797   case 'l':
12798     if (type->isIntegerTy()) {
12799       if (Subtarget->isThumb())
12800         weight = CW_SpecificReg;
12801       else
12802         weight = CW_Register;
12803     }
12804     break;
12805   case 'w':
12806     if (type->isFloatingPointTy())
12807       weight = CW_Register;
12808     break;
12809   }
12810   return weight;
12811 }
12812 
12813 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12814 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12815     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12816   if (Constraint.size() == 1) {
12817     // GCC ARM Constraint Letters
12818     switch (Constraint[0]) {
12819     case 'l': // Low regs or general regs.
12820       if (Subtarget->isThumb())
12821         return RCPair(0U, &ARM::tGPRRegClass);
12822       return RCPair(0U, &ARM::GPRRegClass);
12823     case 'h': // High regs or no regs.
12824       if (Subtarget->isThumb())
12825         return RCPair(0U, &ARM::hGPRRegClass);
12826       break;
12827     case 'r':
12828       if (Subtarget->isThumb1Only())
12829         return RCPair(0U, &ARM::tGPRRegClass);
12830       return RCPair(0U, &ARM::GPRRegClass);
12831     case 'w':
12832       if (VT == MVT::Other)
12833         break;
12834       if (VT == MVT::f32)
12835         return RCPair(0U, &ARM::SPRRegClass);
12836       if (VT.getSizeInBits() == 64)
12837         return RCPair(0U, &ARM::DPRRegClass);
12838       if (VT.getSizeInBits() == 128)
12839         return RCPair(0U, &ARM::QPRRegClass);
12840       break;
12841     case 'x':
12842       if (VT == MVT::Other)
12843         break;
12844       if (VT == MVT::f32)
12845         return RCPair(0U, &ARM::SPR_8RegClass);
12846       if (VT.getSizeInBits() == 64)
12847         return RCPair(0U, &ARM::DPR_8RegClass);
12848       if (VT.getSizeInBits() == 128)
12849         return RCPair(0U, &ARM::QPR_8RegClass);
12850       break;
12851     case 't':
12852       if (VT == MVT::f32)
12853         return RCPair(0U, &ARM::SPRRegClass);
12854       break;
12855     }
12856   }
12857   if (StringRef("{cc}").equals_lower(Constraint))
12858     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12859 
12860   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12861 }
12862 
12863 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12864 /// vector.  If it is invalid, don't add anything to Ops.
12865 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12866                                                      std::string &Constraint,
12867                                                      std::vector<SDValue>&Ops,
12868                                                      SelectionDAG &DAG) const {
12869   SDValue Result;
12870 
12871   // Currently only support length 1 constraints.
12872   if (Constraint.length() != 1) return;
12873 
12874   char ConstraintLetter = Constraint[0];
12875   switch (ConstraintLetter) {
12876   default: break;
12877   case 'j':
12878   case 'I': case 'J': case 'K': case 'L':
12879   case 'M': case 'N': case 'O':
12880     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12881     if (!C)
12882       return;
12883 
12884     int64_t CVal64 = C->getSExtValue();
12885     int CVal = (int) CVal64;
12886     // None of these constraints allow values larger than 32 bits.  Check
12887     // that the value fits in an int.
12888     if (CVal != CVal64)
12889       return;
12890 
12891     switch (ConstraintLetter) {
12892       case 'j':
12893         // Constant suitable for movw, must be between 0 and
12894         // 65535.
12895         if (Subtarget->hasV6T2Ops())
12896           if (CVal >= 0 && CVal <= 65535)
12897             break;
12898         return;
12899       case 'I':
12900         if (Subtarget->isThumb1Only()) {
12901           // This must be a constant between 0 and 255, for ADD
12902           // immediates.
12903           if (CVal >= 0 && CVal <= 255)
12904             break;
12905         } else if (Subtarget->isThumb2()) {
12906           // A constant that can be used as an immediate value in a
12907           // data-processing instruction.
12908           if (ARM_AM::getT2SOImmVal(CVal) != -1)
12909             break;
12910         } else {
12911           // A constant that can be used as an immediate value in a
12912           // data-processing instruction.
12913           if (ARM_AM::getSOImmVal(CVal) != -1)
12914             break;
12915         }
12916         return;
12917 
12918       case 'J':
12919         if (Subtarget->isThumb1Only()) {
12920           // This must be a constant between -255 and -1, for negated ADD
12921           // immediates. This can be used in GCC with an "n" modifier that
12922           // prints the negated value, for use with SUB instructions. It is
12923           // not useful otherwise but is implemented for compatibility.
12924           if (CVal >= -255 && CVal <= -1)
12925             break;
12926         } else {
12927           // This must be a constant between -4095 and 4095. It is not clear
12928           // what this constraint is intended for. Implemented for
12929           // compatibility with GCC.
12930           if (CVal >= -4095 && CVal <= 4095)
12931             break;
12932         }
12933         return;
12934 
12935       case 'K':
12936         if (Subtarget->isThumb1Only()) {
12937           // A 32-bit value where only one byte has a nonzero value. Exclude
12938           // zero to match GCC. This constraint is used by GCC internally for
12939           // constants that can be loaded with a move/shift combination.
12940           // It is not useful otherwise but is implemented for compatibility.
12941           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12942             break;
12943         } else if (Subtarget->isThumb2()) {
12944           // A constant whose bitwise inverse can be used as an immediate
12945           // value in a data-processing instruction. This can be used in GCC
12946           // with a "B" modifier that prints the inverted value, for use with
12947           // BIC and MVN instructions. It is not useful otherwise but is
12948           // implemented for compatibility.
12949           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12950             break;
12951         } else {
12952           // A constant whose bitwise inverse can be used as an immediate
12953           // value in a data-processing instruction. This can be used in GCC
12954           // with a "B" modifier that prints the inverted value, for use with
12955           // BIC and MVN instructions. It is not useful otherwise but is
12956           // implemented for compatibility.
12957           if (ARM_AM::getSOImmVal(~CVal) != -1)
12958             break;
12959         }
12960         return;
12961 
12962       case 'L':
12963         if (Subtarget->isThumb1Only()) {
12964           // This must be a constant between -7 and 7,
12965           // for 3-operand ADD/SUB immediate instructions.
12966           if (CVal >= -7 && CVal < 7)
12967             break;
12968         } else if (Subtarget->isThumb2()) {
12969           // A constant whose negation can be used as an immediate value in a
12970           // data-processing instruction. This can be used in GCC with an "n"
12971           // modifier that prints the negated value, for use with SUB
12972           // instructions. It is not useful otherwise but is implemented for
12973           // compatibility.
12974           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12975             break;
12976         } else {
12977           // A constant whose negation can be used as an immediate value in a
12978           // data-processing instruction. This can be used in GCC with an "n"
12979           // modifier that prints the negated value, for use with SUB
12980           // instructions. It is not useful otherwise but is implemented for
12981           // compatibility.
12982           if (ARM_AM::getSOImmVal(-CVal) != -1)
12983             break;
12984         }
12985         return;
12986 
12987       case 'M':
12988         if (Subtarget->isThumb1Only()) {
12989           // This must be a multiple of 4 between 0 and 1020, for
12990           // ADD sp + immediate.
12991           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12992             break;
12993         } else {
12994           // A power of two or a constant between 0 and 32.  This is used in
12995           // GCC for the shift amount on shifted register operands, but it is
12996           // useful in general for any shift amounts.
12997           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12998             break;
12999         }
13000         return;
13001 
13002       case 'N':
13003         if (Subtarget->isThumb()) {  // FIXME thumb2
13004           // This must be a constant between 0 and 31, for shift amounts.
13005           if (CVal >= 0 && CVal <= 31)
13006             break;
13007         }
13008         return;
13009 
13010       case 'O':
13011         if (Subtarget->isThumb()) {  // FIXME thumb2
13012           // This must be a multiple of 4 between -508 and 508, for
13013           // ADD/SUB sp = sp + immediate.
13014           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13015             break;
13016         }
13017         return;
13018     }
13019     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13020     break;
13021   }
13022 
13023   if (Result.getNode()) {
13024     Ops.push_back(Result);
13025     return;
13026   }
13027   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13028 }
13029 
13030 static RTLIB::Libcall getDivRemLibcall(
13031     const SDNode *N, MVT::SimpleValueType SVT) {
13032   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13033           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13034          "Unhandled Opcode in getDivRemLibcall");
13035   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13036                   N->getOpcode() == ISD::SREM;
13037   RTLIB::Libcall LC;
13038   switch (SVT) {
13039   default: llvm_unreachable("Unexpected request for libcall!");
13040   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13041   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13042   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13043   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13044   }
13045   return LC;
13046 }
13047 
13048 static TargetLowering::ArgListTy getDivRemArgList(
13049     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13050   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13051           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13052          "Unhandled Opcode in getDivRemArgList");
13053   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13054                   N->getOpcode() == ISD::SREM;
13055   TargetLowering::ArgListTy Args;
13056   TargetLowering::ArgListEntry Entry;
13057   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13058     EVT ArgVT = N->getOperand(i).getValueType();
13059     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13060     Entry.Node = N->getOperand(i);
13061     Entry.Ty = ArgTy;
13062     Entry.IsSExt = isSigned;
13063     Entry.IsZExt = !isSigned;
13064     Args.push_back(Entry);
13065   }
13066   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13067     std::swap(Args[0], Args[1]);
13068   return Args;
13069 }
13070 
13071 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13072   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13073           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13074           Subtarget->isTargetWindows()) &&
13075          "Register-based DivRem lowering only");
13076   unsigned Opcode = Op->getOpcode();
13077   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13078          "Invalid opcode for Div/Rem lowering");
13079   bool isSigned = (Opcode == ISD::SDIVREM);
13080   EVT VT = Op->getValueType(0);
13081   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13082   SDLoc dl(Op);
13083 
13084   // If the target has hardware divide, use divide + multiply + subtract:
13085   //     div = a / b
13086   //     rem = a - b * div
13087   //     return {div, rem}
13088   // This should be lowered into UDIV/SDIV + MLS later on.
13089   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13090                                         : Subtarget->hasDivideInARMMode();
13091   if (hasDivide && Op->getValueType(0).isSimple() &&
13092       Op->getSimpleValueType(0) == MVT::i32) {
13093     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13094     const SDValue Dividend = Op->getOperand(0);
13095     const SDValue Divisor = Op->getOperand(1);
13096     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13097     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13098     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13099 
13100     SDValue Values[2] = {Div, Rem};
13101     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13102   }
13103 
13104   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13105                                        VT.getSimpleVT().SimpleTy);
13106   SDValue InChain = DAG.getEntryNode();
13107 
13108   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13109                                                     DAG.getContext(),
13110                                                     Subtarget);
13111 
13112   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13113                                          getPointerTy(DAG.getDataLayout()));
13114 
13115   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
13116 
13117   if (Subtarget->isTargetWindows())
13118     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13119 
13120   TargetLowering::CallLoweringInfo CLI(DAG);
13121   CLI.setDebugLoc(dl).setChain(InChain)
13122     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13123     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13124 
13125   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13126   return CallInfo.first;
13127 }
13128 
13129 // Lowers REM using divmod helpers
13130 // see RTABI section 4.2/4.3
13131 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13132   // Build return types (div and rem)
13133   std::vector<Type*> RetTyParams;
13134   Type *RetTyElement;
13135 
13136   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13137   default: llvm_unreachable("Unexpected request for libcall!");
13138   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13139   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13140   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13141   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13142   }
13143 
13144   RetTyParams.push_back(RetTyElement);
13145   RetTyParams.push_back(RetTyElement);
13146   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13147   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13148 
13149   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13150                                                              SimpleTy);
13151   SDValue InChain = DAG.getEntryNode();
13152   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13153                                                     Subtarget);
13154   bool isSigned = N->getOpcode() == ISD::SREM;
13155   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13156                                          getPointerTy(DAG.getDataLayout()));
13157 
13158   if (Subtarget->isTargetWindows())
13159     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13160 
13161   // Lower call
13162   CallLoweringInfo CLI(DAG);
13163   CLI.setChain(InChain)
13164      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13165      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13166   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13167 
13168   // Return second (rem) result operand (first contains div)
13169   SDNode *ResNode = CallResult.first.getNode();
13170   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13171   return ResNode->getOperand(1);
13172 }
13173 
13174 SDValue
13175 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13176   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13177   SDLoc DL(Op);
13178 
13179   // Get the inputs.
13180   SDValue Chain = Op.getOperand(0);
13181   SDValue Size  = Op.getOperand(1);
13182 
13183   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13184                               DAG.getConstant(2, DL, MVT::i32));
13185 
13186   SDValue Flag;
13187   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13188   Flag = Chain.getValue(1);
13189 
13190   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13191   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13192 
13193   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13194   Chain = NewSP.getValue(1);
13195 
13196   SDValue Ops[2] = { NewSP, Chain };
13197   return DAG.getMergeValues(Ops, DL);
13198 }
13199 
13200 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13201   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13202          "Unexpected type for custom-lowering FP_EXTEND");
13203 
13204   RTLIB::Libcall LC;
13205   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13206 
13207   SDValue SrcVal = Op.getOperand(0);
13208   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13209                      SDLoc(Op)).first;
13210 }
13211 
13212 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13213   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13214          Subtarget->isFPOnlySP() &&
13215          "Unexpected type for custom-lowering FP_ROUND");
13216 
13217   RTLIB::Libcall LC;
13218   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13219 
13220   SDValue SrcVal = Op.getOperand(0);
13221   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13222                      SDLoc(Op)).first;
13223 }
13224 
13225 bool
13226 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13227   // The ARM target isn't yet aware of offsets.
13228   return false;
13229 }
13230 
13231 bool ARM::isBitFieldInvertedMask(unsigned v) {
13232   if (v == 0xffffffff)
13233     return false;
13234 
13235   // there can be 1's on either or both "outsides", all the "inside"
13236   // bits must be 0's
13237   return isShiftedMask_32(~v);
13238 }
13239 
13240 /// isFPImmLegal - Returns true if the target can instruction select the
13241 /// specified FP immediate natively. If false, the legalizer will
13242 /// materialize the FP immediate as a load from a constant pool.
13243 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13244   if (!Subtarget->hasVFP3())
13245     return false;
13246   if (VT == MVT::f32)
13247     return ARM_AM::getFP32Imm(Imm) != -1;
13248   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13249     return ARM_AM::getFP64Imm(Imm) != -1;
13250   return false;
13251 }
13252 
13253 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13254 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13255 /// specified in the intrinsic calls.
13256 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13257                                            const CallInst &I,
13258                                            unsigned Intrinsic) const {
13259   switch (Intrinsic) {
13260   case Intrinsic::arm_neon_vld1:
13261   case Intrinsic::arm_neon_vld2:
13262   case Intrinsic::arm_neon_vld3:
13263   case Intrinsic::arm_neon_vld4:
13264   case Intrinsic::arm_neon_vld2lane:
13265   case Intrinsic::arm_neon_vld3lane:
13266   case Intrinsic::arm_neon_vld4lane: {
13267     Info.opc = ISD::INTRINSIC_W_CHAIN;
13268     // Conservatively set memVT to the entire set of vectors loaded.
13269     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13270     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13271     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13272     Info.ptrVal = I.getArgOperand(0);
13273     Info.offset = 0;
13274     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13275     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13276     Info.vol = false; // volatile loads with NEON intrinsics not supported
13277     Info.readMem = true;
13278     Info.writeMem = false;
13279     return true;
13280   }
13281   case Intrinsic::arm_neon_vst1:
13282   case Intrinsic::arm_neon_vst2:
13283   case Intrinsic::arm_neon_vst3:
13284   case Intrinsic::arm_neon_vst4:
13285   case Intrinsic::arm_neon_vst2lane:
13286   case Intrinsic::arm_neon_vst3lane:
13287   case Intrinsic::arm_neon_vst4lane: {
13288     Info.opc = ISD::INTRINSIC_VOID;
13289     // Conservatively set memVT to the entire set of vectors stored.
13290     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13291     unsigned NumElts = 0;
13292     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13293       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13294       if (!ArgTy->isVectorTy())
13295         break;
13296       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13297     }
13298     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13299     Info.ptrVal = I.getArgOperand(0);
13300     Info.offset = 0;
13301     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13302     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13303     Info.vol = false; // volatile stores with NEON intrinsics not supported
13304     Info.readMem = false;
13305     Info.writeMem = true;
13306     return true;
13307   }
13308   case Intrinsic::arm_ldaex:
13309   case Intrinsic::arm_ldrex: {
13310     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13311     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13312     Info.opc = ISD::INTRINSIC_W_CHAIN;
13313     Info.memVT = MVT::getVT(PtrTy->getElementType());
13314     Info.ptrVal = I.getArgOperand(0);
13315     Info.offset = 0;
13316     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13317     Info.vol = true;
13318     Info.readMem = true;
13319     Info.writeMem = false;
13320     return true;
13321   }
13322   case Intrinsic::arm_stlex:
13323   case Intrinsic::arm_strex: {
13324     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13325     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13326     Info.opc = ISD::INTRINSIC_W_CHAIN;
13327     Info.memVT = MVT::getVT(PtrTy->getElementType());
13328     Info.ptrVal = I.getArgOperand(1);
13329     Info.offset = 0;
13330     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13331     Info.vol = true;
13332     Info.readMem = false;
13333     Info.writeMem = true;
13334     return true;
13335   }
13336   case Intrinsic::arm_stlexd:
13337   case Intrinsic::arm_strexd:
13338     Info.opc = ISD::INTRINSIC_W_CHAIN;
13339     Info.memVT = MVT::i64;
13340     Info.ptrVal = I.getArgOperand(2);
13341     Info.offset = 0;
13342     Info.align = 8;
13343     Info.vol = true;
13344     Info.readMem = false;
13345     Info.writeMem = true;
13346     return true;
13347 
13348   case Intrinsic::arm_ldaexd:
13349   case Intrinsic::arm_ldrexd:
13350     Info.opc = ISD::INTRINSIC_W_CHAIN;
13351     Info.memVT = MVT::i64;
13352     Info.ptrVal = I.getArgOperand(0);
13353     Info.offset = 0;
13354     Info.align = 8;
13355     Info.vol = true;
13356     Info.readMem = true;
13357     Info.writeMem = false;
13358     return true;
13359 
13360   default:
13361     break;
13362   }
13363 
13364   return false;
13365 }
13366 
13367 /// \brief Returns true if it is beneficial to convert a load of a constant
13368 /// to just the constant itself.
13369 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13370                                                           Type *Ty) const {
13371   assert(Ty->isIntegerTy());
13372 
13373   unsigned Bits = Ty->getPrimitiveSizeInBits();
13374   if (Bits == 0 || Bits > 32)
13375     return false;
13376   return true;
13377 }
13378 
13379 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT,
13380                                                 unsigned Index) const {
13381   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13382     return false;
13383 
13384   return (Index == 0 || Index == ResVT.getVectorNumElements());
13385 }
13386 
13387 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13388                                         ARM_MB::MemBOpt Domain) const {
13389   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13390 
13391   // First, if the target has no DMB, see what fallback we can use.
13392   if (!Subtarget->hasDataBarrier()) {
13393     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13394     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13395     // here.
13396     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13397       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13398       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13399                         Builder.getInt32(0), Builder.getInt32(7),
13400                         Builder.getInt32(10), Builder.getInt32(5)};
13401       return Builder.CreateCall(MCR, args);
13402     } else {
13403       // Instead of using barriers, atomic accesses on these subtargets use
13404       // libcalls.
13405       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13406     }
13407   } else {
13408     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13409     // Only a full system barrier exists in the M-class architectures.
13410     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13411     Constant *CDomain = Builder.getInt32(Domain);
13412     return Builder.CreateCall(DMB, CDomain);
13413   }
13414 }
13415 
13416 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13417 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13418                                          AtomicOrdering Ord, bool IsStore,
13419                                          bool IsLoad) const {
13420   switch (Ord) {
13421   case AtomicOrdering::NotAtomic:
13422   case AtomicOrdering::Unordered:
13423     llvm_unreachable("Invalid fence: unordered/non-atomic");
13424   case AtomicOrdering::Monotonic:
13425   case AtomicOrdering::Acquire:
13426     return nullptr; // Nothing to do
13427   case AtomicOrdering::SequentiallyConsistent:
13428     if (!IsStore)
13429       return nullptr; // Nothing to do
13430     /*FALLTHROUGH*/
13431   case AtomicOrdering::Release:
13432   case AtomicOrdering::AcquireRelease:
13433     if (Subtarget->preferISHSTBarriers())
13434       return makeDMB(Builder, ARM_MB::ISHST);
13435     // FIXME: add a comment with a link to documentation justifying this.
13436     else
13437       return makeDMB(Builder, ARM_MB::ISH);
13438   }
13439   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13440 }
13441 
13442 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13443                                           AtomicOrdering Ord, bool IsStore,
13444                                           bool IsLoad) const {
13445   switch (Ord) {
13446   case AtomicOrdering::NotAtomic:
13447   case AtomicOrdering::Unordered:
13448     llvm_unreachable("Invalid fence: unordered/not-atomic");
13449   case AtomicOrdering::Monotonic:
13450   case AtomicOrdering::Release:
13451     return nullptr; // Nothing to do
13452   case AtomicOrdering::Acquire:
13453   case AtomicOrdering::AcquireRelease:
13454   case AtomicOrdering::SequentiallyConsistent:
13455     return makeDMB(Builder, ARM_MB::ISH);
13456   }
13457   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13458 }
13459 
13460 // Loads and stores less than 64-bits are already atomic; ones above that
13461 // are doomed anyway, so defer to the default libcall and blame the OS when
13462 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13463 // anything for those.
13464 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13465   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13466   return (Size == 64) && !Subtarget->isMClass();
13467 }
13468 
13469 // Loads and stores less than 64-bits are already atomic; ones above that
13470 // are doomed anyway, so defer to the default libcall and blame the OS when
13471 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13472 // anything for those.
13473 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13474 // guarantee, see DDI0406C ARM architecture reference manual,
13475 // sections A8.8.72-74 LDRD)
13476 TargetLowering::AtomicExpansionKind
13477 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13478   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13479   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13480                                                   : AtomicExpansionKind::None;
13481 }
13482 
13483 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13484 // and up to 64 bits on the non-M profiles
13485 TargetLowering::AtomicExpansionKind
13486 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13487   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13488   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13489   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13490              ? AtomicExpansionKind::LLSC
13491              : AtomicExpansionKind::None;
13492 }
13493 
13494 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13495     AtomicCmpXchgInst *AI) const {
13496   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13497   // implement cmpxchg without spilling. If the address being exchanged is also
13498   // on the stack and close enough to the spill slot, this can lead to a
13499   // situation where the monitor always gets cleared and the atomic operation
13500   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13501   bool hasAtomicCmpXchg =
13502       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13503   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13504 }
13505 
13506 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13507     const Instruction *I) const {
13508   return InsertFencesForAtomic;
13509 }
13510 
13511 // This has so far only been implemented for MachO.
13512 bool ARMTargetLowering::useLoadStackGuardNode() const {
13513   return Subtarget->isTargetMachO();
13514 }
13515 
13516 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13517                                                   unsigned &Cost) const {
13518   // If we do not have NEON, vector types are not natively supported.
13519   if (!Subtarget->hasNEON())
13520     return false;
13521 
13522   // Floating point values and vector values map to the same register file.
13523   // Therefore, although we could do a store extract of a vector type, this is
13524   // better to leave at float as we have more freedom in the addressing mode for
13525   // those.
13526   if (VectorTy->isFPOrFPVectorTy())
13527     return false;
13528 
13529   // If the index is unknown at compile time, this is very expensive to lower
13530   // and it is not possible to combine the store with the extract.
13531   if (!isa<ConstantInt>(Idx))
13532     return false;
13533 
13534   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13535   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13536   // We can do a store + vector extract on any vector that fits perfectly in a D
13537   // or Q register.
13538   if (BitWidth == 64 || BitWidth == 128) {
13539     Cost = 0;
13540     return true;
13541   }
13542   return false;
13543 }
13544 
13545 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13546   return Subtarget->hasV6T2Ops();
13547 }
13548 
13549 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13550   return Subtarget->hasV6T2Ops();
13551 }
13552 
13553 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13554                                          AtomicOrdering Ord) const {
13555   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13556   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13557   bool IsAcquire = isAcquireOrStronger(Ord);
13558 
13559   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13560   // intrinsic must return {i32, i32} and we have to recombine them into a
13561   // single i64 here.
13562   if (ValTy->getPrimitiveSizeInBits() == 64) {
13563     Intrinsic::ID Int =
13564         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13565     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13566 
13567     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13568     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13569 
13570     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13571     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13572     if (!Subtarget->isLittle())
13573       std::swap (Lo, Hi);
13574     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13575     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13576     return Builder.CreateOr(
13577         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13578   }
13579 
13580   Type *Tys[] = { Addr->getType() };
13581   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13582   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13583 
13584   return Builder.CreateTruncOrBitCast(
13585       Builder.CreateCall(Ldrex, Addr),
13586       cast<PointerType>(Addr->getType())->getElementType());
13587 }
13588 
13589 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13590     IRBuilder<> &Builder) const {
13591   if (!Subtarget->hasV7Ops())
13592     return;
13593   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13594   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13595 }
13596 
13597 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13598                                                Value *Addr,
13599                                                AtomicOrdering Ord) const {
13600   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13601   bool IsRelease = isReleaseOrStronger(Ord);
13602 
13603   // Since the intrinsics must have legal type, the i64 intrinsics take two
13604   // parameters: "i32, i32". We must marshal Val into the appropriate form
13605   // before the call.
13606   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13607     Intrinsic::ID Int =
13608         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13609     Function *Strex = Intrinsic::getDeclaration(M, Int);
13610     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13611 
13612     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13613     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13614     if (!Subtarget->isLittle())
13615       std::swap (Lo, Hi);
13616     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13617     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13618   }
13619 
13620   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13621   Type *Tys[] = { Addr->getType() };
13622   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13623 
13624   return Builder.CreateCall(
13625       Strex, {Builder.CreateZExtOrBitCast(
13626                   Val, Strex->getFunctionType()->getParamType(0)),
13627               Addr});
13628 }
13629 
13630 /// A helper function for determining the number of interleaved accesses we
13631 /// will generate when lowering accesses of the given type.
13632 unsigned
13633 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13634                                              const DataLayout &DL) const {
13635   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13636 }
13637 
13638 bool ARMTargetLowering::isLegalInterleavedAccessType(
13639     VectorType *VecTy, const DataLayout &DL) const {
13640 
13641   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13642   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13643 
13644   // Ensure the vector doesn't have f16 elements. Even though we could do an
13645   // i16 vldN, we can't hold the f16 vectors and will end up converting via
13646   // f32.
13647   if (VecTy->getElementType()->isHalfTy())
13648     return false;
13649 
13650   // Ensure the number of vector elements is greater than 1.
13651   if (VecTy->getNumElements() < 2)
13652     return false;
13653 
13654   // Ensure the element type is legal.
13655   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13656     return false;
13657 
13658   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13659   // 128 will be split into multiple interleaved accesses.
13660   return VecSize == 64 || VecSize % 128 == 0;
13661 }
13662 
13663 /// \brief Lower an interleaved load into a vldN intrinsic.
13664 ///
13665 /// E.g. Lower an interleaved load (Factor = 2):
13666 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13667 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13668 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13669 ///
13670 ///      Into:
13671 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13672 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13673 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13674 bool ARMTargetLowering::lowerInterleavedLoad(
13675     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13676     ArrayRef<unsigned> Indices, unsigned Factor) const {
13677   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13678          "Invalid interleave factor");
13679   assert(!Shuffles.empty() && "Empty shufflevector input");
13680   assert(Shuffles.size() == Indices.size() &&
13681          "Unmatched number of shufflevectors and indices");
13682 
13683   VectorType *VecTy = Shuffles[0]->getType();
13684   Type *EltTy = VecTy->getVectorElementType();
13685 
13686   const DataLayout &DL = LI->getModule()->getDataLayout();
13687 
13688   // Skip if we do not have NEON and skip illegal vector types. We can
13689   // "legalize" wide vector types into multiple interleaved accesses as long as
13690   // the vector types are divisible by 128.
13691   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13692     return false;
13693 
13694   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13695 
13696   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13697   // load integer vectors first and then convert to pointer vectors.
13698   if (EltTy->isPointerTy())
13699     VecTy =
13700         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13701 
13702   IRBuilder<> Builder(LI);
13703 
13704   // The base address of the load.
13705   Value *BaseAddr = LI->getPointerOperand();
13706 
13707   if (NumLoads > 1) {
13708     // If we're going to generate more than one load, reset the sub-vector type
13709     // to something legal.
13710     VecTy = VectorType::get(VecTy->getVectorElementType(),
13711                             VecTy->getVectorNumElements() / NumLoads);
13712 
13713     // We will compute the pointer operand of each load from the original base
13714     // address using GEPs. Cast the base address to a pointer to the scalar
13715     // element type.
13716     BaseAddr = Builder.CreateBitCast(
13717         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13718                       LI->getPointerAddressSpace()));
13719   }
13720 
13721   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13722 
13723   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13724   Type *Tys[] = {VecTy, Int8Ptr};
13725   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13726                                             Intrinsic::arm_neon_vld3,
13727                                             Intrinsic::arm_neon_vld4};
13728   Function *VldnFunc =
13729       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13730 
13731   // Holds sub-vectors extracted from the load intrinsic return values. The
13732   // sub-vectors are associated with the shufflevector instructions they will
13733   // replace.
13734   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13735 
13736   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13737 
13738     // If we're generating more than one load, compute the base address of
13739     // subsequent loads as an offset from the previous.
13740     if (LoadCount > 0)
13741       BaseAddr = Builder.CreateConstGEP1_32(
13742           BaseAddr, VecTy->getVectorNumElements() * Factor);
13743 
13744     SmallVector<Value *, 2> Ops;
13745     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13746     Ops.push_back(Builder.getInt32(LI->getAlignment()));
13747 
13748     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13749 
13750     // Replace uses of each shufflevector with the corresponding vector loaded
13751     // by ldN.
13752     for (unsigned i = 0; i < Shuffles.size(); i++) {
13753       ShuffleVectorInst *SV = Shuffles[i];
13754       unsigned Index = Indices[i];
13755 
13756       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13757 
13758       // Convert the integer vector to pointer vector if the element is pointer.
13759       if (EltTy->isPointerTy())
13760         SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13761 
13762       SubVecs[SV].push_back(SubVec);
13763     }
13764   }
13765 
13766   // Replace uses of the shufflevector instructions with the sub-vectors
13767   // returned by the load intrinsic. If a shufflevector instruction is
13768   // associated with more than one sub-vector, those sub-vectors will be
13769   // concatenated into a single wide vector.
13770   for (ShuffleVectorInst *SVI : Shuffles) {
13771     auto &SubVec = SubVecs[SVI];
13772     auto *WideVec =
13773         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13774     SVI->replaceAllUsesWith(WideVec);
13775   }
13776 
13777   return true;
13778 }
13779 
13780 /// \brief Lower an interleaved store into a vstN intrinsic.
13781 ///
13782 /// E.g. Lower an interleaved store (Factor = 3):
13783 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13784 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13785 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13786 ///
13787 ///      Into:
13788 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13789 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13790 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13791 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13792 ///
13793 /// Note that the new shufflevectors will be removed and we'll only generate one
13794 /// vst3 instruction in CodeGen.
13795 ///
13796 /// Example for a more general valid mask (Factor 3). Lower:
13797 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
13798 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
13799 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
13800 ///
13801 ///      Into:
13802 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
13803 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
13804 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
13805 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13806 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13807                                               ShuffleVectorInst *SVI,
13808                                               unsigned Factor) const {
13809   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13810          "Invalid interleave factor");
13811 
13812   VectorType *VecTy = SVI->getType();
13813   assert(VecTy->getVectorNumElements() % Factor == 0 &&
13814          "Invalid interleaved store");
13815 
13816   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
13817   Type *EltTy = VecTy->getVectorElementType();
13818   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
13819 
13820   const DataLayout &DL = SI->getModule()->getDataLayout();
13821 
13822   // Skip if we do not have NEON and skip illegal vector types. We can
13823   // "legalize" wide vector types into multiple interleaved accesses as long as
13824   // the vector types are divisible by 128.
13825   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
13826     return false;
13827 
13828   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
13829 
13830   Value *Op0 = SVI->getOperand(0);
13831   Value *Op1 = SVI->getOperand(1);
13832   IRBuilder<> Builder(SI);
13833 
13834   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13835   // vectors to integer vectors.
13836   if (EltTy->isPointerTy()) {
13837     Type *IntTy = DL.getIntPtrType(EltTy);
13838 
13839     // Convert to the corresponding integer vector.
13840     Type *IntVecTy =
13841         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13842     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13843     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13844 
13845     SubVecTy = VectorType::get(IntTy, LaneLen);
13846   }
13847 
13848   // The base address of the store.
13849   Value *BaseAddr = SI->getPointerOperand();
13850 
13851   if (NumStores > 1) {
13852     // If we're going to generate more than one store, reset the lane length
13853     // and sub-vector type to something legal.
13854     LaneLen /= NumStores;
13855     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
13856 
13857     // We will compute the pointer operand of each store from the original base
13858     // address using GEPs. Cast the base address to a pointer to the scalar
13859     // element type.
13860     BaseAddr = Builder.CreateBitCast(
13861         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
13862                       SI->getPointerAddressSpace()));
13863   }
13864 
13865   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
13866 
13867   auto Mask = SVI->getShuffleMask();
13868 
13869   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13870   Type *Tys[] = {Int8Ptr, SubVecTy};
13871   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13872                                              Intrinsic::arm_neon_vst3,
13873                                              Intrinsic::arm_neon_vst4};
13874 
13875   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
13876 
13877     // If we generating more than one store, we compute the base address of
13878     // subsequent stores as an offset from the previous.
13879     if (StoreCount > 0)
13880       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
13881 
13882     SmallVector<Value *, 6> Ops;
13883     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13884 
13885     Function *VstNFunc =
13886         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
13887 
13888     // Split the shufflevector operands into sub vectors for the new vstN call.
13889     for (unsigned i = 0; i < Factor; i++) {
13890       unsigned IdxI = StoreCount * LaneLen * Factor + i;
13891       if (Mask[IdxI] >= 0) {
13892         Ops.push_back(Builder.CreateShuffleVector(
13893             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
13894       } else {
13895         unsigned StartMask = 0;
13896         for (unsigned j = 1; j < LaneLen; j++) {
13897           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
13898           if (Mask[IdxJ * Factor + IdxI] >= 0) {
13899             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
13900             break;
13901           }
13902         }
13903         // Note: If all elements in a chunk are undefs, StartMask=0!
13904         // Note: Filling undef gaps with random elements is ok, since
13905         // those elements were being written anyway (with undefs).
13906         // In the case of all undefs we're defaulting to using elems from 0
13907         // Note: StartMask cannot be negative, it's checked in
13908         // isReInterleaveMask
13909         Ops.push_back(Builder.CreateShuffleVector(
13910             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
13911       }
13912     }
13913 
13914     Ops.push_back(Builder.getInt32(SI->getAlignment()));
13915     Builder.CreateCall(VstNFunc, Ops);
13916   }
13917   return true;
13918 }
13919 
13920 enum HABaseType {
13921   HA_UNKNOWN = 0,
13922   HA_FLOAT,
13923   HA_DOUBLE,
13924   HA_VECT64,
13925   HA_VECT128
13926 };
13927 
13928 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13929                                    uint64_t &Members) {
13930   if (auto *ST = dyn_cast<StructType>(Ty)) {
13931     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13932       uint64_t SubMembers = 0;
13933       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13934         return false;
13935       Members += SubMembers;
13936     }
13937   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13938     uint64_t SubMembers = 0;
13939     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13940       return false;
13941     Members += SubMembers * AT->getNumElements();
13942   } else if (Ty->isFloatTy()) {
13943     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13944       return false;
13945     Members = 1;
13946     Base = HA_FLOAT;
13947   } else if (Ty->isDoubleTy()) {
13948     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13949       return false;
13950     Members = 1;
13951     Base = HA_DOUBLE;
13952   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13953     Members = 1;
13954     switch (Base) {
13955     case HA_FLOAT:
13956     case HA_DOUBLE:
13957       return false;
13958     case HA_VECT64:
13959       return VT->getBitWidth() == 64;
13960     case HA_VECT128:
13961       return VT->getBitWidth() == 128;
13962     case HA_UNKNOWN:
13963       switch (VT->getBitWidth()) {
13964       case 64:
13965         Base = HA_VECT64;
13966         return true;
13967       case 128:
13968         Base = HA_VECT128;
13969         return true;
13970       default:
13971         return false;
13972       }
13973     }
13974   }
13975 
13976   return (Members > 0 && Members <= 4);
13977 }
13978 
13979 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13980 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13981 /// passing according to AAPCS rules.
13982 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13983     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13984   if (getEffectiveCallingConv(CallConv, isVarArg) !=
13985       CallingConv::ARM_AAPCS_VFP)
13986     return false;
13987 
13988   HABaseType Base = HA_UNKNOWN;
13989   uint64_t Members = 0;
13990   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13991   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13992 
13993   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13994   return IsHA || IsIntArray;
13995 }
13996 
13997 unsigned ARMTargetLowering::getExceptionPointerRegister(
13998     const Constant *PersonalityFn) const {
13999   // Platforms which do not use SjLj EH may return values in these registers
14000   // via the personality function.
14001   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14002 }
14003 
14004 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14005     const Constant *PersonalityFn) const {
14006   // Platforms which do not use SjLj EH may return values in these registers
14007   // via the personality function.
14008   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14009 }
14010 
14011 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14012   // Update IsSplitCSR in ARMFunctionInfo.
14013   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14014   AFI->setIsSplitCSR(true);
14015 }
14016 
14017 void ARMTargetLowering::insertCopiesSplitCSR(
14018     MachineBasicBlock *Entry,
14019     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14020   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14021   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14022   if (!IStart)
14023     return;
14024 
14025   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14026   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14027   MachineBasicBlock::iterator MBBI = Entry->begin();
14028   for (const MCPhysReg *I = IStart; *I; ++I) {
14029     const TargetRegisterClass *RC = nullptr;
14030     if (ARM::GPRRegClass.contains(*I))
14031       RC = &ARM::GPRRegClass;
14032     else if (ARM::DPRRegClass.contains(*I))
14033       RC = &ARM::DPRRegClass;
14034     else
14035       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14036 
14037     unsigned NewVR = MRI->createVirtualRegister(RC);
14038     // Create copy from CSR to a virtual register.
14039     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14040     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14041     // nounwind. If we want to generalize this later, we may need to emit
14042     // CFI pseudo-instructions.
14043     assert(Entry->getParent()->getFunction()->hasFnAttribute(
14044                Attribute::NoUnwind) &&
14045            "Function should be nounwind in insertCopiesSplitCSR!");
14046     Entry->addLiveIn(*I);
14047     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14048         .addReg(*I);
14049 
14050     // Insert the copy-back instructions right before the terminator.
14051     for (auto *Exit : Exits)
14052       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14053               TII->get(TargetOpcode::COPY), *I)
14054           .addReg(NewVR);
14055   }
14056 }
14057 
14058 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14059   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14060   TargetLoweringBase::finalizeLowering(MF);
14061 }
14062