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 "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "arm-isel"
58 
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62 
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67 
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82 
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87 
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93 
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97 
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127 
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137 
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 
146   if (!VT.isFloatingPoint() &&
147       VT != MVT::v2i64 && VT != MVT::v1i64)
148     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
149       setOperationAction(Opcode, VT, Legal);
150 }
151 
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156 
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161 
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167 
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169 
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       static const struct {
175         const RTLIB::Libcall Op;
176         const char * const Name;
177         const ISD::CondCode Cond;
178       } LibraryCalls[] = {
179         // Single-precision floating-point arithmetic.
180         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184 
185         // Double-precision floating-point arithmetic.
186         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190 
191         // Single-precision comparisons.
192         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200 
201         // Double-precision comparisons.
202         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210 
211         // Floating-point to integer conversions.
212         // i64 conversions are done via library routines even when generating VFP
213         // instructions, so use the same ones.
214         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218 
219         // Conversions between floating types.
220         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222 
223         // Integer to floating-point conversions.
224         // i64 conversions are done via library routines even when generating VFP
225         // instructions, so use the same ones.
226         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227         // e.g., __floatunsidf vs. __floatunssidfvfp.
228         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232       };
233 
234       for (const auto &LC : LibraryCalls) {
235         setLibcallName(LC.Op, LC.Name);
236         if (LC.Cond != ISD::SETCC_INVALID)
237           setCmpLibcallCC(LC.Op, LC.Cond);
238       }
239     }
240 
241     // Set the correct calling convention for ARMv7k WatchOS. It's just
242     // AAPCS_VFP for functions as simple as libcalls.
243     if (Subtarget->isTargetWatchABI()) {
244       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
245         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
246     }
247   }
248 
249   // These libcalls are not available in 32-bit.
250   setLibcallName(RTLIB::SHL_I128, nullptr);
251   setLibcallName(RTLIB::SRL_I128, nullptr);
252   setLibcallName(RTLIB::SRA_I128, nullptr);
253 
254   // RTLIB
255   if (Subtarget->isAAPCS_ABI() &&
256       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
257        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
258     static const struct {
259       const RTLIB::Libcall Op;
260       const char * const Name;
261       const CallingConv::ID CC;
262       const ISD::CondCode Cond;
263     } LibraryCalls[] = {
264       // Double-precision floating-point arithmetic helper functions
265       // RTABI chapter 4.1.2, Table 2
266       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 
271       // Double-precision floating-point comparison helper functions
272       // RTABI chapter 4.1.2, Table 3
273       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
275       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
281 
282       // Single-precision floating-point arithmetic helper functions
283       // RTABI chapter 4.1.2, Table 4
284       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 
289       // Single-precision floating-point comparison helper functions
290       // RTABI chapter 4.1.2, Table 5
291       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
293       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
299 
300       // Floating-point to integer conversions.
301       // RTABI chapter 4.1.2, Table 6
302       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 
311       // Conversions between floating types.
312       // RTABI chapter 4.1.2, Table 7
313       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 
317       // Integer to floating-point conversions.
318       // RTABI chapter 4.1.2, Table 8
319       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 
328       // Long long helper functions
329       // RTABI chapter 4.2, Table 9
330       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 
335       // Integer division functions
336       // RTABI chapter 4.3.1
337       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345     };
346 
347     for (const auto &LC : LibraryCalls) {
348       setLibcallName(LC.Op, LC.Name);
349       setLibcallCallingConv(LC.Op, LC.CC);
350       if (LC.Cond != ISD::SETCC_INVALID)
351         setCmpLibcallCC(LC.Op, LC.Cond);
352     }
353 
354     // EABI dependent RTLIB
355     if (TM.Options.EABIVersion == EABI::EABI4 ||
356         TM.Options.EABIVersion == EABI::EABI5) {
357       static const struct {
358         const RTLIB::Libcall Op;
359         const char *const Name;
360         const CallingConv::ID CC;
361         const ISD::CondCode Cond;
362       } MemOpsLibraryCalls[] = {
363         // Memory operations
364         // RTABI chapter 4.3.4
365         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368       };
369 
370       for (const auto &LC : MemOpsLibraryCalls) {
371         setLibcallName(LC.Op, LC.Name);
372         setLibcallCallingConv(LC.Op, LC.CC);
373         if (LC.Cond != ISD::SETCC_INVALID)
374           setCmpLibcallCC(LC.Op, LC.Cond);
375       }
376     }
377   }
378 
379   if (Subtarget->isTargetWindows()) {
380     static const struct {
381       const RTLIB::Libcall Op;
382       const char * const Name;
383       const CallingConv::ID CC;
384     } LibraryCalls[] = {
385       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
386       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
387       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
388       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
389       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
390       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
391       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
392       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
393     };
394 
395     for (const auto &LC : LibraryCalls) {
396       setLibcallName(LC.Op, LC.Name);
397       setLibcallCallingConv(LC.Op, LC.CC);
398     }
399   }
400 
401   // Use divmod compiler-rt calls for iOS 5.0 and later.
402   if (Subtarget->isTargetWatchOS() ||
403       (Subtarget->isTargetIOS() &&
404        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
405     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
406     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
407   }
408 
409   // The half <-> float conversion functions are always soft-float on
410   // non-watchos platforms, but are needed for some targets which use a
411   // hard-float calling convention by default.
412   if (!Subtarget->isTargetWatchABI()) {
413     if (Subtarget->isAAPCS_ABI()) {
414       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
415       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
416       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
417     } else {
418       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
419       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
420       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
421     }
422   }
423 
424   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
425   // a __gnu_ prefix (which is the default).
426   if (Subtarget->isTargetAEABI()) {
427     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
428     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
429     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
430   }
431 
432   if (Subtarget->isThumb1Only())
433     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
434   else
435     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
436   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
437       !Subtarget->isThumb1Only()) {
438     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
439     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
440   }
441 
442   for (MVT VT : MVT::vector_valuetypes()) {
443     for (MVT InnerVT : MVT::vector_valuetypes()) {
444       setTruncStoreAction(VT, InnerVT, Expand);
445       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
446       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
447       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
448     }
449 
450     setOperationAction(ISD::MULHS, VT, Expand);
451     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
452     setOperationAction(ISD::MULHU, VT, Expand);
453     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
454 
455     setOperationAction(ISD::BSWAP, VT, Expand);
456   }
457 
458   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
459   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
460 
461   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
462   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
463 
464   if (Subtarget->hasNEON()) {
465     addDRTypeForNEON(MVT::v2f32);
466     addDRTypeForNEON(MVT::v8i8);
467     addDRTypeForNEON(MVT::v4i16);
468     addDRTypeForNEON(MVT::v2i32);
469     addDRTypeForNEON(MVT::v1i64);
470 
471     addQRTypeForNEON(MVT::v4f32);
472     addQRTypeForNEON(MVT::v2f64);
473     addQRTypeForNEON(MVT::v16i8);
474     addQRTypeForNEON(MVT::v8i16);
475     addQRTypeForNEON(MVT::v4i32);
476     addQRTypeForNEON(MVT::v2i64);
477 
478     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
479     // neither Neon nor VFP support any arithmetic operations on it.
480     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
481     // supported for v4f32.
482     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
483     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
484     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
485     // FIXME: Code duplication: FDIV and FREM are expanded always, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
488     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
489     // FIXME: Create unittest.
490     // In another words, find a way when "copysign" appears in DAG with vector
491     // operands.
492     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
493     // FIXME: Code duplication: SETCC has custom operation action, see
494     // ARMTargetLowering::addTypeForNEON method for details.
495     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
496     // FIXME: Create unittest for FNEG and for FABS.
497     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
498     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
499     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
500     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
501     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
502     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
503     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
504     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
505     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
506     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
507     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
508     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
509     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
510     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
511     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
512     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
513     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
514     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
515     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
516 
517     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
518     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
520     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
521     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
522     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
523     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
524     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
525     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
526     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
527     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
528     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
529     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
530     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
531     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
532 
533     // Mark v2f32 intrinsics.
534     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
535     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
537     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
538     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
539     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
540     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
541     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
542     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
543     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
544     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
545     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
546     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
547     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
548     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
549 
550     // Neon does not support some operations on v1i64 and v2i64 types.
551     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
552     // Custom handling for some quad-vector types to detect VMULL.
553     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
554     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
555     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
556     // Custom handling for some vector types to avoid expensive expansions
557     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
558     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
559     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
560     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
561     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
562     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
563     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
564     // a destination type that is wider than the source, and nor does
565     // it have a FP_TO_[SU]INT instruction with a narrower destination than
566     // source.
567     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
568     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
569     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
570     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
571 
572     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
573     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
574 
575     // NEON does not have single instruction CTPOP for vectors with element
576     // types wider than 8-bits.  However, custom lowering can leverage the
577     // v8i8/v16i8 vcnt instruction.
578     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
579     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
580     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
583     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
584 
585     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
586     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
587 
588     // NEON does not have single instruction CTTZ for vectors.
589     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
590     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
591     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
592     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
593 
594     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
595     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
596     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
597     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
598 
599     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
600     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
601     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
602     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
603 
604     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
605     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
606     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
607     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
608 
609     // NEON only has FMA instructions as of VFP4.
610     if (!Subtarget->hasVFP4()) {
611       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
612       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
613     }
614 
615     setTargetDAGCombine(ISD::INTRINSIC_VOID);
616     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
617     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
618     setTargetDAGCombine(ISD::SHL);
619     setTargetDAGCombine(ISD::SRL);
620     setTargetDAGCombine(ISD::SRA);
621     setTargetDAGCombine(ISD::SIGN_EXTEND);
622     setTargetDAGCombine(ISD::ZERO_EXTEND);
623     setTargetDAGCombine(ISD::ANY_EXTEND);
624     setTargetDAGCombine(ISD::BUILD_VECTOR);
625     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
626     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
627     setTargetDAGCombine(ISD::STORE);
628     setTargetDAGCombine(ISD::FP_TO_SINT);
629     setTargetDAGCombine(ISD::FP_TO_UINT);
630     setTargetDAGCombine(ISD::FDIV);
631     setTargetDAGCombine(ISD::LOAD);
632 
633     // It is legal to extload from v4i8 to v4i16 or v4i32.
634     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
635                    MVT::v2i32}) {
636       for (MVT VT : MVT::integer_vector_valuetypes()) {
637         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
638         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
639         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
640       }
641     }
642   }
643 
644   // ARM and Thumb2 support UMLAL/SMLAL.
645   if (!Subtarget->isThumb1Only())
646     setTargetDAGCombine(ISD::ADDC);
647 
648   if (Subtarget->isFPOnlySP()) {
649     // When targeting a floating-point unit with only single-precision
650     // operations, f64 is legal for the few double-precision instructions which
651     // are present However, no double-precision operations other than moves,
652     // loads and stores are provided by the hardware.
653     setOperationAction(ISD::FADD,       MVT::f64, Expand);
654     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
655     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
656     setOperationAction(ISD::FMA,        MVT::f64, Expand);
657     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
658     setOperationAction(ISD::FREM,       MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
660     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
661     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
662     setOperationAction(ISD::FABS,       MVT::f64, Expand);
663     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
664     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
665     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
666     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
667     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
668     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
669     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
670     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
671     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
672     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
673     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
674     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
675     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
676     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
677     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
678     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
679     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
680     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
681     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
682     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
683     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
684     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
685     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
686   }
687 
688   computeRegisterProperties(Subtarget->getRegisterInfo());
689 
690   // ARM does not have floating-point extending loads.
691   for (MVT VT : MVT::fp_valuetypes()) {
692     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
693     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
694   }
695 
696   // ... or truncating stores
697   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
698   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
699   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
700 
701   // ARM does not have i1 sign extending load.
702   for (MVT VT : MVT::integer_valuetypes())
703     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
704 
705   // ARM supports all 4 flavors of integer indexed load / store.
706   if (!Subtarget->isThumb1Only()) {
707     for (unsigned im = (unsigned)ISD::PRE_INC;
708          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
709       setIndexedLoadAction(im,  MVT::i1,  Legal);
710       setIndexedLoadAction(im,  MVT::i8,  Legal);
711       setIndexedLoadAction(im,  MVT::i16, Legal);
712       setIndexedLoadAction(im,  MVT::i32, Legal);
713       setIndexedStoreAction(im, MVT::i1,  Legal);
714       setIndexedStoreAction(im, MVT::i8,  Legal);
715       setIndexedStoreAction(im, MVT::i16, Legal);
716       setIndexedStoreAction(im, MVT::i32, Legal);
717     }
718   } else {
719     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
720     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
721     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
722   }
723 
724   setOperationAction(ISD::SADDO, MVT::i32, Custom);
725   setOperationAction(ISD::UADDO, MVT::i32, Custom);
726   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
727   setOperationAction(ISD::USUBO, MVT::i32, Custom);
728 
729   // i64 operation support.
730   setOperationAction(ISD::MUL,     MVT::i64, Expand);
731   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
732   if (Subtarget->isThumb1Only()) {
733     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
734     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
735   }
736   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
737       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
738     setOperationAction(ISD::MULHS, MVT::i32, Expand);
739 
740   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
741   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
742   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
743   setOperationAction(ISD::SRL,       MVT::i64, Custom);
744   setOperationAction(ISD::SRA,       MVT::i64, Custom);
745 
746   if (!Subtarget->isThumb1Only()) {
747     // FIXME: We should do this for Thumb1 as well.
748     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
749     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
750     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
751     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
752   }
753 
754   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
755     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
756 
757   // ARM does not have ROTL.
758   setOperationAction(ISD::ROTL, MVT::i32, Expand);
759   for (MVT VT : MVT::vector_valuetypes()) {
760     setOperationAction(ISD::ROTL, VT, Expand);
761     setOperationAction(ISD::ROTR, VT, Expand);
762   }
763   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
764   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
765   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
766     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
767 
768   // @llvm.readcyclecounter requires the Performance Monitors extension.
769   // Default to the 0 expansion on unsupported platforms.
770   // FIXME: Technically there are older ARM CPUs that have
771   // implementation-specific ways of obtaining this information.
772   if (Subtarget->hasPerfMon())
773     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
774 
775   // Only ARMv6 has BSWAP.
776   if (!Subtarget->hasV6Ops())
777     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
778 
779   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
780                                         : Subtarget->hasDivideInARMMode();
781   if (!hasDivide) {
782     // These are expanded into libcalls if the cpu doesn't have HW divider.
783     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
784     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
785   }
786 
787   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
788     setOperationAction(ISD::SDIV, MVT::i32, Custom);
789     setOperationAction(ISD::UDIV, MVT::i32, Custom);
790 
791     setOperationAction(ISD::SDIV, MVT::i64, Custom);
792     setOperationAction(ISD::UDIV, MVT::i64, Custom);
793   }
794 
795   setOperationAction(ISD::SREM,  MVT::i32, Expand);
796   setOperationAction(ISD::UREM,  MVT::i32, Expand);
797   // Register based DivRem for AEABI (RTABI 4.2)
798   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
799       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) {
800     setOperationAction(ISD::SREM, MVT::i64, Custom);
801     setOperationAction(ISD::UREM, MVT::i64, Custom);
802     HasStandaloneRem = false;
803 
804     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
805     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
806     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
807     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
808     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
809     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
810     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
811     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
812 
813     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
814     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
815     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
816     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
817     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
818     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
819     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
820     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
821 
822     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
823     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
824     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
825     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
826   } else {
827     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
828     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
829   }
830 
831   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
832   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
833   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
834   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
835 
836   setOperationAction(ISD::TRAP, MVT::Other, Legal);
837 
838   // Use the default implementation.
839   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
840   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
841   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
842   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
843   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
844   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
845 
846   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
847     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
848   else
849     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
850 
851   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
852   // the default expansion.
853   InsertFencesForAtomic = false;
854   if (Subtarget->hasAnyDataBarrier() &&
855       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
856     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
857     // to ldrex/strex loops already.
858     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
859     if (!Subtarget->isThumb() || !Subtarget->isMClass())
860       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
861 
862     // On v8, we have particularly efficient implementations of atomic fences
863     // if they can be combined with nearby atomic loads and stores.
864     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
865       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
866       InsertFencesForAtomic = true;
867     }
868   } else {
869     // If there's anything we can use as a barrier, go through custom lowering
870     // for ATOMIC_FENCE.
871     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
872                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
873 
874     // Set them all for expansion, which will force libcalls.
875     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
876     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
877     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
878     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
879     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
880     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
881     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
882     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
883     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
884     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
885     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
886     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
887     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
888     // Unordered/Monotonic case.
889     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
890     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
891   }
892 
893   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
894 
895   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
896   if (!Subtarget->hasV6Ops()) {
897     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
898     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
899   }
900   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
901 
902   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
903       !Subtarget->isThumb1Only()) {
904     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
905     // iff target supports vfp2.
906     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
907     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
908   }
909 
910   // We want to custom lower some of our intrinsics.
911   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
912   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
913   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
914   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
915   if (Subtarget->useSjLjEH())
916     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
917 
918   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
919   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
920   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
921   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
922   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
923   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
924   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
925   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
926   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
927 
928   // Thumb-1 cannot currently select ARMISD::SUBE.
929   if (!Subtarget->isThumb1Only())
930     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
931 
932   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
933   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
934   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
935   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
936   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
937 
938   // We don't support sin/cos/fmod/copysign/pow
939   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
940   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
941   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
942   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
943   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
944   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
945   setOperationAction(ISD::FREM,      MVT::f64, Expand);
946   setOperationAction(ISD::FREM,      MVT::f32, Expand);
947   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
948       !Subtarget->isThumb1Only()) {
949     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
950     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
951   }
952   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
953   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
954 
955   if (!Subtarget->hasVFP4()) {
956     setOperationAction(ISD::FMA, MVT::f64, Expand);
957     setOperationAction(ISD::FMA, MVT::f32, Expand);
958   }
959 
960   // Various VFP goodness
961   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
962     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
963     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
964       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
965       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
966     }
967 
968     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
969     if (!Subtarget->hasFP16()) {
970       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
971       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
972     }
973   }
974 
975   // Combine sin / cos into one node or libcall if possible.
976   if (Subtarget->hasSinCos()) {
977     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
978     setLibcallName(RTLIB::SINCOS_F64, "sincos");
979     if (Subtarget->isTargetWatchABI()) {
980       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
981       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
982     }
983     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
984       // For iOS, we don't want to the normal expansion of a libcall to
985       // sincos. We want to issue a libcall to __sincos_stret.
986       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
987       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
988     }
989   }
990 
991   // FP-ARMv8 implements a lot of rounding-like FP operations.
992   if (Subtarget->hasFPARMv8()) {
993     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
994     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
995     setOperationAction(ISD::FROUND, MVT::f32, Legal);
996     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
997     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
998     setOperationAction(ISD::FRINT, MVT::f32, Legal);
999     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1000     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1001     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1002     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1003     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1004     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1005 
1006     if (!Subtarget->isFPOnlySP()) {
1007       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1008       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1009       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1010       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1011       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1012       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1013       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1014       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1015     }
1016   }
1017 
1018   if (Subtarget->hasNEON()) {
1019     // vmin and vmax aren't available in a scalar form, so we use
1020     // a NEON instruction with an undef lane instead.
1021     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1022     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1023     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1024     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1025     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1026     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1027   }
1028 
1029   // We have target-specific dag combine patterns for the following nodes:
1030   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1031   setTargetDAGCombine(ISD::ADD);
1032   setTargetDAGCombine(ISD::SUB);
1033   setTargetDAGCombine(ISD::MUL);
1034   setTargetDAGCombine(ISD::AND);
1035   setTargetDAGCombine(ISD::OR);
1036   setTargetDAGCombine(ISD::XOR);
1037 
1038   if (Subtarget->hasV6Ops())
1039     setTargetDAGCombine(ISD::SRL);
1040 
1041   setStackPointerRegisterToSaveRestore(ARM::SP);
1042 
1043   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1044       !Subtarget->hasVFP2())
1045     setSchedulingPreference(Sched::RegPressure);
1046   else
1047     setSchedulingPreference(Sched::Hybrid);
1048 
1049   //// temporary - rewrite interface to use type
1050   MaxStoresPerMemset = 8;
1051   MaxStoresPerMemsetOptSize = 4;
1052   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1053   MaxStoresPerMemcpyOptSize = 2;
1054   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1055   MaxStoresPerMemmoveOptSize = 2;
1056 
1057   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1058   // are at least 4 bytes aligned.
1059   setMinStackArgumentAlignment(4);
1060 
1061   // Prefer likely predicted branches to selects on out-of-order cores.
1062   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1063 
1064   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1065 }
1066 
1067 bool ARMTargetLowering::useSoftFloat() const {
1068   return Subtarget->useSoftFloat();
1069 }
1070 
1071 // FIXME: It might make sense to define the representative register class as the
1072 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1073 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1074 // SPR's representative would be DPR_VFP2. This should work well if register
1075 // pressure tracking were modified such that a register use would increment the
1076 // pressure of the register class's representative and all of it's super
1077 // classes' representatives transitively. We have not implemented this because
1078 // of the difficulty prior to coalescing of modeling operand register classes
1079 // due to the common occurrence of cross class copies and subregister insertions
1080 // and extractions.
1081 std::pair<const TargetRegisterClass *, uint8_t>
1082 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1083                                            MVT VT) const {
1084   const TargetRegisterClass *RRC = nullptr;
1085   uint8_t Cost = 1;
1086   switch (VT.SimpleTy) {
1087   default:
1088     return TargetLowering::findRepresentativeClass(TRI, VT);
1089   // Use DPR as representative register class for all floating point
1090   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1091   // the cost is 1 for both f32 and f64.
1092   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1093   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1094     RRC = &ARM::DPRRegClass;
1095     // When NEON is used for SP, only half of the register file is available
1096     // because operations that define both SP and DP results will be constrained
1097     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1098     // coalescing by double-counting the SP regs. See the FIXME above.
1099     if (Subtarget->useNEONForSinglePrecisionFP())
1100       Cost = 2;
1101     break;
1102   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1103   case MVT::v4f32: case MVT::v2f64:
1104     RRC = &ARM::DPRRegClass;
1105     Cost = 2;
1106     break;
1107   case MVT::v4i64:
1108     RRC = &ARM::DPRRegClass;
1109     Cost = 4;
1110     break;
1111   case MVT::v8i64:
1112     RRC = &ARM::DPRRegClass;
1113     Cost = 8;
1114     break;
1115   }
1116   return std::make_pair(RRC, Cost);
1117 }
1118 
1119 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1120   switch ((ARMISD::NodeType)Opcode) {
1121   case ARMISD::FIRST_NUMBER:  break;
1122   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1123   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1124   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1125   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1126   case ARMISD::CALL:          return "ARMISD::CALL";
1127   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1128   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1129   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1130   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1131   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1132   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1133   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1134   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1135   case ARMISD::CMP:           return "ARMISD::CMP";
1136   case ARMISD::CMN:           return "ARMISD::CMN";
1137   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1138   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1139   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1140   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1141   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1142 
1143   case ARMISD::CMOV:          return "ARMISD::CMOV";
1144 
1145   case ARMISD::SSAT:          return "ARMISD::SSAT";
1146 
1147   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1148   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1149   case ARMISD::RRX:           return "ARMISD::RRX";
1150 
1151   case ARMISD::ADDC:          return "ARMISD::ADDC";
1152   case ARMISD::ADDE:          return "ARMISD::ADDE";
1153   case ARMISD::SUBC:          return "ARMISD::SUBC";
1154   case ARMISD::SUBE:          return "ARMISD::SUBE";
1155 
1156   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1157   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1158 
1159   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1160   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1161   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1162 
1163   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1164 
1165   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1166 
1167   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1168 
1169   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1170 
1171   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1172 
1173   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1174   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1175 
1176   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1177   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1178   case ARMISD::VCGE:          return "ARMISD::VCGE";
1179   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1180   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1181   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1182   case ARMISD::VCGT:          return "ARMISD::VCGT";
1183   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1184   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1185   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1186   case ARMISD::VTST:          return "ARMISD::VTST";
1187 
1188   case ARMISD::VSHL:          return "ARMISD::VSHL";
1189   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1190   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1191   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1192   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1193   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1194   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1195   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1196   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1197   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1198   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1199   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1200   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1201   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1202   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1203   case ARMISD::VSLI:          return "ARMISD::VSLI";
1204   case ARMISD::VSRI:          return "ARMISD::VSRI";
1205   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1206   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1207   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1208   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1209   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1210   case ARMISD::VDUP:          return "ARMISD::VDUP";
1211   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1212   case ARMISD::VEXT:          return "ARMISD::VEXT";
1213   case ARMISD::VREV64:        return "ARMISD::VREV64";
1214   case ARMISD::VREV32:        return "ARMISD::VREV32";
1215   case ARMISD::VREV16:        return "ARMISD::VREV16";
1216   case ARMISD::VZIP:          return "ARMISD::VZIP";
1217   case ARMISD::VUZP:          return "ARMISD::VUZP";
1218   case ARMISD::VTRN:          return "ARMISD::VTRN";
1219   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1220   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1221   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1222   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1223   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1224   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1225   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1226   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1227   case ARMISD::BFI:           return "ARMISD::BFI";
1228   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1229   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1230   case ARMISD::VBSL:          return "ARMISD::VBSL";
1231   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1232   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1233   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1234   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1235   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1236   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1237   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1238   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1239   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1240   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1241   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1242   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1243   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1244   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1245   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1246   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1247   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1248   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1249   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1250   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1251   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1252   }
1253   return nullptr;
1254 }
1255 
1256 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1257                                           EVT VT) const {
1258   if (!VT.isVector())
1259     return getPointerTy(DL);
1260   return VT.changeVectorElementTypeToInteger();
1261 }
1262 
1263 /// getRegClassFor - Return the register class that should be used for the
1264 /// specified value type.
1265 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1266   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1267   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1268   // load / store 4 to 8 consecutive D registers.
1269   if (Subtarget->hasNEON()) {
1270     if (VT == MVT::v4i64)
1271       return &ARM::QQPRRegClass;
1272     if (VT == MVT::v8i64)
1273       return &ARM::QQQQPRRegClass;
1274   }
1275   return TargetLowering::getRegClassFor(VT);
1276 }
1277 
1278 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1279 // source/dest is aligned and the copy size is large enough. We therefore want
1280 // to align such objects passed to memory intrinsics.
1281 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1282                                                unsigned &PrefAlign) const {
1283   if (!isa<MemIntrinsic>(CI))
1284     return false;
1285   MinSize = 8;
1286   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1287   // cycle faster than 4-byte aligned LDM.
1288   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1289   return true;
1290 }
1291 
1292 // Create a fast isel object.
1293 FastISel *
1294 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1295                                   const TargetLibraryInfo *libInfo) const {
1296   return ARM::createFastISel(funcInfo, libInfo);
1297 }
1298 
1299 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1300   unsigned NumVals = N->getNumValues();
1301   if (!NumVals)
1302     return Sched::RegPressure;
1303 
1304   for (unsigned i = 0; i != NumVals; ++i) {
1305     EVT VT = N->getValueType(i);
1306     if (VT == MVT::Glue || VT == MVT::Other)
1307       continue;
1308     if (VT.isFloatingPoint() || VT.isVector())
1309       return Sched::ILP;
1310   }
1311 
1312   if (!N->isMachineOpcode())
1313     return Sched::RegPressure;
1314 
1315   // Load are scheduled for latency even if there instruction itinerary
1316   // is not available.
1317   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1318   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1319 
1320   if (MCID.getNumDefs() == 0)
1321     return Sched::RegPressure;
1322   if (!Itins->isEmpty() &&
1323       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1324     return Sched::ILP;
1325 
1326   return Sched::RegPressure;
1327 }
1328 
1329 //===----------------------------------------------------------------------===//
1330 // Lowering Code
1331 //===----------------------------------------------------------------------===//
1332 
1333 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1334 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1335   switch (CC) {
1336   default: llvm_unreachable("Unknown condition code!");
1337   case ISD::SETNE:  return ARMCC::NE;
1338   case ISD::SETEQ:  return ARMCC::EQ;
1339   case ISD::SETGT:  return ARMCC::GT;
1340   case ISD::SETGE:  return ARMCC::GE;
1341   case ISD::SETLT:  return ARMCC::LT;
1342   case ISD::SETLE:  return ARMCC::LE;
1343   case ISD::SETUGT: return ARMCC::HI;
1344   case ISD::SETUGE: return ARMCC::HS;
1345   case ISD::SETULT: return ARMCC::LO;
1346   case ISD::SETULE: return ARMCC::LS;
1347   }
1348 }
1349 
1350 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1351 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1352                         ARMCC::CondCodes &CondCode2) {
1353   CondCode2 = ARMCC::AL;
1354   switch (CC) {
1355   default: llvm_unreachable("Unknown FP condition!");
1356   case ISD::SETEQ:
1357   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1358   case ISD::SETGT:
1359   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1360   case ISD::SETGE:
1361   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1362   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1363   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1364   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1365   case ISD::SETO:   CondCode = ARMCC::VC; break;
1366   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1367   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1368   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1369   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1370   case ISD::SETLT:
1371   case ISD::SETULT: CondCode = ARMCC::LT; break;
1372   case ISD::SETLE:
1373   case ISD::SETULE: CondCode = ARMCC::LE; break;
1374   case ISD::SETNE:
1375   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1376   }
1377 }
1378 
1379 //===----------------------------------------------------------------------===//
1380 //                      Calling Convention Implementation
1381 //===----------------------------------------------------------------------===//
1382 
1383 #include "ARMGenCallingConv.inc"
1384 
1385 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1386 /// account presence of floating point hardware and calling convention
1387 /// limitations, such as support for variadic functions.
1388 CallingConv::ID
1389 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1390                                            bool isVarArg) const {
1391   switch (CC) {
1392   default:
1393     llvm_unreachable("Unsupported calling convention");
1394   case CallingConv::ARM_AAPCS:
1395   case CallingConv::ARM_APCS:
1396   case CallingConv::GHC:
1397     return CC;
1398   case CallingConv::PreserveMost:
1399     return CallingConv::PreserveMost;
1400   case CallingConv::ARM_AAPCS_VFP:
1401   case CallingConv::Swift:
1402     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1403   case CallingConv::C:
1404     if (!Subtarget->isAAPCS_ABI())
1405       return CallingConv::ARM_APCS;
1406     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1407              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1408              !isVarArg)
1409       return CallingConv::ARM_AAPCS_VFP;
1410     else
1411       return CallingConv::ARM_AAPCS;
1412   case CallingConv::Fast:
1413   case CallingConv::CXX_FAST_TLS:
1414     if (!Subtarget->isAAPCS_ABI()) {
1415       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1416         return CallingConv::Fast;
1417       return CallingConv::ARM_APCS;
1418     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1419       return CallingConv::ARM_AAPCS_VFP;
1420     else
1421       return CallingConv::ARM_AAPCS;
1422   }
1423 }
1424 
1425 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1426 /// CallingConvention.
1427 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1428                                                  bool Return,
1429                                                  bool isVarArg) const {
1430   switch (getEffectiveCallingConv(CC, isVarArg)) {
1431   default:
1432     llvm_unreachable("Unsupported calling convention");
1433   case CallingConv::ARM_APCS:
1434     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1435   case CallingConv::ARM_AAPCS:
1436     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1437   case CallingConv::ARM_AAPCS_VFP:
1438     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1439   case CallingConv::Fast:
1440     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1441   case CallingConv::GHC:
1442     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1443   case CallingConv::PreserveMost:
1444     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1445   }
1446 }
1447 
1448 /// LowerCallResult - Lower the result values of a call into the
1449 /// appropriate copies out of appropriate physical registers.
1450 SDValue ARMTargetLowering::LowerCallResult(
1451     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1452     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1453     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1454     SDValue ThisVal) const {
1455 
1456   // Assign locations to each value returned by this call.
1457   SmallVector<CCValAssign, 16> RVLocs;
1458   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1459                     *DAG.getContext(), Call);
1460   CCInfo.AnalyzeCallResult(Ins,
1461                            CCAssignFnForNode(CallConv, /* Return*/ true,
1462                                              isVarArg));
1463 
1464   // Copy all of the result registers out of their specified physreg.
1465   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1466     CCValAssign VA = RVLocs[i];
1467 
1468     // Pass 'this' value directly from the argument to return value, to avoid
1469     // reg unit interference
1470     if (i == 0 && isThisReturn) {
1471       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1472              "unexpected return calling convention register assignment");
1473       InVals.push_back(ThisVal);
1474       continue;
1475     }
1476 
1477     SDValue Val;
1478     if (VA.needsCustom()) {
1479       // Handle f64 or half of a v2f64.
1480       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1481                                       InFlag);
1482       Chain = Lo.getValue(1);
1483       InFlag = Lo.getValue(2);
1484       VA = RVLocs[++i]; // skip ahead to next loc
1485       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1486                                       InFlag);
1487       Chain = Hi.getValue(1);
1488       InFlag = Hi.getValue(2);
1489       if (!Subtarget->isLittle())
1490         std::swap (Lo, Hi);
1491       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1492 
1493       if (VA.getLocVT() == MVT::v2f64) {
1494         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1495         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1496                           DAG.getConstant(0, dl, MVT::i32));
1497 
1498         VA = RVLocs[++i]; // skip ahead to next loc
1499         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1500         Chain = Lo.getValue(1);
1501         InFlag = Lo.getValue(2);
1502         VA = RVLocs[++i]; // skip ahead to next loc
1503         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1504         Chain = Hi.getValue(1);
1505         InFlag = Hi.getValue(2);
1506         if (!Subtarget->isLittle())
1507           std::swap (Lo, Hi);
1508         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1509         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1510                           DAG.getConstant(1, dl, MVT::i32));
1511       }
1512     } else {
1513       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1514                                InFlag);
1515       Chain = Val.getValue(1);
1516       InFlag = Val.getValue(2);
1517     }
1518 
1519     switch (VA.getLocInfo()) {
1520     default: llvm_unreachable("Unknown loc info!");
1521     case CCValAssign::Full: break;
1522     case CCValAssign::BCvt:
1523       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1524       break;
1525     }
1526 
1527     InVals.push_back(Val);
1528   }
1529 
1530   return Chain;
1531 }
1532 
1533 /// LowerMemOpCallTo - Store the argument to the stack.
1534 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1535                                             SDValue Arg, const SDLoc &dl,
1536                                             SelectionDAG &DAG,
1537                                             const CCValAssign &VA,
1538                                             ISD::ArgFlagsTy Flags) const {
1539   unsigned LocMemOffset = VA.getLocMemOffset();
1540   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1541   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1542                        StackPtr, PtrOff);
1543   return DAG.getStore(
1544       Chain, dl, Arg, PtrOff,
1545       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1546 }
1547 
1548 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1549                                          SDValue Chain, SDValue &Arg,
1550                                          RegsToPassVector &RegsToPass,
1551                                          CCValAssign &VA, CCValAssign &NextVA,
1552                                          SDValue &StackPtr,
1553                                          SmallVectorImpl<SDValue> &MemOpChains,
1554                                          ISD::ArgFlagsTy Flags) const {
1555 
1556   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1557                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1558   unsigned id = Subtarget->isLittle() ? 0 : 1;
1559   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1560 
1561   if (NextVA.isRegLoc())
1562     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1563   else {
1564     assert(NextVA.isMemLoc());
1565     if (!StackPtr.getNode())
1566       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1567                                     getPointerTy(DAG.getDataLayout()));
1568 
1569     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1570                                            dl, DAG, NextVA,
1571                                            Flags));
1572   }
1573 }
1574 
1575 /// LowerCall - Lowering a call into a callseq_start <-
1576 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1577 /// nodes.
1578 SDValue
1579 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1580                              SmallVectorImpl<SDValue> &InVals) const {
1581   SelectionDAG &DAG                     = CLI.DAG;
1582   SDLoc &dl                             = CLI.DL;
1583   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1584   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1585   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1586   SDValue Chain                         = CLI.Chain;
1587   SDValue Callee                        = CLI.Callee;
1588   bool &isTailCall                      = CLI.IsTailCall;
1589   CallingConv::ID CallConv              = CLI.CallConv;
1590   bool doesNotRet                       = CLI.DoesNotReturn;
1591   bool isVarArg                         = CLI.IsVarArg;
1592 
1593   MachineFunction &MF = DAG.getMachineFunction();
1594   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1595   bool isThisReturn   = false;
1596   bool isSibCall      = false;
1597   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1598 
1599   // Disable tail calls if they're not supported.
1600   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1601     isTailCall = false;
1602 
1603   if (isTailCall) {
1604     // Check if it's really possible to do a tail call.
1605     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1606                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1607                                                    Outs, OutVals, Ins, DAG);
1608     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1609       report_fatal_error("failed to perform tail call elimination on a call "
1610                          "site marked musttail");
1611     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1612     // detected sibcalls.
1613     if (isTailCall) {
1614       ++NumTailCalls;
1615       isSibCall = true;
1616     }
1617   }
1618 
1619   // Analyze operands of the call, assigning locations to each operand.
1620   SmallVector<CCValAssign, 16> ArgLocs;
1621   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1622                     *DAG.getContext(), Call);
1623   CCInfo.AnalyzeCallOperands(Outs,
1624                              CCAssignFnForNode(CallConv, /* Return*/ false,
1625                                                isVarArg));
1626 
1627   // Get a count of how many bytes are to be pushed on the stack.
1628   unsigned NumBytes = CCInfo.getNextStackOffset();
1629 
1630   // For tail calls, memory operands are available in our caller's stack.
1631   if (isSibCall)
1632     NumBytes = 0;
1633 
1634   // Adjust the stack pointer for the new arguments...
1635   // These operations are automatically eliminated by the prolog/epilog pass
1636   if (!isSibCall)
1637     Chain = DAG.getCALLSEQ_START(Chain,
1638                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1639 
1640   SDValue StackPtr =
1641       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1642 
1643   RegsToPassVector RegsToPass;
1644   SmallVector<SDValue, 8> MemOpChains;
1645 
1646   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1647   // of tail call optimization, arguments are handled later.
1648   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1649        i != e;
1650        ++i, ++realArgIdx) {
1651     CCValAssign &VA = ArgLocs[i];
1652     SDValue Arg = OutVals[realArgIdx];
1653     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1654     bool isByVal = Flags.isByVal();
1655 
1656     // Promote the value if needed.
1657     switch (VA.getLocInfo()) {
1658     default: llvm_unreachable("Unknown loc info!");
1659     case CCValAssign::Full: break;
1660     case CCValAssign::SExt:
1661       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1662       break;
1663     case CCValAssign::ZExt:
1664       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1665       break;
1666     case CCValAssign::AExt:
1667       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1668       break;
1669     case CCValAssign::BCvt:
1670       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1671       break;
1672     }
1673 
1674     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1675     if (VA.needsCustom()) {
1676       if (VA.getLocVT() == MVT::v2f64) {
1677         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1678                                   DAG.getConstant(0, dl, MVT::i32));
1679         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1680                                   DAG.getConstant(1, dl, MVT::i32));
1681 
1682         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1683                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1684 
1685         VA = ArgLocs[++i]; // skip ahead to next loc
1686         if (VA.isRegLoc()) {
1687           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1688                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1689         } else {
1690           assert(VA.isMemLoc());
1691 
1692           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1693                                                  dl, DAG, VA, Flags));
1694         }
1695       } else {
1696         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1697                          StackPtr, MemOpChains, Flags);
1698       }
1699     } else if (VA.isRegLoc()) {
1700       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1701         assert(VA.getLocVT() == MVT::i32 &&
1702                "unexpected calling convention register assignment");
1703         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1704                "unexpected use of 'returned'");
1705         isThisReturn = true;
1706       }
1707       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1708     } else if (isByVal) {
1709       assert(VA.isMemLoc());
1710       unsigned offset = 0;
1711 
1712       // True if this byval aggregate will be split between registers
1713       // and memory.
1714       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1715       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1716 
1717       if (CurByValIdx < ByValArgsCount) {
1718 
1719         unsigned RegBegin, RegEnd;
1720         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1721 
1722         EVT PtrVT =
1723             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1724         unsigned int i, j;
1725         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1726           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1727           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1728           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1729                                      MachinePointerInfo(),
1730                                      DAG.InferPtrAlignment(AddArg));
1731           MemOpChains.push_back(Load.getValue(1));
1732           RegsToPass.push_back(std::make_pair(j, Load));
1733         }
1734 
1735         // If parameter size outsides register area, "offset" value
1736         // helps us to calculate stack slot for remained part properly.
1737         offset = RegEnd - RegBegin;
1738 
1739         CCInfo.nextInRegsParam();
1740       }
1741 
1742       if (Flags.getByValSize() > 4*offset) {
1743         auto PtrVT = getPointerTy(DAG.getDataLayout());
1744         unsigned LocMemOffset = VA.getLocMemOffset();
1745         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1746         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1747         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1748         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1749         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1750                                            MVT::i32);
1751         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1752                                             MVT::i32);
1753 
1754         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1755         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1756         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1757                                           Ops));
1758       }
1759     } else if (!isSibCall) {
1760       assert(VA.isMemLoc());
1761 
1762       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1763                                              dl, DAG, VA, Flags));
1764     }
1765   }
1766 
1767   if (!MemOpChains.empty())
1768     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1769 
1770   // Build a sequence of copy-to-reg nodes chained together with token chain
1771   // and flag operands which copy the outgoing args into the appropriate regs.
1772   SDValue InFlag;
1773   // Tail call byval lowering might overwrite argument registers so in case of
1774   // tail call optimization the copies to registers are lowered later.
1775   if (!isTailCall)
1776     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1777       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1778                                RegsToPass[i].second, InFlag);
1779       InFlag = Chain.getValue(1);
1780     }
1781 
1782   // For tail calls lower the arguments to the 'real' stack slot.
1783   if (isTailCall) {
1784     // Force all the incoming stack arguments to be loaded from the stack
1785     // before any new outgoing arguments are stored to the stack, because the
1786     // outgoing stack slots may alias the incoming argument stack slots, and
1787     // the alias isn't otherwise explicit. This is slightly more conservative
1788     // than necessary, because it means that each store effectively depends
1789     // on every argument instead of just those arguments it would clobber.
1790 
1791     // Do not flag preceding copytoreg stuff together with the following stuff.
1792     InFlag = SDValue();
1793     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1794       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1795                                RegsToPass[i].second, InFlag);
1796       InFlag = Chain.getValue(1);
1797     }
1798     InFlag = SDValue();
1799   }
1800 
1801   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1802   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1803   // node so that legalize doesn't hack it.
1804   bool isDirect = false;
1805 
1806   const TargetMachine &TM = getTargetMachine();
1807   const Module *Mod = MF.getFunction()->getParent();
1808   const GlobalValue *GV = nullptr;
1809   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1810     GV = G->getGlobal();
1811   bool isStub =
1812       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1813 
1814   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1815   bool isLocalARMFunc = false;
1816   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1817   auto PtrVt = getPointerTy(DAG.getDataLayout());
1818 
1819   if (Subtarget->genLongCalls()) {
1820     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1821            "long-calls codegen is not position independent!");
1822     // Handle a global address or an external symbol. If it's not one of
1823     // those, the target's already in a register, so we don't need to do
1824     // anything extra.
1825     if (isa<GlobalAddressSDNode>(Callee)) {
1826       // Create a constant pool entry for the callee address
1827       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1828       ARMConstantPoolValue *CPV =
1829         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1830 
1831       // Get the address of the callee into a register
1832       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1833       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1834       Callee = DAG.getLoad(
1835           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1836           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1837     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1838       const char *Sym = S->getSymbol();
1839 
1840       // Create a constant pool entry for the callee address
1841       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1842       ARMConstantPoolValue *CPV =
1843         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1844                                       ARMPCLabelIndex, 0);
1845       // Get the address of the callee into a register
1846       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1847       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1848       Callee = DAG.getLoad(
1849           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1850           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1851     }
1852   } else if (isa<GlobalAddressSDNode>(Callee)) {
1853     // If we're optimizing for minimum size and the function is called three or
1854     // more times in this block, we can improve codesize by calling indirectly
1855     // as BLXr has a 16-bit encoding.
1856     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1857     auto *BB = CLI.CS->getParent();
1858     bool PreferIndirect =
1859         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
1860         std::count_if(GV->user_begin(), GV->user_end(), [&BB](const User *U) {
1861           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
1862         }) > 2;
1863 
1864     if (!PreferIndirect) {
1865       isDirect = true;
1866       bool isDef = GV->isStrongDefinitionForLinker();
1867 
1868       // ARM call to a local ARM function is predicable.
1869       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1870       // tBX takes a register source operand.
1871       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1872         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1873         Callee = DAG.getNode(
1874             ARMISD::WrapperPIC, dl, PtrVt,
1875             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1876         Callee =
1877             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1878                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1879                         /* Alignment = */ 0, MachineMemOperand::MOInvariant);
1880       } else if (Subtarget->isTargetCOFF()) {
1881         assert(Subtarget->isTargetWindows() &&
1882                "Windows is the only supported COFF target");
1883         unsigned TargetFlags = GV->hasDLLImportStorageClass()
1884                                    ? ARMII::MO_DLLIMPORT
1885                                    : ARMII::MO_NO_FLAG;
1886         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
1887                                             TargetFlags);
1888         if (GV->hasDLLImportStorageClass())
1889           Callee =
1890               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1891                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1892                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1893       } else {
1894         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
1895       }
1896     }
1897   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1898     isDirect = true;
1899     // tBX takes a register source operand.
1900     const char *Sym = S->getSymbol();
1901     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1902       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1903       ARMConstantPoolValue *CPV =
1904         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1905                                       ARMPCLabelIndex, 4);
1906       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1907       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1908       Callee = DAG.getLoad(
1909           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1910           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1911       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1912       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1913     } else {
1914       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
1915     }
1916   }
1917 
1918   // FIXME: handle tail calls differently.
1919   unsigned CallOpc;
1920   if (Subtarget->isThumb()) {
1921     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1922       CallOpc = ARMISD::CALL_NOLINK;
1923     else
1924       CallOpc = ARMISD::CALL;
1925   } else {
1926     if (!isDirect && !Subtarget->hasV5TOps())
1927       CallOpc = ARMISD::CALL_NOLINK;
1928     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
1929              // Emit regular call when code size is the priority
1930              !MF.getFunction()->optForMinSize())
1931       // "mov lr, pc; b _foo" to avoid confusing the RSP
1932       CallOpc = ARMISD::CALL_NOLINK;
1933     else
1934       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1935   }
1936 
1937   std::vector<SDValue> Ops;
1938   Ops.push_back(Chain);
1939   Ops.push_back(Callee);
1940 
1941   // Add argument registers to the end of the list so that they are known live
1942   // into the call.
1943   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1944     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1945                                   RegsToPass[i].second.getValueType()));
1946 
1947   // Add a register mask operand representing the call-preserved registers.
1948   if (!isTailCall) {
1949     const uint32_t *Mask;
1950     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1951     if (isThisReturn) {
1952       // For 'this' returns, use the R0-preserving mask if applicable
1953       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1954       if (!Mask) {
1955         // Set isThisReturn to false if the calling convention is not one that
1956         // allows 'returned' to be modeled in this way, so LowerCallResult does
1957         // not try to pass 'this' straight through
1958         isThisReturn = false;
1959         Mask = ARI->getCallPreservedMask(MF, CallConv);
1960       }
1961     } else
1962       Mask = ARI->getCallPreservedMask(MF, CallConv);
1963 
1964     assert(Mask && "Missing call preserved mask for calling convention");
1965     Ops.push_back(DAG.getRegisterMask(Mask));
1966   }
1967 
1968   if (InFlag.getNode())
1969     Ops.push_back(InFlag);
1970 
1971   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1972   if (isTailCall) {
1973     MF.getFrameInfo().setHasTailCall();
1974     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1975   }
1976 
1977   // Returns a chain and a flag for retval copy to use.
1978   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1979   InFlag = Chain.getValue(1);
1980 
1981   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1982                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1983   if (!Ins.empty())
1984     InFlag = Chain.getValue(1);
1985 
1986   // Handle result values, copying them out of physregs into vregs that we
1987   // return.
1988   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1989                          InVals, isThisReturn,
1990                          isThisReturn ? OutVals[0] : SDValue());
1991 }
1992 
1993 /// HandleByVal - Every parameter *after* a byval parameter is passed
1994 /// on the stack.  Remember the next parameter register to allocate,
1995 /// and then confiscate the rest of the parameter registers to insure
1996 /// this.
1997 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1998                                     unsigned Align) const {
1999   assert((State->getCallOrPrologue() == Prologue ||
2000           State->getCallOrPrologue() == Call) &&
2001          "unhandled ParmContext");
2002 
2003   // Byval (as with any stack) slots are always at least 4 byte aligned.
2004   Align = std::max(Align, 4U);
2005 
2006   unsigned Reg = State->AllocateReg(GPRArgRegs);
2007   if (!Reg)
2008     return;
2009 
2010   unsigned AlignInRegs = Align / 4;
2011   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2012   for (unsigned i = 0; i < Waste; ++i)
2013     Reg = State->AllocateReg(GPRArgRegs);
2014 
2015   if (!Reg)
2016     return;
2017 
2018   unsigned Excess = 4 * (ARM::R4 - Reg);
2019 
2020   // Special case when NSAA != SP and parameter size greater than size of
2021   // all remained GPR regs. In that case we can't split parameter, we must
2022   // send it to stack. We also must set NCRN to R4, so waste all
2023   // remained registers.
2024   const unsigned NSAAOffset = State->getNextStackOffset();
2025   if (NSAAOffset != 0 && Size > Excess) {
2026     while (State->AllocateReg(GPRArgRegs))
2027       ;
2028     return;
2029   }
2030 
2031   // First register for byval parameter is the first register that wasn't
2032   // allocated before this method call, so it would be "reg".
2033   // If parameter is small enough to be saved in range [reg, r4), then
2034   // the end (first after last) register would be reg + param-size-in-regs,
2035   // else parameter would be splitted between registers and stack,
2036   // end register would be r4 in this case.
2037   unsigned ByValRegBegin = Reg;
2038   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2039   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2040   // Note, first register is allocated in the beginning of function already,
2041   // allocate remained amount of registers we need.
2042   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2043     State->AllocateReg(GPRArgRegs);
2044   // A byval parameter that is split between registers and memory needs its
2045   // size truncated here.
2046   // In the case where the entire structure fits in registers, we set the
2047   // size in memory to zero.
2048   Size = std::max<int>(Size - Excess, 0);
2049 }
2050 
2051 /// MatchingStackOffset - Return true if the given stack call argument is
2052 /// already available in the same position (relatively) of the caller's
2053 /// incoming argument stack.
2054 static
2055 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2056                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2057                          const TargetInstrInfo *TII) {
2058   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2059   int FI = INT_MAX;
2060   if (Arg.getOpcode() == ISD::CopyFromReg) {
2061     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2062     if (!TargetRegisterInfo::isVirtualRegister(VR))
2063       return false;
2064     MachineInstr *Def = MRI->getVRegDef(VR);
2065     if (!Def)
2066       return false;
2067     if (!Flags.isByVal()) {
2068       if (!TII->isLoadFromStackSlot(*Def, FI))
2069         return false;
2070     } else {
2071       return false;
2072     }
2073   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2074     if (Flags.isByVal())
2075       // ByVal argument is passed in as a pointer but it's now being
2076       // dereferenced. e.g.
2077       // define @foo(%struct.X* %A) {
2078       //   tail call @bar(%struct.X* byval %A)
2079       // }
2080       return false;
2081     SDValue Ptr = Ld->getBasePtr();
2082     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2083     if (!FINode)
2084       return false;
2085     FI = FINode->getIndex();
2086   } else
2087     return false;
2088 
2089   assert(FI != INT_MAX);
2090   if (!MFI.isFixedObjectIndex(FI))
2091     return false;
2092   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2093 }
2094 
2095 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2096 /// for tail call optimization. Targets which want to do tail call
2097 /// optimization should implement this function.
2098 bool
2099 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2100                                                      CallingConv::ID CalleeCC,
2101                                                      bool isVarArg,
2102                                                      bool isCalleeStructRet,
2103                                                      bool isCallerStructRet,
2104                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2105                                     const SmallVectorImpl<SDValue> &OutVals,
2106                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2107                                                      SelectionDAG& DAG) const {
2108   MachineFunction &MF = DAG.getMachineFunction();
2109   const Function *CallerF = MF.getFunction();
2110   CallingConv::ID CallerCC = CallerF->getCallingConv();
2111 
2112   assert(Subtarget->supportsTailCall());
2113 
2114   // Look for obvious safe cases to perform tail call optimization that do not
2115   // require ABI changes. This is what gcc calls sibcall.
2116 
2117   // Do not sibcall optimize vararg calls unless the call site is not passing
2118   // any arguments.
2119   if (isVarArg && !Outs.empty())
2120     return false;
2121 
2122   // Exception-handling functions need a special set of instructions to indicate
2123   // a return to the hardware. Tail-calling another function would probably
2124   // break this.
2125   if (CallerF->hasFnAttribute("interrupt"))
2126     return false;
2127 
2128   // Also avoid sibcall optimization if either caller or callee uses struct
2129   // return semantics.
2130   if (isCalleeStructRet || isCallerStructRet)
2131     return false;
2132 
2133   // Externally-defined functions with weak linkage should not be
2134   // tail-called on ARM when the OS does not support dynamic
2135   // pre-emption of symbols, as the AAELF spec requires normal calls
2136   // to undefined weak functions to be replaced with a NOP or jump to the
2137   // next instruction. The behaviour of branch instructions in this
2138   // situation (as used for tail calls) is implementation-defined, so we
2139   // cannot rely on the linker replacing the tail call with a return.
2140   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2141     const GlobalValue *GV = G->getGlobal();
2142     const Triple &TT = getTargetMachine().getTargetTriple();
2143     if (GV->hasExternalWeakLinkage() &&
2144         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2145       return false;
2146   }
2147 
2148   // Check that the call results are passed in the same way.
2149   LLVMContext &C = *DAG.getContext();
2150   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2151                                   CCAssignFnForNode(CalleeCC, true, isVarArg),
2152                                   CCAssignFnForNode(CallerCC, true, isVarArg)))
2153     return false;
2154   // The callee has to preserve all registers the caller needs to preserve.
2155   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2156   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2157   if (CalleeCC != CallerCC) {
2158     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2159     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2160       return false;
2161   }
2162 
2163   // If Caller's vararg or byval argument has been split between registers and
2164   // stack, do not perform tail call, since part of the argument is in caller's
2165   // local frame.
2166   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2167   if (AFI_Caller->getArgRegsSaveSize())
2168     return false;
2169 
2170   // If the callee takes no arguments then go on to check the results of the
2171   // call.
2172   if (!Outs.empty()) {
2173     // Check if stack adjustment is needed. For now, do not do this if any
2174     // argument is passed on the stack.
2175     SmallVector<CCValAssign, 16> ArgLocs;
2176     ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call);
2177     CCInfo.AnalyzeCallOperands(Outs,
2178                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2179     if (CCInfo.getNextStackOffset()) {
2180       // Check if the arguments are already laid out in the right way as
2181       // the caller's fixed stack objects.
2182       MachineFrameInfo &MFI = MF.getFrameInfo();
2183       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2184       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2185       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2186            i != e;
2187            ++i, ++realArgIdx) {
2188         CCValAssign &VA = ArgLocs[i];
2189         EVT RegVT = VA.getLocVT();
2190         SDValue Arg = OutVals[realArgIdx];
2191         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2192         if (VA.getLocInfo() == CCValAssign::Indirect)
2193           return false;
2194         if (VA.needsCustom()) {
2195           // f64 and vector types are split into multiple registers or
2196           // register/stack-slot combinations.  The types will not match
2197           // the registers; give up on memory f64 refs until we figure
2198           // out what to do about this.
2199           if (!VA.isRegLoc())
2200             return false;
2201           if (!ArgLocs[++i].isRegLoc())
2202             return false;
2203           if (RegVT == MVT::v2f64) {
2204             if (!ArgLocs[++i].isRegLoc())
2205               return false;
2206             if (!ArgLocs[++i].isRegLoc())
2207               return false;
2208           }
2209         } else if (!VA.isRegLoc()) {
2210           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2211                                    MFI, MRI, TII))
2212             return false;
2213         }
2214       }
2215     }
2216 
2217     const MachineRegisterInfo &MRI = MF.getRegInfo();
2218     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2219       return false;
2220   }
2221 
2222   return true;
2223 }
2224 
2225 bool
2226 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2227                                   MachineFunction &MF, bool isVarArg,
2228                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2229                                   LLVMContext &Context) const {
2230   SmallVector<CCValAssign, 16> RVLocs;
2231   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2232   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2233                                                     isVarArg));
2234 }
2235 
2236 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2237                                     const SDLoc &DL, SelectionDAG &DAG) {
2238   const MachineFunction &MF = DAG.getMachineFunction();
2239   const Function *F = MF.getFunction();
2240 
2241   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2242 
2243   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2244   // version of the "preferred return address". These offsets affect the return
2245   // instruction if this is a return from PL1 without hypervisor extensions.
2246   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2247   //    SWI:     0      "subs pc, lr, #0"
2248   //    ABORT:   +4     "subs pc, lr, #4"
2249   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2250   // UNDEF varies depending on where the exception came from ARM or Thumb
2251   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2252 
2253   int64_t LROffset;
2254   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2255       IntKind == "ABORT")
2256     LROffset = 4;
2257   else if (IntKind == "SWI" || IntKind == "UNDEF")
2258     LROffset = 0;
2259   else
2260     report_fatal_error("Unsupported interrupt attribute. If present, value "
2261                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2262 
2263   RetOps.insert(RetOps.begin() + 1,
2264                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2265 
2266   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2267 }
2268 
2269 SDValue
2270 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2271                                bool isVarArg,
2272                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2273                                const SmallVectorImpl<SDValue> &OutVals,
2274                                const SDLoc &dl, SelectionDAG &DAG) const {
2275 
2276   // CCValAssign - represent the assignment of the return value to a location.
2277   SmallVector<CCValAssign, 16> RVLocs;
2278 
2279   // CCState - Info about the registers and stack slots.
2280   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2281                     *DAG.getContext(), Call);
2282 
2283   // Analyze outgoing return values.
2284   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2285                                                isVarArg));
2286 
2287   SDValue Flag;
2288   SmallVector<SDValue, 4> RetOps;
2289   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2290   bool isLittleEndian = Subtarget->isLittle();
2291 
2292   MachineFunction &MF = DAG.getMachineFunction();
2293   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2294   AFI->setReturnRegsCount(RVLocs.size());
2295 
2296   // Copy the result values into the output registers.
2297   for (unsigned i = 0, realRVLocIdx = 0;
2298        i != RVLocs.size();
2299        ++i, ++realRVLocIdx) {
2300     CCValAssign &VA = RVLocs[i];
2301     assert(VA.isRegLoc() && "Can only return in registers!");
2302 
2303     SDValue Arg = OutVals[realRVLocIdx];
2304 
2305     switch (VA.getLocInfo()) {
2306     default: llvm_unreachable("Unknown loc info!");
2307     case CCValAssign::Full: break;
2308     case CCValAssign::BCvt:
2309       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2310       break;
2311     }
2312 
2313     if (VA.needsCustom()) {
2314       if (VA.getLocVT() == MVT::v2f64) {
2315         // Extract the first half and return it in two registers.
2316         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2317                                    DAG.getConstant(0, dl, MVT::i32));
2318         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2319                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2320 
2321         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2322                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2323                                  Flag);
2324         Flag = Chain.getValue(1);
2325         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2326         VA = RVLocs[++i]; // skip ahead to next loc
2327         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2328                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2329                                  Flag);
2330         Flag = Chain.getValue(1);
2331         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2332         VA = RVLocs[++i]; // skip ahead to next loc
2333 
2334         // Extract the 2nd half and fall through to handle it as an f64 value.
2335         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2336                           DAG.getConstant(1, dl, MVT::i32));
2337       }
2338       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2339       // available.
2340       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2341                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2342       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2343                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2344                                Flag);
2345       Flag = Chain.getValue(1);
2346       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2347       VA = RVLocs[++i]; // skip ahead to next loc
2348       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2349                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2350                                Flag);
2351     } else
2352       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2353 
2354     // Guarantee that all emitted copies are
2355     // stuck together, avoiding something bad.
2356     Flag = Chain.getValue(1);
2357     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2358   }
2359   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2360   const MCPhysReg *I =
2361       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2362   if (I) {
2363     for (; *I; ++I) {
2364       if (ARM::GPRRegClass.contains(*I))
2365         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2366       else if (ARM::DPRRegClass.contains(*I))
2367         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2368       else
2369         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2370     }
2371   }
2372 
2373   // Update chain and glue.
2374   RetOps[0] = Chain;
2375   if (Flag.getNode())
2376     RetOps.push_back(Flag);
2377 
2378   // CPUs which aren't M-class use a special sequence to return from
2379   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2380   // though we use "subs pc, lr, #N").
2381   //
2382   // M-class CPUs actually use a normal return sequence with a special
2383   // (hardware-provided) value in LR, so the normal code path works.
2384   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2385       !Subtarget->isMClass()) {
2386     if (Subtarget->isThumb1Only())
2387       report_fatal_error("interrupt attribute is not supported in Thumb1");
2388     return LowerInterruptReturn(RetOps, dl, DAG);
2389   }
2390 
2391   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2392 }
2393 
2394 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2395   if (N->getNumValues() != 1)
2396     return false;
2397   if (!N->hasNUsesOfValue(1, 0))
2398     return false;
2399 
2400   SDValue TCChain = Chain;
2401   SDNode *Copy = *N->use_begin();
2402   if (Copy->getOpcode() == ISD::CopyToReg) {
2403     // If the copy has a glue operand, we conservatively assume it isn't safe to
2404     // perform a tail call.
2405     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2406       return false;
2407     TCChain = Copy->getOperand(0);
2408   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2409     SDNode *VMov = Copy;
2410     // f64 returned in a pair of GPRs.
2411     SmallPtrSet<SDNode*, 2> Copies;
2412     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2413          UI != UE; ++UI) {
2414       if (UI->getOpcode() != ISD::CopyToReg)
2415         return false;
2416       Copies.insert(*UI);
2417     }
2418     if (Copies.size() > 2)
2419       return false;
2420 
2421     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2422          UI != UE; ++UI) {
2423       SDValue UseChain = UI->getOperand(0);
2424       if (Copies.count(UseChain.getNode()))
2425         // Second CopyToReg
2426         Copy = *UI;
2427       else {
2428         // We are at the top of this chain.
2429         // If the copy has a glue operand, we conservatively assume it
2430         // isn't safe to perform a tail call.
2431         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2432           return false;
2433         // First CopyToReg
2434         TCChain = UseChain;
2435       }
2436     }
2437   } else if (Copy->getOpcode() == ISD::BITCAST) {
2438     // f32 returned in a single GPR.
2439     if (!Copy->hasOneUse())
2440       return false;
2441     Copy = *Copy->use_begin();
2442     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2443       return false;
2444     // If the copy has a glue operand, we conservatively assume it isn't safe to
2445     // perform a tail call.
2446     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2447       return false;
2448     TCChain = Copy->getOperand(0);
2449   } else {
2450     return false;
2451   }
2452 
2453   bool HasRet = false;
2454   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2455        UI != UE; ++UI) {
2456     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2457         UI->getOpcode() != ARMISD::INTRET_FLAG)
2458       return false;
2459     HasRet = true;
2460   }
2461 
2462   if (!HasRet)
2463     return false;
2464 
2465   Chain = TCChain;
2466   return true;
2467 }
2468 
2469 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2470   if (!Subtarget->supportsTailCall())
2471     return false;
2472 
2473   auto Attr =
2474       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2475   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2476     return false;
2477 
2478   return true;
2479 }
2480 
2481 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2482 // and pass the lower and high parts through.
2483 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2484   SDLoc DL(Op);
2485   SDValue WriteValue = Op->getOperand(2);
2486 
2487   // This function is only supposed to be called for i64 type argument.
2488   assert(WriteValue.getValueType() == MVT::i64
2489           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2490 
2491   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2492                            DAG.getConstant(0, DL, MVT::i32));
2493   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2494                            DAG.getConstant(1, DL, MVT::i32));
2495   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2496   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2497 }
2498 
2499 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2500 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2501 // one of the above mentioned nodes. It has to be wrapped because otherwise
2502 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2503 // be used to form addressing mode. These wrapped nodes will be selected
2504 // into MOVi.
2505 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2506   EVT PtrVT = Op.getValueType();
2507   // FIXME there is no actual debug info here
2508   SDLoc dl(Op);
2509   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2510   SDValue Res;
2511   if (CP->isMachineConstantPoolEntry())
2512     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2513                                     CP->getAlignment());
2514   else
2515     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2516                                     CP->getAlignment());
2517   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2518 }
2519 
2520 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2521   return MachineJumpTableInfo::EK_Inline;
2522 }
2523 
2524 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2525                                              SelectionDAG &DAG) const {
2526   MachineFunction &MF = DAG.getMachineFunction();
2527   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2528   unsigned ARMPCLabelIndex = 0;
2529   SDLoc DL(Op);
2530   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2531   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2532   SDValue CPAddr;
2533   bool IsPositionIndependent = isPositionIndependent();
2534   if (!IsPositionIndependent) {
2535     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2536   } else {
2537     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2538     ARMPCLabelIndex = AFI->createPICLabelUId();
2539     ARMConstantPoolValue *CPV =
2540       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2541                                       ARMCP::CPBlockAddress, PCAdj);
2542     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2543   }
2544   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2545   SDValue Result = DAG.getLoad(
2546       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2547       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2548   if (!IsPositionIndependent)
2549     return Result;
2550   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2551   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2552 }
2553 
2554 /// \brief Convert a TLS address reference into the correct sequence of loads
2555 /// and calls to compute the variable's address for Darwin, and return an
2556 /// SDValue containing the final node.
2557 
2558 /// Darwin only has one TLS scheme which must be capable of dealing with the
2559 /// fully general situation, in the worst case. This means:
2560 ///     + "extern __thread" declaration.
2561 ///     + Defined in a possibly unknown dynamic library.
2562 ///
2563 /// The general system is that each __thread variable has a [3 x i32] descriptor
2564 /// which contains information used by the runtime to calculate the address. The
2565 /// only part of this the compiler needs to know about is the first word, which
2566 /// contains a function pointer that must be called with the address of the
2567 /// entire descriptor in "r0".
2568 ///
2569 /// Since this descriptor may be in a different unit, in general access must
2570 /// proceed along the usual ARM rules. A common sequence to produce is:
2571 ///
2572 ///     movw rT1, :lower16:_var$non_lazy_ptr
2573 ///     movt rT1, :upper16:_var$non_lazy_ptr
2574 ///     ldr r0, [rT1]
2575 ///     ldr rT2, [r0]
2576 ///     blx rT2
2577 ///     [...address now in r0...]
2578 SDValue
2579 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2580                                                SelectionDAG &DAG) const {
2581   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2582   SDLoc DL(Op);
2583 
2584   // First step is to get the address of the actua global symbol. This is where
2585   // the TLS descriptor lives.
2586   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2587 
2588   // The first entry in the descriptor is a function pointer that we must call
2589   // to obtain the address of the variable.
2590   SDValue Chain = DAG.getEntryNode();
2591   SDValue FuncTLVGet =
2592       DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2593                   MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2594                   /* Alignment = */ 4, MachineMemOperand::MONonTemporal |
2595                                            MachineMemOperand::MOInvariant);
2596   Chain = FuncTLVGet.getValue(1);
2597 
2598   MachineFunction &F = DAG.getMachineFunction();
2599   MachineFrameInfo &MFI = F.getFrameInfo();
2600   MFI.setAdjustsStack(true);
2601 
2602   // TLS calls preserve all registers except those that absolutely must be
2603   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2604   // silly).
2605   auto TRI =
2606       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2607   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2608   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2609 
2610   // Finally, we can make the call. This is just a degenerate version of a
2611   // normal AArch64 call node: r0 takes the address of the descriptor, and
2612   // returns the address of the variable in this thread.
2613   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2614   Chain =
2615       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2616                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2617                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2618   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2619 }
2620 
2621 SDValue
2622 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2623                                                 SelectionDAG &DAG) const {
2624   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2625 
2626   SDValue Chain = DAG.getEntryNode();
2627   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2628   SDLoc DL(Op);
2629 
2630   // Load the current TEB (thread environment block)
2631   SDValue Ops[] = {Chain,
2632                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2633                    DAG.getConstant(15, DL, MVT::i32),
2634                    DAG.getConstant(0, DL, MVT::i32),
2635                    DAG.getConstant(13, DL, MVT::i32),
2636                    DAG.getConstant(0, DL, MVT::i32),
2637                    DAG.getConstant(2, DL, MVT::i32)};
2638   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2639                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2640 
2641   SDValue TEB = CurrentTEB.getValue(0);
2642   Chain = CurrentTEB.getValue(1);
2643 
2644   // Load the ThreadLocalStoragePointer from the TEB
2645   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2646   SDValue TLSArray =
2647       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2648   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2649 
2650   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2651   // offset into the TLSArray.
2652 
2653   // Load the TLS index from the C runtime
2654   SDValue TLSIndex =
2655       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2656   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2657   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2658 
2659   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2660                               DAG.getConstant(2, DL, MVT::i32));
2661   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2662                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2663                             MachinePointerInfo());
2664 
2665   // Get the offset of the start of the .tls section (section base)
2666   const auto *GA = cast<GlobalAddressSDNode>(Op);
2667   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2668   SDValue Offset = DAG.getLoad(
2669       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2670                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2671       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2672 
2673   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2674 }
2675 
2676 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2677 SDValue
2678 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2679                                                  SelectionDAG &DAG) const {
2680   SDLoc dl(GA);
2681   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2682   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2683   MachineFunction &MF = DAG.getMachineFunction();
2684   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2685   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2686   ARMConstantPoolValue *CPV =
2687     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2688                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2689   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2690   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2691   Argument = DAG.getLoad(
2692       PtrVT, dl, DAG.getEntryNode(), Argument,
2693       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2694   SDValue Chain = Argument.getValue(1);
2695 
2696   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2697   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2698 
2699   // call __tls_get_addr.
2700   ArgListTy Args;
2701   ArgListEntry Entry;
2702   Entry.Node = Argument;
2703   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2704   Args.push_back(Entry);
2705 
2706   // FIXME: is there useful debug info available here?
2707   TargetLowering::CallLoweringInfo CLI(DAG);
2708   CLI.setDebugLoc(dl).setChain(Chain)
2709     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2710                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2711 
2712   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2713   return CallResult.first;
2714 }
2715 
2716 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2717 // "local exec" model.
2718 SDValue
2719 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2720                                         SelectionDAG &DAG,
2721                                         TLSModel::Model model) const {
2722   const GlobalValue *GV = GA->getGlobal();
2723   SDLoc dl(GA);
2724   SDValue Offset;
2725   SDValue Chain = DAG.getEntryNode();
2726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727   // Get the Thread Pointer
2728   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2729 
2730   if (model == TLSModel::InitialExec) {
2731     MachineFunction &MF = DAG.getMachineFunction();
2732     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2733     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2734     // Initial exec model.
2735     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2736     ARMConstantPoolValue *CPV =
2737       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2738                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2739                                       true);
2740     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2741     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2742     Offset = DAG.getLoad(
2743         PtrVT, dl, Chain, Offset,
2744         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2745     Chain = Offset.getValue(1);
2746 
2747     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2748     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2749 
2750     Offset = DAG.getLoad(
2751         PtrVT, dl, Chain, Offset,
2752         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2753   } else {
2754     // local exec model
2755     assert(model == TLSModel::LocalExec);
2756     ARMConstantPoolValue *CPV =
2757       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2758     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2759     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2760     Offset = DAG.getLoad(
2761         PtrVT, dl, Chain, Offset,
2762         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2763   }
2764 
2765   // The address of the thread local variable is the add of the thread
2766   // pointer with the offset of the variable.
2767   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2768 }
2769 
2770 SDValue
2771 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2772   if (Subtarget->isTargetDarwin())
2773     return LowerGlobalTLSAddressDarwin(Op, DAG);
2774 
2775   if (Subtarget->isTargetWindows())
2776     return LowerGlobalTLSAddressWindows(Op, DAG);
2777 
2778   // TODO: implement the "local dynamic" model
2779   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2780   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2781   if (DAG.getTarget().Options.EmulatedTLS)
2782     return LowerToTLSEmulatedModel(GA, DAG);
2783 
2784   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2785 
2786   switch (model) {
2787     case TLSModel::GeneralDynamic:
2788     case TLSModel::LocalDynamic:
2789       return LowerToTLSGeneralDynamicModel(GA, DAG);
2790     case TLSModel::InitialExec:
2791     case TLSModel::LocalExec:
2792       return LowerToTLSExecModels(GA, DAG, model);
2793   }
2794   llvm_unreachable("bogus TLS model");
2795 }
2796 
2797 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2798                                                  SelectionDAG &DAG) const {
2799   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2800   SDLoc dl(Op);
2801   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2802   const TargetMachine &TM = getTargetMachine();
2803   if (isPositionIndependent()) {
2804     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
2805 
2806     MachineFunction &MF = DAG.getMachineFunction();
2807     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2808     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2809     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2810     SDLoc dl(Op);
2811     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2812     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2813         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2814         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2815         /*AddCurrentAddress=*/UseGOT_PREL);
2816     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2817     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2818     SDValue Result = DAG.getLoad(
2819         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2820         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2821     SDValue Chain = Result.getValue(1);
2822     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2823     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2824     if (UseGOT_PREL)
2825       Result =
2826           DAG.getLoad(PtrVT, dl, Chain, Result,
2827                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2828     return Result;
2829   }
2830 
2831   // If we have T2 ops, we can materialize the address directly via movt/movw
2832   // pair. This is always cheaper.
2833   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2834     ++NumMovwMovt;
2835     // FIXME: Once remat is capable of dealing with instructions with register
2836     // operands, expand this into two nodes.
2837     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2838                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2839   } else {
2840     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2841     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2842     return DAG.getLoad(
2843         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2844         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2845   }
2846 }
2847 
2848 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2849                                                     SelectionDAG &DAG) const {
2850   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2851   SDLoc dl(Op);
2852   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2853 
2854   if (Subtarget->useMovt(DAG.getMachineFunction()))
2855     ++NumMovwMovt;
2856 
2857   // FIXME: Once remat is capable of dealing with instructions with register
2858   // operands, expand this into multiple nodes
2859   unsigned Wrapper =
2860       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2861 
2862   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2863   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2864 
2865   if (Subtarget->isGVIndirectSymbol(GV))
2866     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2867                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2868   return Result;
2869 }
2870 
2871 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2872                                                      SelectionDAG &DAG) const {
2873   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2874   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2875          "Windows on ARM expects to use movw/movt");
2876 
2877   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2878   const ARMII::TOF TargetFlags =
2879     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2880   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2881   SDValue Result;
2882   SDLoc DL(Op);
2883 
2884   ++NumMovwMovt;
2885 
2886   // FIXME: Once remat is capable of dealing with instructions with register
2887   // operands, expand this into two nodes.
2888   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2889                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2890                                                   TargetFlags));
2891   if (GV->hasDLLImportStorageClass())
2892     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2893                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2894   return Result;
2895 }
2896 
2897 SDValue
2898 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2899   SDLoc dl(Op);
2900   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2901   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2902                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2903                      Op.getOperand(1), Val);
2904 }
2905 
2906 SDValue
2907 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2908   SDLoc dl(Op);
2909   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2910                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2911 }
2912 
2913 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2914                                                       SelectionDAG &DAG) const {
2915   SDLoc dl(Op);
2916   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2917                      Op.getOperand(0));
2918 }
2919 
2920 SDValue
2921 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2922                                           const ARMSubtarget *Subtarget) const {
2923   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2924   SDLoc dl(Op);
2925   switch (IntNo) {
2926   default: return SDValue();    // Don't custom lower most intrinsics.
2927   case Intrinsic::arm_rbit: {
2928     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2929            "RBIT intrinsic must have i32 type!");
2930     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2931   }
2932   case Intrinsic::thread_pointer: {
2933     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2934     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2935   }
2936   case Intrinsic::eh_sjlj_lsda: {
2937     MachineFunction &MF = DAG.getMachineFunction();
2938     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2939     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2940     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2941     SDValue CPAddr;
2942     bool IsPositionIndependent = isPositionIndependent();
2943     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
2944     ARMConstantPoolValue *CPV =
2945       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2946                                       ARMCP::CPLSDA, PCAdj);
2947     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2948     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2949     SDValue Result = DAG.getLoad(
2950         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2951         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2952 
2953     if (IsPositionIndependent) {
2954       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2955       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2956     }
2957     return Result;
2958   }
2959   case Intrinsic::arm_neon_vmulls:
2960   case Intrinsic::arm_neon_vmullu: {
2961     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2962       ? ARMISD::VMULLs : ARMISD::VMULLu;
2963     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2964                        Op.getOperand(1), Op.getOperand(2));
2965   }
2966   case Intrinsic::arm_neon_vminnm:
2967   case Intrinsic::arm_neon_vmaxnm: {
2968     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2969       ? ISD::FMINNUM : ISD::FMAXNUM;
2970     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2971                        Op.getOperand(1), Op.getOperand(2));
2972   }
2973   case Intrinsic::arm_neon_vminu:
2974   case Intrinsic::arm_neon_vmaxu: {
2975     if (Op.getValueType().isFloatingPoint())
2976       return SDValue();
2977     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2978       ? ISD::UMIN : ISD::UMAX;
2979     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2980                          Op.getOperand(1), Op.getOperand(2));
2981   }
2982   case Intrinsic::arm_neon_vmins:
2983   case Intrinsic::arm_neon_vmaxs: {
2984     // v{min,max}s is overloaded between signed integers and floats.
2985     if (!Op.getValueType().isFloatingPoint()) {
2986       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2987         ? ISD::SMIN : ISD::SMAX;
2988       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2989                          Op.getOperand(1), Op.getOperand(2));
2990     }
2991     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2992       ? ISD::FMINNAN : ISD::FMAXNAN;
2993     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2994                        Op.getOperand(1), Op.getOperand(2));
2995   }
2996   }
2997 }
2998 
2999 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3000                                  const ARMSubtarget *Subtarget) {
3001   // FIXME: handle "fence singlethread" more efficiently.
3002   SDLoc dl(Op);
3003   if (!Subtarget->hasDataBarrier()) {
3004     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3005     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3006     // here.
3007     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3008            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3009     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3010                        DAG.getConstant(0, dl, MVT::i32));
3011   }
3012 
3013   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3014   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3015   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3016   if (Subtarget->isMClass()) {
3017     // Only a full system barrier exists in the M-class architectures.
3018     Domain = ARM_MB::SY;
3019   } else if (Subtarget->preferISHSTBarriers() &&
3020              Ord == AtomicOrdering::Release) {
3021     // Swift happens to implement ISHST barriers in a way that's compatible with
3022     // Release semantics but weaker than ISH so we'd be fools not to use
3023     // it. Beware: other processors probably don't!
3024     Domain = ARM_MB::ISHST;
3025   }
3026 
3027   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3028                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3029                      DAG.getConstant(Domain, dl, MVT::i32));
3030 }
3031 
3032 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3033                              const ARMSubtarget *Subtarget) {
3034   // ARM pre v5TE and Thumb1 does not have preload instructions.
3035   if (!(Subtarget->isThumb2() ||
3036         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3037     // Just preserve the chain.
3038     return Op.getOperand(0);
3039 
3040   SDLoc dl(Op);
3041   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3042   if (!isRead &&
3043       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3044     // ARMv7 with MP extension has PLDW.
3045     return Op.getOperand(0);
3046 
3047   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3048   if (Subtarget->isThumb()) {
3049     // Invert the bits.
3050     isRead = ~isRead & 1;
3051     isData = ~isData & 1;
3052   }
3053 
3054   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3055                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3056                      DAG.getConstant(isData, dl, MVT::i32));
3057 }
3058 
3059 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3060   MachineFunction &MF = DAG.getMachineFunction();
3061   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3062 
3063   // vastart just stores the address of the VarArgsFrameIndex slot into the
3064   // memory location argument.
3065   SDLoc dl(Op);
3066   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3067   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3068   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3069   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3070                       MachinePointerInfo(SV));
3071 }
3072 
3073 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3074                                                 CCValAssign &NextVA,
3075                                                 SDValue &Root,
3076                                                 SelectionDAG &DAG,
3077                                                 const SDLoc &dl) const {
3078   MachineFunction &MF = DAG.getMachineFunction();
3079   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3080 
3081   const TargetRegisterClass *RC;
3082   if (AFI->isThumb1OnlyFunction())
3083     RC = &ARM::tGPRRegClass;
3084   else
3085     RC = &ARM::GPRRegClass;
3086 
3087   // Transform the arguments stored in physical registers into virtual ones.
3088   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3089   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3090 
3091   SDValue ArgValue2;
3092   if (NextVA.isMemLoc()) {
3093     MachineFrameInfo &MFI = MF.getFrameInfo();
3094     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3095 
3096     // Create load node to retrieve arguments from the stack.
3097     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3098     ArgValue2 = DAG.getLoad(
3099         MVT::i32, dl, Root, FIN,
3100         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3101   } else {
3102     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3103     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3104   }
3105   if (!Subtarget->isLittle())
3106     std::swap (ArgValue, ArgValue2);
3107   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3108 }
3109 
3110 // The remaining GPRs hold either the beginning of variable-argument
3111 // data, or the beginning of an aggregate passed by value (usually
3112 // byval).  Either way, we allocate stack slots adjacent to the data
3113 // provided by our caller, and store the unallocated registers there.
3114 // If this is a variadic function, the va_list pointer will begin with
3115 // these values; otherwise, this reassembles a (byval) structure that
3116 // was split between registers and memory.
3117 // Return: The frame index registers were stored into.
3118 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3119                                       const SDLoc &dl, SDValue &Chain,
3120                                       const Value *OrigArg,
3121                                       unsigned InRegsParamRecordIdx,
3122                                       int ArgOffset, unsigned ArgSize) const {
3123   // Currently, two use-cases possible:
3124   // Case #1. Non-var-args function, and we meet first byval parameter.
3125   //          Setup first unallocated register as first byval register;
3126   //          eat all remained registers
3127   //          (these two actions are performed by HandleByVal method).
3128   //          Then, here, we initialize stack frame with
3129   //          "store-reg" instructions.
3130   // Case #2. Var-args function, that doesn't contain byval parameters.
3131   //          The same: eat all remained unallocated registers,
3132   //          initialize stack frame.
3133 
3134   MachineFunction &MF = DAG.getMachineFunction();
3135   MachineFrameInfo &MFI = MF.getFrameInfo();
3136   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3137   unsigned RBegin, REnd;
3138   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3139     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3140   } else {
3141     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3142     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3143     REnd = ARM::R4;
3144   }
3145 
3146   if (REnd != RBegin)
3147     ArgOffset = -4 * (ARM::R4 - RBegin);
3148 
3149   auto PtrVT = getPointerTy(DAG.getDataLayout());
3150   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3151   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3152 
3153   SmallVector<SDValue, 4> MemOps;
3154   const TargetRegisterClass *RC =
3155       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3156 
3157   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3158     unsigned VReg = MF.addLiveIn(Reg, RC);
3159     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3160     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3161                                  MachinePointerInfo(OrigArg, 4 * i));
3162     MemOps.push_back(Store);
3163     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3164   }
3165 
3166   if (!MemOps.empty())
3167     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3168   return FrameIndex;
3169 }
3170 
3171 // Setup stack frame, the va_list pointer will start from.
3172 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3173                                              const SDLoc &dl, SDValue &Chain,
3174                                              unsigned ArgOffset,
3175                                              unsigned TotalArgRegsSaveSize,
3176                                              bool ForceMutable) const {
3177   MachineFunction &MF = DAG.getMachineFunction();
3178   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3179 
3180   // Try to store any remaining integer argument regs
3181   // to their spots on the stack so that they may be loaded by dereferencing
3182   // the result of va_next.
3183   // If there is no regs to be stored, just point address after last
3184   // argument passed via stack.
3185   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3186                                   CCInfo.getInRegsParamsCount(),
3187                                   CCInfo.getNextStackOffset(), 4);
3188   AFI->setVarArgsFrameIndex(FrameIndex);
3189 }
3190 
3191 SDValue ARMTargetLowering::LowerFormalArguments(
3192     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3193     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3194     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3195   MachineFunction &MF = DAG.getMachineFunction();
3196   MachineFrameInfo &MFI = MF.getFrameInfo();
3197 
3198   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3199 
3200   // Assign locations to all of the incoming arguments.
3201   SmallVector<CCValAssign, 16> ArgLocs;
3202   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3203                     *DAG.getContext(), Prologue);
3204   CCInfo.AnalyzeFormalArguments(Ins,
3205                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3206                                                   isVarArg));
3207 
3208   SmallVector<SDValue, 16> ArgValues;
3209   SDValue ArgValue;
3210   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3211   unsigned CurArgIdx = 0;
3212 
3213   // Initially ArgRegsSaveSize is zero.
3214   // Then we increase this value each time we meet byval parameter.
3215   // We also increase this value in case of varargs function.
3216   AFI->setArgRegsSaveSize(0);
3217 
3218   // Calculate the amount of stack space that we need to allocate to store
3219   // byval and variadic arguments that are passed in registers.
3220   // We need to know this before we allocate the first byval or variadic
3221   // argument, as they will be allocated a stack slot below the CFA (Canonical
3222   // Frame Address, the stack pointer at entry to the function).
3223   unsigned ArgRegBegin = ARM::R4;
3224   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3225     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3226       break;
3227 
3228     CCValAssign &VA = ArgLocs[i];
3229     unsigned Index = VA.getValNo();
3230     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3231     if (!Flags.isByVal())
3232       continue;
3233 
3234     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3235     unsigned RBegin, REnd;
3236     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3237     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3238 
3239     CCInfo.nextInRegsParam();
3240   }
3241   CCInfo.rewindByValRegsInfo();
3242 
3243   int lastInsIndex = -1;
3244   if (isVarArg && MFI.hasVAStart()) {
3245     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3246     if (RegIdx != array_lengthof(GPRArgRegs))
3247       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3248   }
3249 
3250   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3251   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3252   auto PtrVT = getPointerTy(DAG.getDataLayout());
3253 
3254   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3255     CCValAssign &VA = ArgLocs[i];
3256     if (Ins[VA.getValNo()].isOrigArg()) {
3257       std::advance(CurOrigArg,
3258                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3259       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3260     }
3261     // Arguments stored in registers.
3262     if (VA.isRegLoc()) {
3263       EVT RegVT = VA.getLocVT();
3264 
3265       if (VA.needsCustom()) {
3266         // f64 and vector types are split up into multiple registers or
3267         // combinations of registers and stack slots.
3268         if (VA.getLocVT() == MVT::v2f64) {
3269           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3270                                                    Chain, DAG, dl);
3271           VA = ArgLocs[++i]; // skip ahead to next loc
3272           SDValue ArgValue2;
3273           if (VA.isMemLoc()) {
3274             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3275             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3276             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3277                                     MachinePointerInfo::getFixedStack(
3278                                         DAG.getMachineFunction(), FI));
3279           } else {
3280             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3281                                              Chain, DAG, dl);
3282           }
3283           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3284           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3285                                  ArgValue, ArgValue1,
3286                                  DAG.getIntPtrConstant(0, dl));
3287           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3288                                  ArgValue, ArgValue2,
3289                                  DAG.getIntPtrConstant(1, dl));
3290         } else
3291           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3292 
3293       } else {
3294         const TargetRegisterClass *RC;
3295 
3296         if (RegVT == MVT::f32)
3297           RC = &ARM::SPRRegClass;
3298         else if (RegVT == MVT::f64)
3299           RC = &ARM::DPRRegClass;
3300         else if (RegVT == MVT::v2f64)
3301           RC = &ARM::QPRRegClass;
3302         else if (RegVT == MVT::i32)
3303           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3304                                            : &ARM::GPRRegClass;
3305         else
3306           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3307 
3308         // Transform the arguments in physical registers into virtual ones.
3309         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3310         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3311       }
3312 
3313       // If this is an 8 or 16-bit value, it is really passed promoted
3314       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3315       // truncate to the right size.
3316       switch (VA.getLocInfo()) {
3317       default: llvm_unreachable("Unknown loc info!");
3318       case CCValAssign::Full: break;
3319       case CCValAssign::BCvt:
3320         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3321         break;
3322       case CCValAssign::SExt:
3323         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3324                                DAG.getValueType(VA.getValVT()));
3325         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3326         break;
3327       case CCValAssign::ZExt:
3328         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3329                                DAG.getValueType(VA.getValVT()));
3330         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3331         break;
3332       }
3333 
3334       InVals.push_back(ArgValue);
3335 
3336     } else { // VA.isRegLoc()
3337 
3338       // sanity check
3339       assert(VA.isMemLoc());
3340       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3341 
3342       int index = VA.getValNo();
3343 
3344       // Some Ins[] entries become multiple ArgLoc[] entries.
3345       // Process them only once.
3346       if (index != lastInsIndex)
3347         {
3348           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3349           // FIXME: For now, all byval parameter objects are marked mutable.
3350           // This can be changed with more analysis.
3351           // In case of tail call optimization mark all arguments mutable.
3352           // Since they could be overwritten by lowering of arguments in case of
3353           // a tail call.
3354           if (Flags.isByVal()) {
3355             assert(Ins[index].isOrigArg() &&
3356                    "Byval arguments cannot be implicit");
3357             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3358 
3359             int FrameIndex = StoreByValRegs(
3360                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3361                 VA.getLocMemOffset(), Flags.getByValSize());
3362             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3363             CCInfo.nextInRegsParam();
3364           } else {
3365             unsigned FIOffset = VA.getLocMemOffset();
3366             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3367                                            FIOffset, true);
3368 
3369             // Create load nodes to retrieve arguments from the stack.
3370             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3371             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3372                                          MachinePointerInfo::getFixedStack(
3373                                              DAG.getMachineFunction(), FI)));
3374           }
3375           lastInsIndex = index;
3376         }
3377     }
3378   }
3379 
3380   // varargs
3381   if (isVarArg && MFI.hasVAStart())
3382     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3383                          CCInfo.getNextStackOffset(),
3384                          TotalArgRegsSaveSize);
3385 
3386   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3387 
3388   return Chain;
3389 }
3390 
3391 /// isFloatingPointZero - Return true if this is +0.0.
3392 static bool isFloatingPointZero(SDValue Op) {
3393   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3394     return CFP->getValueAPF().isPosZero();
3395   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3396     // Maybe this has already been legalized into the constant pool?
3397     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3398       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3399       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3400         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3401           return CFP->getValueAPF().isPosZero();
3402     }
3403   } else if (Op->getOpcode() == ISD::BITCAST &&
3404              Op->getValueType(0) == MVT::f64) {
3405     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3406     // created by LowerConstantFP().
3407     SDValue BitcastOp = Op->getOperand(0);
3408     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3409         isNullConstant(BitcastOp->getOperand(0)))
3410       return true;
3411   }
3412   return false;
3413 }
3414 
3415 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3416 /// the given operands.
3417 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3418                                      SDValue &ARMcc, SelectionDAG &DAG,
3419                                      const SDLoc &dl) const {
3420   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3421     unsigned C = RHSC->getZExtValue();
3422     if (!isLegalICmpImmediate(C)) {
3423       // Constant does not fit, try adjusting it by one?
3424       switch (CC) {
3425       default: break;
3426       case ISD::SETLT:
3427       case ISD::SETGE:
3428         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3429           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3430           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3431         }
3432         break;
3433       case ISD::SETULT:
3434       case ISD::SETUGE:
3435         if (C != 0 && isLegalICmpImmediate(C-1)) {
3436           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3437           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3438         }
3439         break;
3440       case ISD::SETLE:
3441       case ISD::SETGT:
3442         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3443           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3444           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3445         }
3446         break;
3447       case ISD::SETULE:
3448       case ISD::SETUGT:
3449         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3450           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3451           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3452         }
3453         break;
3454       }
3455     }
3456   }
3457 
3458   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3459   ARMISD::NodeType CompareType;
3460   switch (CondCode) {
3461   default:
3462     CompareType = ARMISD::CMP;
3463     break;
3464   case ARMCC::EQ:
3465   case ARMCC::NE:
3466     // Uses only Z Flag
3467     CompareType = ARMISD::CMPZ;
3468     break;
3469   }
3470   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3471   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3472 }
3473 
3474 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3475 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3476                                      SelectionDAG &DAG, const SDLoc &dl) const {
3477   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3478   SDValue Cmp;
3479   if (!isFloatingPointZero(RHS))
3480     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3481   else
3482     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3483   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3484 }
3485 
3486 /// duplicateCmp - Glue values can have only one use, so this function
3487 /// duplicates a comparison node.
3488 SDValue
3489 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3490   unsigned Opc = Cmp.getOpcode();
3491   SDLoc DL(Cmp);
3492   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3493     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3494 
3495   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3496   Cmp = Cmp.getOperand(0);
3497   Opc = Cmp.getOpcode();
3498   if (Opc == ARMISD::CMPFP)
3499     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3500   else {
3501     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3502     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3503   }
3504   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3505 }
3506 
3507 std::pair<SDValue, SDValue>
3508 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3509                                  SDValue &ARMcc) const {
3510   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3511 
3512   SDValue Value, OverflowCmp;
3513   SDValue LHS = Op.getOperand(0);
3514   SDValue RHS = Op.getOperand(1);
3515   SDLoc dl(Op);
3516 
3517   // FIXME: We are currently always generating CMPs because we don't support
3518   // generating CMN through the backend. This is not as good as the natural
3519   // CMP case because it causes a register dependency and cannot be folded
3520   // later.
3521 
3522   switch (Op.getOpcode()) {
3523   default:
3524     llvm_unreachable("Unknown overflow instruction!");
3525   case ISD::SADDO:
3526     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3527     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3528     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3529     break;
3530   case ISD::UADDO:
3531     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3532     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3533     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3534     break;
3535   case ISD::SSUBO:
3536     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3537     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3538     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3539     break;
3540   case ISD::USUBO:
3541     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3542     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3543     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3544     break;
3545   } // switch (...)
3546 
3547   return std::make_pair(Value, OverflowCmp);
3548 }
3549 
3550 
3551 SDValue
3552 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3553   // Let legalize expand this if it isn't a legal type yet.
3554   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3555     return SDValue();
3556 
3557   SDValue Value, OverflowCmp;
3558   SDValue ARMcc;
3559   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3560   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3561   SDLoc dl(Op);
3562   // We use 0 and 1 as false and true values.
3563   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3564   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3565   EVT VT = Op.getValueType();
3566 
3567   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3568                                  ARMcc, CCR, OverflowCmp);
3569 
3570   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3571   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3572 }
3573 
3574 
3575 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3576   SDValue Cond = Op.getOperand(0);
3577   SDValue SelectTrue = Op.getOperand(1);
3578   SDValue SelectFalse = Op.getOperand(2);
3579   SDLoc dl(Op);
3580   unsigned Opc = Cond.getOpcode();
3581 
3582   if (Cond.getResNo() == 1 &&
3583       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3584        Opc == ISD::USUBO)) {
3585     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3586       return SDValue();
3587 
3588     SDValue Value, OverflowCmp;
3589     SDValue ARMcc;
3590     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3591     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3592     EVT VT = Op.getValueType();
3593 
3594     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3595                    OverflowCmp, DAG);
3596   }
3597 
3598   // Convert:
3599   //
3600   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3601   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3602   //
3603   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3604     const ConstantSDNode *CMOVTrue =
3605       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3606     const ConstantSDNode *CMOVFalse =
3607       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3608 
3609     if (CMOVTrue && CMOVFalse) {
3610       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3611       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3612 
3613       SDValue True;
3614       SDValue False;
3615       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3616         True = SelectTrue;
3617         False = SelectFalse;
3618       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3619         True = SelectFalse;
3620         False = SelectTrue;
3621       }
3622 
3623       if (True.getNode() && False.getNode()) {
3624         EVT VT = Op.getValueType();
3625         SDValue ARMcc = Cond.getOperand(2);
3626         SDValue CCR = Cond.getOperand(3);
3627         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3628         assert(True.getValueType() == VT);
3629         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3630       }
3631     }
3632   }
3633 
3634   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3635   // undefined bits before doing a full-word comparison with zero.
3636   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3637                      DAG.getConstant(1, dl, Cond.getValueType()));
3638 
3639   return DAG.getSelectCC(dl, Cond,
3640                          DAG.getConstant(0, dl, Cond.getValueType()),
3641                          SelectTrue, SelectFalse, ISD::SETNE);
3642 }
3643 
3644 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3645                                  bool &swpCmpOps, bool &swpVselOps) {
3646   // Start by selecting the GE condition code for opcodes that return true for
3647   // 'equality'
3648   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3649       CC == ISD::SETULE)
3650     CondCode = ARMCC::GE;
3651 
3652   // and GT for opcodes that return false for 'equality'.
3653   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3654            CC == ISD::SETULT)
3655     CondCode = ARMCC::GT;
3656 
3657   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3658   // to swap the compare operands.
3659   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3660       CC == ISD::SETULT)
3661     swpCmpOps = true;
3662 
3663   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3664   // If we have an unordered opcode, we need to swap the operands to the VSEL
3665   // instruction (effectively negating the condition).
3666   //
3667   // This also has the effect of swapping which one of 'less' or 'greater'
3668   // returns true, so we also swap the compare operands. It also switches
3669   // whether we return true for 'equality', so we compensate by picking the
3670   // opposite condition code to our original choice.
3671   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3672       CC == ISD::SETUGT) {
3673     swpCmpOps = !swpCmpOps;
3674     swpVselOps = !swpVselOps;
3675     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3676   }
3677 
3678   // 'ordered' is 'anything but unordered', so use the VS condition code and
3679   // swap the VSEL operands.
3680   if (CC == ISD::SETO) {
3681     CondCode = ARMCC::VS;
3682     swpVselOps = true;
3683   }
3684 
3685   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3686   // code and swap the VSEL operands.
3687   if (CC == ISD::SETUNE) {
3688     CondCode = ARMCC::EQ;
3689     swpVselOps = true;
3690   }
3691 }
3692 
3693 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
3694                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3695                                    SDValue Cmp, SelectionDAG &DAG) const {
3696   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3697     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3698                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3699     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3700                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3701 
3702     SDValue TrueLow = TrueVal.getValue(0);
3703     SDValue TrueHigh = TrueVal.getValue(1);
3704     SDValue FalseLow = FalseVal.getValue(0);
3705     SDValue FalseHigh = FalseVal.getValue(1);
3706 
3707     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3708                               ARMcc, CCR, Cmp);
3709     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3710                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3711 
3712     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3713   } else {
3714     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3715                        Cmp);
3716   }
3717 }
3718 
3719 static bool isGTorGE(ISD::CondCode CC) {
3720   return CC == ISD::SETGT || CC == ISD::SETGE;
3721 }
3722 
3723 static bool isLTorLE(ISD::CondCode CC) {
3724   return CC == ISD::SETLT || CC == ISD::SETLE;
3725 }
3726 
3727 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
3728 // All of these conditions (and their <= and >= counterparts) will do:
3729 //          x < k ? k : x
3730 //          x > k ? x : k
3731 //          k < x ? x : k
3732 //          k > x ? k : x
3733 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
3734                             const SDValue TrueVal, const SDValue FalseVal,
3735                             const ISD::CondCode CC, const SDValue K) {
3736   return (isGTorGE(CC) &&
3737           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
3738          (isLTorLE(CC) &&
3739           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
3740 }
3741 
3742 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
3743 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
3744                             const SDValue TrueVal, const SDValue FalseVal,
3745                             const ISD::CondCode CC, const SDValue K) {
3746   return (isGTorGE(CC) &&
3747           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
3748          (isLTorLE(CC) &&
3749           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
3750 }
3751 
3752 // Check if two chained conditionals could be converted into SSAT.
3753 //
3754 // SSAT can replace a set of two conditional selectors that bound a number to an
3755 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
3756 //
3757 //     x < -k ? -k : (x > k ? k : x)
3758 //     x < -k ? -k : (x < k ? x : k)
3759 //     x > -k ? (x > k ? k : x) : -k
3760 //     x < k ? (x < -k ? -k : x) : k
3761 //     etc.
3762 //
3763 // It returns true if the conversion can be done, false otherwise.
3764 // Additionally, the variable is returned in parameter V and the constant in K.
3765 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
3766                                     uint64_t &K) {
3767 
3768   SDValue LHS1 = Op.getOperand(0);
3769   SDValue RHS1 = Op.getOperand(1);
3770   SDValue TrueVal1 = Op.getOperand(2);
3771   SDValue FalseVal1 = Op.getOperand(3);
3772   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3773 
3774   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
3775   if (Op2.getOpcode() != ISD::SELECT_CC)
3776     return false;
3777 
3778   SDValue LHS2 = Op2.getOperand(0);
3779   SDValue RHS2 = Op2.getOperand(1);
3780   SDValue TrueVal2 = Op2.getOperand(2);
3781   SDValue FalseVal2 = Op2.getOperand(3);
3782   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
3783 
3784   // Find out which are the constants and which are the variables
3785   // in each conditional
3786   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
3787                                                         ? &RHS1
3788                                                         : NULL;
3789   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
3790                                                         ? &RHS2
3791                                                         : NULL;
3792   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
3793   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
3794   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
3795   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
3796 
3797   // We must detect cases where the original operations worked with 16- or
3798   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
3799   // must work with sign-extended values but the select operations return
3800   // the original non-extended value.
3801   SDValue V2TmpReg = V2Tmp;
3802   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
3803     V2TmpReg = V2Tmp->getOperand(0);
3804 
3805   // Check that the registers and the constants have the correct values
3806   // in both conditionals
3807   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
3808       V2TmpReg != V2)
3809     return false;
3810 
3811   // Figure out which conditional is saturating the lower/upper bound.
3812   const SDValue *LowerCheckOp =
3813       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
3814           ? &Op
3815           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
3816                                                                        : NULL;
3817   const SDValue *UpperCheckOp =
3818       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
3819           ? &Op
3820           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
3821                                                                        : NULL;
3822 
3823   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
3824     return false;
3825 
3826   // Check that the constant in the lower-bound check is
3827   // the opposite of the constant in the upper-bound check
3828   // in 1's complement.
3829   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
3830   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
3831   int64_t PosVal = std::max(Val1, Val2);
3832 
3833   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
3834        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
3835       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
3836 
3837     V = V2;
3838     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
3839     return true;
3840   }
3841 
3842   return false;
3843 }
3844 
3845 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3846 
3847   EVT VT = Op.getValueType();
3848   SDLoc dl(Op);
3849 
3850   // Try to convert two saturating conditional selects into a single SSAT
3851   SDValue SatValue;
3852   uint64_t SatConstant;
3853   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
3854       isSaturatingConditional(Op, SatValue, SatConstant))
3855     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
3856                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
3857 
3858   SDValue LHS = Op.getOperand(0);
3859   SDValue RHS = Op.getOperand(1);
3860   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3861   SDValue TrueVal = Op.getOperand(2);
3862   SDValue FalseVal = Op.getOperand(3);
3863 
3864   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3865     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3866                                                     dl);
3867 
3868     // If softenSetCCOperands only returned one value, we should compare it to
3869     // zero.
3870     if (!RHS.getNode()) {
3871       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3872       CC = ISD::SETNE;
3873     }
3874   }
3875 
3876   if (LHS.getValueType() == MVT::i32) {
3877     // Try to generate VSEL on ARMv8.
3878     // The VSEL instruction can't use all the usual ARM condition
3879     // codes: it only has two bits to select the condition code, so it's
3880     // constrained to use only GE, GT, VS and EQ.
3881     //
3882     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3883     // swap the operands of the previous compare instruction (effectively
3884     // inverting the compare condition, swapping 'less' and 'greater') and
3885     // sometimes need to swap the operands to the VSEL (which inverts the
3886     // condition in the sense of firing whenever the previous condition didn't)
3887     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3888                                     TrueVal.getValueType() == MVT::f64)) {
3889       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3890       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3891           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3892         CC = ISD::getSetCCInverse(CC, true);
3893         std::swap(TrueVal, FalseVal);
3894       }
3895     }
3896 
3897     SDValue ARMcc;
3898     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3899     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3900     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3901   }
3902 
3903   ARMCC::CondCodes CondCode, CondCode2;
3904   FPCCToARMCC(CC, CondCode, CondCode2);
3905 
3906   // Try to generate VMAXNM/VMINNM on ARMv8.
3907   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3908                                   TrueVal.getValueType() == MVT::f64)) {
3909     bool swpCmpOps = false;
3910     bool swpVselOps = false;
3911     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3912 
3913     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3914         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3915       if (swpCmpOps)
3916         std::swap(LHS, RHS);
3917       if (swpVselOps)
3918         std::swap(TrueVal, FalseVal);
3919     }
3920   }
3921 
3922   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3923   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3924   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3925   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3926   if (CondCode2 != ARMCC::AL) {
3927     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3928     // FIXME: Needs another CMP because flag can have but one use.
3929     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3930     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3931   }
3932   return Result;
3933 }
3934 
3935 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3936 /// to morph to an integer compare sequence.
3937 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3938                            const ARMSubtarget *Subtarget) {
3939   SDNode *N = Op.getNode();
3940   if (!N->hasOneUse())
3941     // Otherwise it requires moving the value from fp to integer registers.
3942     return false;
3943   if (!N->getNumValues())
3944     return false;
3945   EVT VT = Op.getValueType();
3946   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3947     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3948     // vmrs are very slow, e.g. cortex-a8.
3949     return false;
3950 
3951   if (isFloatingPointZero(Op)) {
3952     SeenZero = true;
3953     return true;
3954   }
3955   return ISD::isNormalLoad(N);
3956 }
3957 
3958 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3959   if (isFloatingPointZero(Op))
3960     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3961 
3962   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3963     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
3964                        Ld->getPointerInfo(), Ld->getAlignment(),
3965                        Ld->getMemOperand()->getFlags());
3966 
3967   llvm_unreachable("Unknown VFP cmp argument!");
3968 }
3969 
3970 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3971                            SDValue &RetVal1, SDValue &RetVal2) {
3972   SDLoc dl(Op);
3973 
3974   if (isFloatingPointZero(Op)) {
3975     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3976     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3977     return;
3978   }
3979 
3980   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3981     SDValue Ptr = Ld->getBasePtr();
3982     RetVal1 =
3983         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
3984                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
3985 
3986     EVT PtrType = Ptr.getValueType();
3987     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3988     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3989                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3990     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
3991                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
3992                           Ld->getMemOperand()->getFlags());
3993     return;
3994   }
3995 
3996   llvm_unreachable("Unknown VFP cmp argument!");
3997 }
3998 
3999 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4000 /// f32 and even f64 comparisons to integer ones.
4001 SDValue
4002 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4003   SDValue Chain = Op.getOperand(0);
4004   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4005   SDValue LHS = Op.getOperand(2);
4006   SDValue RHS = Op.getOperand(3);
4007   SDValue Dest = Op.getOperand(4);
4008   SDLoc dl(Op);
4009 
4010   bool LHSSeenZero = false;
4011   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4012   bool RHSSeenZero = false;
4013   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4014   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4015     // If unsafe fp math optimization is enabled and there are no other uses of
4016     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4017     // to an integer comparison.
4018     if (CC == ISD::SETOEQ)
4019       CC = ISD::SETEQ;
4020     else if (CC == ISD::SETUNE)
4021       CC = ISD::SETNE;
4022 
4023     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4024     SDValue ARMcc;
4025     if (LHS.getValueType() == MVT::f32) {
4026       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4027                         bitcastf32Toi32(LHS, DAG), Mask);
4028       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4029                         bitcastf32Toi32(RHS, DAG), Mask);
4030       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4031       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4032       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4033                          Chain, Dest, ARMcc, CCR, Cmp);
4034     }
4035 
4036     SDValue LHS1, LHS2;
4037     SDValue RHS1, RHS2;
4038     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4039     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4040     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4041     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4042     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4043     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4044     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4045     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4046     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4047   }
4048 
4049   return SDValue();
4050 }
4051 
4052 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4053   SDValue Chain = Op.getOperand(0);
4054   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4055   SDValue LHS = Op.getOperand(2);
4056   SDValue RHS = Op.getOperand(3);
4057   SDValue Dest = Op.getOperand(4);
4058   SDLoc dl(Op);
4059 
4060   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4061     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4062                                                     dl);
4063 
4064     // If softenSetCCOperands only returned one value, we should compare it to
4065     // zero.
4066     if (!RHS.getNode()) {
4067       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4068       CC = ISD::SETNE;
4069     }
4070   }
4071 
4072   if (LHS.getValueType() == MVT::i32) {
4073     SDValue ARMcc;
4074     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4075     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4076     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4077                        Chain, Dest, ARMcc, CCR, Cmp);
4078   }
4079 
4080   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4081 
4082   if (getTargetMachine().Options.UnsafeFPMath &&
4083       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4084        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4085     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4086       return Result;
4087   }
4088 
4089   ARMCC::CondCodes CondCode, CondCode2;
4090   FPCCToARMCC(CC, CondCode, CondCode2);
4091 
4092   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4093   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4094   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4095   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4096   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4097   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4098   if (CondCode2 != ARMCC::AL) {
4099     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4100     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4101     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4102   }
4103   return Res;
4104 }
4105 
4106 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4107   SDValue Chain = Op.getOperand(0);
4108   SDValue Table = Op.getOperand(1);
4109   SDValue Index = Op.getOperand(2);
4110   SDLoc dl(Op);
4111 
4112   EVT PTy = getPointerTy(DAG.getDataLayout());
4113   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4114   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4115   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4116   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4117   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4118   if (Subtarget->isThumb2()) {
4119     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4120     // which does another jump to the destination. This also makes it easier
4121     // to translate it to TBB / TBH later.
4122     // FIXME: This might not work if the function is extremely large.
4123     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4124                        Addr, Op.getOperand(2), JTI);
4125   }
4126   if (isPositionIndependent()) {
4127     Addr =
4128         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4129                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4130     Chain = Addr.getValue(1);
4131     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4132     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4133   } else {
4134     Addr =
4135         DAG.getLoad(PTy, dl, Chain, Addr,
4136                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4137     Chain = Addr.getValue(1);
4138     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4139   }
4140 }
4141 
4142 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4143   EVT VT = Op.getValueType();
4144   SDLoc dl(Op);
4145 
4146   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4147     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4148       return Op;
4149     return DAG.UnrollVectorOp(Op.getNode());
4150   }
4151 
4152   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4153          "Invalid type for custom lowering!");
4154   if (VT != MVT::v4i16)
4155     return DAG.UnrollVectorOp(Op.getNode());
4156 
4157   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4158   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4159 }
4160 
4161 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4162   EVT VT = Op.getValueType();
4163   if (VT.isVector())
4164     return LowerVectorFP_TO_INT(Op, DAG);
4165   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4166     RTLIB::Libcall LC;
4167     if (Op.getOpcode() == ISD::FP_TO_SINT)
4168       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4169                               Op.getValueType());
4170     else
4171       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4172                               Op.getValueType());
4173     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4174                        /*isSigned*/ false, SDLoc(Op)).first;
4175   }
4176 
4177   return Op;
4178 }
4179 
4180 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4181   EVT VT = Op.getValueType();
4182   SDLoc dl(Op);
4183 
4184   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4185     if (VT.getVectorElementType() == MVT::f32)
4186       return Op;
4187     return DAG.UnrollVectorOp(Op.getNode());
4188   }
4189 
4190   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4191          "Invalid type for custom lowering!");
4192   if (VT != MVT::v4f32)
4193     return DAG.UnrollVectorOp(Op.getNode());
4194 
4195   unsigned CastOpc;
4196   unsigned Opc;
4197   switch (Op.getOpcode()) {
4198   default: llvm_unreachable("Invalid opcode!");
4199   case ISD::SINT_TO_FP:
4200     CastOpc = ISD::SIGN_EXTEND;
4201     Opc = ISD::SINT_TO_FP;
4202     break;
4203   case ISD::UINT_TO_FP:
4204     CastOpc = ISD::ZERO_EXTEND;
4205     Opc = ISD::UINT_TO_FP;
4206     break;
4207   }
4208 
4209   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4210   return DAG.getNode(Opc, dl, VT, Op);
4211 }
4212 
4213 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4214   EVT VT = Op.getValueType();
4215   if (VT.isVector())
4216     return LowerVectorINT_TO_FP(Op, DAG);
4217   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4218     RTLIB::Libcall LC;
4219     if (Op.getOpcode() == ISD::SINT_TO_FP)
4220       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4221                               Op.getValueType());
4222     else
4223       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4224                               Op.getValueType());
4225     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4226                        /*isSigned*/ false, SDLoc(Op)).first;
4227   }
4228 
4229   return Op;
4230 }
4231 
4232 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4233   // Implement fcopysign with a fabs and a conditional fneg.
4234   SDValue Tmp0 = Op.getOperand(0);
4235   SDValue Tmp1 = Op.getOperand(1);
4236   SDLoc dl(Op);
4237   EVT VT = Op.getValueType();
4238   EVT SrcVT = Tmp1.getValueType();
4239   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4240     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4241   bool UseNEON = !InGPR && Subtarget->hasNEON();
4242 
4243   if (UseNEON) {
4244     // Use VBSL to copy the sign bit.
4245     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4246     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4247                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4248     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4249     if (VT == MVT::f64)
4250       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4251                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4252                          DAG.getConstant(32, dl, MVT::i32));
4253     else /*if (VT == MVT::f32)*/
4254       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4255     if (SrcVT == MVT::f32) {
4256       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4257       if (VT == MVT::f64)
4258         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4259                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4260                            DAG.getConstant(32, dl, MVT::i32));
4261     } else if (VT == MVT::f32)
4262       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4263                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4264                          DAG.getConstant(32, dl, MVT::i32));
4265     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4266     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4267 
4268     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4269                                             dl, MVT::i32);
4270     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4271     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4272                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4273 
4274     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4275                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4276                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4277     if (VT == MVT::f32) {
4278       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4279       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4280                         DAG.getConstant(0, dl, MVT::i32));
4281     } else {
4282       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4283     }
4284 
4285     return Res;
4286   }
4287 
4288   // Bitcast operand 1 to i32.
4289   if (SrcVT == MVT::f64)
4290     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4291                        Tmp1).getValue(1);
4292   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4293 
4294   // Or in the signbit with integer operations.
4295   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4296   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4297   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4298   if (VT == MVT::f32) {
4299     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4300                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4301     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4302                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4303   }
4304 
4305   // f64: Or the high part with signbit and then combine two parts.
4306   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4307                      Tmp0);
4308   SDValue Lo = Tmp0.getValue(0);
4309   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4310   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4311   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4312 }
4313 
4314 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4315   MachineFunction &MF = DAG.getMachineFunction();
4316   MachineFrameInfo &MFI = MF.getFrameInfo();
4317   MFI.setReturnAddressIsTaken(true);
4318 
4319   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4320     return SDValue();
4321 
4322   EVT VT = Op.getValueType();
4323   SDLoc dl(Op);
4324   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4325   if (Depth) {
4326     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4327     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4328     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4329                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4330                        MachinePointerInfo());
4331   }
4332 
4333   // Return LR, which contains the return address. Mark it an implicit live-in.
4334   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4335   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4336 }
4337 
4338 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4339   const ARMBaseRegisterInfo &ARI =
4340     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4341   MachineFunction &MF = DAG.getMachineFunction();
4342   MachineFrameInfo &MFI = MF.getFrameInfo();
4343   MFI.setFrameAddressIsTaken(true);
4344 
4345   EVT VT = Op.getValueType();
4346   SDLoc dl(Op);  // FIXME probably not meaningful
4347   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4348   unsigned FrameReg = ARI.getFrameRegister(MF);
4349   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4350   while (Depth--)
4351     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4352                             MachinePointerInfo());
4353   return FrameAddr;
4354 }
4355 
4356 // FIXME? Maybe this could be a TableGen attribute on some registers and
4357 // this table could be generated automatically from RegInfo.
4358 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4359                                               SelectionDAG &DAG) const {
4360   unsigned Reg = StringSwitch<unsigned>(RegName)
4361                        .Case("sp", ARM::SP)
4362                        .Default(0);
4363   if (Reg)
4364     return Reg;
4365   report_fatal_error(Twine("Invalid register name \""
4366                               + StringRef(RegName)  + "\"."));
4367 }
4368 
4369 // Result is 64 bit value so split into two 32 bit values and return as a
4370 // pair of values.
4371 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4372                                 SelectionDAG &DAG) {
4373   SDLoc DL(N);
4374 
4375   // This function is only supposed to be called for i64 type destination.
4376   assert(N->getValueType(0) == MVT::i64
4377           && "ExpandREAD_REGISTER called for non-i64 type result.");
4378 
4379   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4380                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4381                              N->getOperand(0),
4382                              N->getOperand(1));
4383 
4384   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4385                     Read.getValue(1)));
4386   Results.push_back(Read.getOperand(0));
4387 }
4388 
4389 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4390 /// When \p DstVT, the destination type of \p BC, is on the vector
4391 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4392 /// it might be possible to combine them, such that everything stays on the
4393 /// vector register bank.
4394 /// \p return The node that would replace \p BT, if the combine
4395 /// is possible.
4396 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4397                                                 SelectionDAG &DAG) {
4398   SDValue Op = BC->getOperand(0);
4399   EVT DstVT = BC->getValueType(0);
4400 
4401   // The only vector instruction that can produce a scalar (remember,
4402   // since the bitcast was about to be turned into VMOVDRR, the source
4403   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4404   // Moreover, we can do this combine only if there is one use.
4405   // Finally, if the destination type is not a vector, there is not
4406   // much point on forcing everything on the vector bank.
4407   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4408       !Op.hasOneUse())
4409     return SDValue();
4410 
4411   // If the index is not constant, we will introduce an additional
4412   // multiply that will stick.
4413   // Give up in that case.
4414   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4415   if (!Index)
4416     return SDValue();
4417   unsigned DstNumElt = DstVT.getVectorNumElements();
4418 
4419   // Compute the new index.
4420   const APInt &APIntIndex = Index->getAPIntValue();
4421   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4422   NewIndex *= APIntIndex;
4423   // Check if the new constant index fits into i32.
4424   if (NewIndex.getBitWidth() > 32)
4425     return SDValue();
4426 
4427   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4428   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4429   SDLoc dl(Op);
4430   SDValue ExtractSrc = Op.getOperand(0);
4431   EVT VecVT = EVT::getVectorVT(
4432       *DAG.getContext(), DstVT.getScalarType(),
4433       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4434   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4435   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4436                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4437 }
4438 
4439 /// ExpandBITCAST - If the target supports VFP, this function is called to
4440 /// expand a bit convert where either the source or destination type is i64 to
4441 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4442 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4443 /// vectors), since the legalizer won't know what to do with that.
4444 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4446   SDLoc dl(N);
4447   SDValue Op = N->getOperand(0);
4448 
4449   // This function is only supposed to be called for i64 types, either as the
4450   // source or destination of the bit convert.
4451   EVT SrcVT = Op.getValueType();
4452   EVT DstVT = N->getValueType(0);
4453   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4454          "ExpandBITCAST called for non-i64 type");
4455 
4456   // Turn i64->f64 into VMOVDRR.
4457   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4458     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4459     // if we can combine the bitcast with its source.
4460     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4461       return Val;
4462 
4463     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4464                              DAG.getConstant(0, dl, MVT::i32));
4465     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4466                              DAG.getConstant(1, dl, MVT::i32));
4467     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4468                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4469   }
4470 
4471   // Turn f64->i64 into VMOVRRD.
4472   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4473     SDValue Cvt;
4474     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4475         SrcVT.getVectorNumElements() > 1)
4476       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4477                         DAG.getVTList(MVT::i32, MVT::i32),
4478                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4479     else
4480       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4481                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4482     // Merge the pieces into a single i64 value.
4483     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4484   }
4485 
4486   return SDValue();
4487 }
4488 
4489 /// getZeroVector - Returns a vector of specified type with all zero elements.
4490 /// Zero vectors are used to represent vector negation and in those cases
4491 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4492 /// not support i64 elements, so sometimes the zero vectors will need to be
4493 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4494 /// zero vector.
4495 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4496   assert(VT.isVector() && "Expected a vector type");
4497   // The canonical modified immediate encoding of a zero vector is....0!
4498   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4499   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4500   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4501   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4502 }
4503 
4504 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4505 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4506 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4507                                                 SelectionDAG &DAG) const {
4508   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4509   EVT VT = Op.getValueType();
4510   unsigned VTBits = VT.getSizeInBits();
4511   SDLoc dl(Op);
4512   SDValue ShOpLo = Op.getOperand(0);
4513   SDValue ShOpHi = Op.getOperand(1);
4514   SDValue ShAmt  = Op.getOperand(2);
4515   SDValue ARMcc;
4516   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4517 
4518   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4519 
4520   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4521                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4522   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4523   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4524                                    DAG.getConstant(VTBits, dl, MVT::i32));
4525   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4526   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4527   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4528 
4529   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4530   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4531                           ISD::SETGE, ARMcc, DAG, dl);
4532   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4533   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4534                            CCR, Cmp);
4535 
4536   SDValue Ops[2] = { Lo, Hi };
4537   return DAG.getMergeValues(Ops, dl);
4538 }
4539 
4540 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4541 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4542 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4543                                                SelectionDAG &DAG) const {
4544   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4545   EVT VT = Op.getValueType();
4546   unsigned VTBits = VT.getSizeInBits();
4547   SDLoc dl(Op);
4548   SDValue ShOpLo = Op.getOperand(0);
4549   SDValue ShOpHi = Op.getOperand(1);
4550   SDValue ShAmt  = Op.getOperand(2);
4551   SDValue ARMcc;
4552 
4553   assert(Op.getOpcode() == ISD::SHL_PARTS);
4554   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4555                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4556   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4557   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4558                                    DAG.getConstant(VTBits, dl, MVT::i32));
4559   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4560   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4561 
4562   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4563   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4564   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4565                           ISD::SETGE, ARMcc, DAG, dl);
4566   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4567   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4568                            CCR, Cmp);
4569 
4570   SDValue Ops[2] = { Lo, Hi };
4571   return DAG.getMergeValues(Ops, dl);
4572 }
4573 
4574 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4575                                             SelectionDAG &DAG) const {
4576   // The rounding mode is in bits 23:22 of the FPSCR.
4577   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4578   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4579   // so that the shift + and get folded into a bitfield extract.
4580   SDLoc dl(Op);
4581   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4582                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4583                                               MVT::i32));
4584   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4585                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4586   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4587                               DAG.getConstant(22, dl, MVT::i32));
4588   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4589                      DAG.getConstant(3, dl, MVT::i32));
4590 }
4591 
4592 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4593                          const ARMSubtarget *ST) {
4594   SDLoc dl(N);
4595   EVT VT = N->getValueType(0);
4596   if (VT.isVector()) {
4597     assert(ST->hasNEON());
4598 
4599     // Compute the least significant set bit: LSB = X & -X
4600     SDValue X = N->getOperand(0);
4601     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4602     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4603 
4604     EVT ElemTy = VT.getVectorElementType();
4605 
4606     if (ElemTy == MVT::i8) {
4607       // Compute with: cttz(x) = ctpop(lsb - 1)
4608       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4609                                 DAG.getTargetConstant(1, dl, ElemTy));
4610       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4611       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4612     }
4613 
4614     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4615         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4616       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4617       unsigned NumBits = ElemTy.getSizeInBits();
4618       SDValue WidthMinus1 =
4619           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4620                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4621       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4622       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4623     }
4624 
4625     // Compute with: cttz(x) = ctpop(lsb - 1)
4626 
4627     // Since we can only compute the number of bits in a byte with vcnt.8, we
4628     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4629     // and i64.
4630 
4631     // Compute LSB - 1.
4632     SDValue Bits;
4633     if (ElemTy == MVT::i64) {
4634       // Load constant 0xffff'ffff'ffff'ffff to register.
4635       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4636                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4637       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4638     } else {
4639       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4640                                 DAG.getTargetConstant(1, dl, ElemTy));
4641       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4642     }
4643 
4644     // Count #bits with vcnt.8.
4645     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4646     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4647     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4648 
4649     // Gather the #bits with vpaddl (pairwise add.)
4650     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4651     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4652         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4653         Cnt8);
4654     if (ElemTy == MVT::i16)
4655       return Cnt16;
4656 
4657     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4658     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4659         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4660         Cnt16);
4661     if (ElemTy == MVT::i32)
4662       return Cnt32;
4663 
4664     assert(ElemTy == MVT::i64);
4665     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4666         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4667         Cnt32);
4668     return Cnt64;
4669   }
4670 
4671   if (!ST->hasV6T2Ops())
4672     return SDValue();
4673 
4674   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4675   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4676 }
4677 
4678 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4679 /// for each 16-bit element from operand, repeated.  The basic idea is to
4680 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4681 ///
4682 /// Trace for v4i16:
4683 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4684 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4685 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4686 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4687 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4688 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4689 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4690 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4691 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4692   EVT VT = N->getValueType(0);
4693   SDLoc DL(N);
4694 
4695   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4696   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4697   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4698   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4699   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4700   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4701 }
4702 
4703 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4704 /// bit-count for each 16-bit element from the operand.  We need slightly
4705 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4706 /// 64/128-bit registers.
4707 ///
4708 /// Trace for v4i16:
4709 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4710 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4711 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4712 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4713 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4714   EVT VT = N->getValueType(0);
4715   SDLoc DL(N);
4716 
4717   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4718   if (VT.is64BitVector()) {
4719     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4720     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4721                        DAG.getIntPtrConstant(0, DL));
4722   } else {
4723     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4724                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4725     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4726   }
4727 }
4728 
4729 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4730 /// bit-count for each 32-bit element from the operand.  The idea here is
4731 /// to split the vector into 16-bit elements, leverage the 16-bit count
4732 /// routine, and then combine the results.
4733 ///
4734 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4735 /// input    = [v0    v1    ] (vi: 32-bit elements)
4736 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4737 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4738 /// vrev: N0 = [k1 k0 k3 k2 ]
4739 ///            [k0 k1 k2 k3 ]
4740 ///       N1 =+[k1 k0 k3 k2 ]
4741 ///            [k0 k2 k1 k3 ]
4742 ///       N2 =+[k1 k3 k0 k2 ]
4743 ///            [k0    k2    k1    k3    ]
4744 /// Extended =+[k1    k3    k0    k2    ]
4745 ///            [k0    k2    ]
4746 /// Extracted=+[k1    k3    ]
4747 ///
4748 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4749   EVT VT = N->getValueType(0);
4750   SDLoc DL(N);
4751 
4752   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4753 
4754   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4755   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4756   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4757   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4758   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4759 
4760   if (VT.is64BitVector()) {
4761     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4762     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4763                        DAG.getIntPtrConstant(0, DL));
4764   } else {
4765     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4766                                     DAG.getIntPtrConstant(0, DL));
4767     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4768   }
4769 }
4770 
4771 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4772                           const ARMSubtarget *ST) {
4773   EVT VT = N->getValueType(0);
4774 
4775   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4776   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4777           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4778          "Unexpected type for custom ctpop lowering");
4779 
4780   if (VT.getVectorElementType() == MVT::i32)
4781     return lowerCTPOP32BitElements(N, DAG);
4782   else
4783     return lowerCTPOP16BitElements(N, DAG);
4784 }
4785 
4786 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4787                           const ARMSubtarget *ST) {
4788   EVT VT = N->getValueType(0);
4789   SDLoc dl(N);
4790 
4791   if (!VT.isVector())
4792     return SDValue();
4793 
4794   // Lower vector shifts on NEON to use VSHL.
4795   assert(ST->hasNEON() && "unexpected vector shift");
4796 
4797   // Left shifts translate directly to the vshiftu intrinsic.
4798   if (N->getOpcode() == ISD::SHL)
4799     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4800                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4801                                        MVT::i32),
4802                        N->getOperand(0), N->getOperand(1));
4803 
4804   assert((N->getOpcode() == ISD::SRA ||
4805           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4806 
4807   // NEON uses the same intrinsics for both left and right shifts.  For
4808   // right shifts, the shift amounts are negative, so negate the vector of
4809   // shift amounts.
4810   EVT ShiftVT = N->getOperand(1).getValueType();
4811   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4812                                      getZeroVector(ShiftVT, DAG, dl),
4813                                      N->getOperand(1));
4814   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4815                              Intrinsic::arm_neon_vshifts :
4816                              Intrinsic::arm_neon_vshiftu);
4817   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4818                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4819                      N->getOperand(0), NegatedCount);
4820 }
4821 
4822 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4823                                 const ARMSubtarget *ST) {
4824   EVT VT = N->getValueType(0);
4825   SDLoc dl(N);
4826 
4827   // We can get here for a node like i32 = ISD::SHL i32, i64
4828   if (VT != MVT::i64)
4829     return SDValue();
4830 
4831   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4832          "Unknown shift to lower!");
4833 
4834   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4835   if (!isOneConstant(N->getOperand(1)))
4836     return SDValue();
4837 
4838   // If we are in thumb mode, we don't have RRX.
4839   if (ST->isThumb1Only()) return SDValue();
4840 
4841   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4842   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4843                            DAG.getConstant(0, dl, MVT::i32));
4844   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4845                            DAG.getConstant(1, dl, MVT::i32));
4846 
4847   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4848   // captures the result into a carry flag.
4849   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4850   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4851 
4852   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4853   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4854 
4855   // Merge the pieces into a single i64 value.
4856  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4857 }
4858 
4859 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4860   SDValue TmpOp0, TmpOp1;
4861   bool Invert = false;
4862   bool Swap = false;
4863   unsigned Opc = 0;
4864 
4865   SDValue Op0 = Op.getOperand(0);
4866   SDValue Op1 = Op.getOperand(1);
4867   SDValue CC = Op.getOperand(2);
4868   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4869   EVT VT = Op.getValueType();
4870   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4871   SDLoc dl(Op);
4872 
4873   if (CmpVT.getVectorElementType() == MVT::i64)
4874     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4875     // but it's possible that our operands are 64-bit but our result is 32-bit.
4876     // Bail in this case.
4877     return SDValue();
4878 
4879   if (Op1.getValueType().isFloatingPoint()) {
4880     switch (SetCCOpcode) {
4881     default: llvm_unreachable("Illegal FP comparison");
4882     case ISD::SETUNE:
4883     case ISD::SETNE:  Invert = true; // Fallthrough
4884     case ISD::SETOEQ:
4885     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4886     case ISD::SETOLT:
4887     case ISD::SETLT: Swap = true; // Fallthrough
4888     case ISD::SETOGT:
4889     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4890     case ISD::SETOLE:
4891     case ISD::SETLE:  Swap = true; // Fallthrough
4892     case ISD::SETOGE:
4893     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4894     case ISD::SETUGE: Swap = true; // Fallthrough
4895     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4896     case ISD::SETUGT: Swap = true; // Fallthrough
4897     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4898     case ISD::SETUEQ: Invert = true; // Fallthrough
4899     case ISD::SETONE:
4900       // Expand this to (OLT | OGT).
4901       TmpOp0 = Op0;
4902       TmpOp1 = Op1;
4903       Opc = ISD::OR;
4904       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4905       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4906       break;
4907     case ISD::SETUO: Invert = true; // Fallthrough
4908     case ISD::SETO:
4909       // Expand this to (OLT | OGE).
4910       TmpOp0 = Op0;
4911       TmpOp1 = Op1;
4912       Opc = ISD::OR;
4913       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4914       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4915       break;
4916     }
4917   } else {
4918     // Integer comparisons.
4919     switch (SetCCOpcode) {
4920     default: llvm_unreachable("Illegal integer comparison");
4921     case ISD::SETNE:  Invert = true;
4922     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4923     case ISD::SETLT:  Swap = true;
4924     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4925     case ISD::SETLE:  Swap = true;
4926     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4927     case ISD::SETULT: Swap = true;
4928     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4929     case ISD::SETULE: Swap = true;
4930     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4931     }
4932 
4933     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4934     if (Opc == ARMISD::VCEQ) {
4935 
4936       SDValue AndOp;
4937       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4938         AndOp = Op0;
4939       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4940         AndOp = Op1;
4941 
4942       // Ignore bitconvert.
4943       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4944         AndOp = AndOp.getOperand(0);
4945 
4946       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4947         Opc = ARMISD::VTST;
4948         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4949         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4950         Invert = !Invert;
4951       }
4952     }
4953   }
4954 
4955   if (Swap)
4956     std::swap(Op0, Op1);
4957 
4958   // If one of the operands is a constant vector zero, attempt to fold the
4959   // comparison to a specialized compare-against-zero form.
4960   SDValue SingleOp;
4961   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4962     SingleOp = Op0;
4963   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4964     if (Opc == ARMISD::VCGE)
4965       Opc = ARMISD::VCLEZ;
4966     else if (Opc == ARMISD::VCGT)
4967       Opc = ARMISD::VCLTZ;
4968     SingleOp = Op1;
4969   }
4970 
4971   SDValue Result;
4972   if (SingleOp.getNode()) {
4973     switch (Opc) {
4974     case ARMISD::VCEQ:
4975       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4976     case ARMISD::VCGE:
4977       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4978     case ARMISD::VCLEZ:
4979       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4980     case ARMISD::VCGT:
4981       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4982     case ARMISD::VCLTZ:
4983       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4984     default:
4985       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4986     }
4987   } else {
4988      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4989   }
4990 
4991   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4992 
4993   if (Invert)
4994     Result = DAG.getNOT(dl, Result, VT);
4995 
4996   return Result;
4997 }
4998 
4999 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5000   SDValue LHS = Op.getOperand(0);
5001   SDValue RHS = Op.getOperand(1);
5002   SDValue Carry = Op.getOperand(2);
5003   SDValue Cond = Op.getOperand(3);
5004   SDLoc DL(Op);
5005 
5006   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5007 
5008   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5009   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5010   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5011 
5012   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5013   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5014   SDValue ARMcc = DAG.getConstant(
5015       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5016   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5017   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5018                                    Cmp.getValue(1), SDValue());
5019   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5020                      CCR, Chain.getValue(1));
5021 }
5022 
5023 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5024 /// valid vector constant for a NEON instruction with a "modified immediate"
5025 /// operand (e.g., VMOV).  If so, return the encoded value.
5026 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5027                                  unsigned SplatBitSize, SelectionDAG &DAG,
5028                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5029                                  NEONModImmType type) {
5030   unsigned OpCmode, Imm;
5031 
5032   // SplatBitSize is set to the smallest size that splats the vector, so a
5033   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5034   // immediate instructions others than VMOV do not support the 8-bit encoding
5035   // of a zero vector, and the default encoding of zero is supposed to be the
5036   // 32-bit version.
5037   if (SplatBits == 0)
5038     SplatBitSize = 32;
5039 
5040   switch (SplatBitSize) {
5041   case 8:
5042     if (type != VMOVModImm)
5043       return SDValue();
5044     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5045     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5046     OpCmode = 0xe;
5047     Imm = SplatBits;
5048     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5049     break;
5050 
5051   case 16:
5052     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5053     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5054     if ((SplatBits & ~0xff) == 0) {
5055       // Value = 0x00nn: Op=x, Cmode=100x.
5056       OpCmode = 0x8;
5057       Imm = SplatBits;
5058       break;
5059     }
5060     if ((SplatBits & ~0xff00) == 0) {
5061       // Value = 0xnn00: Op=x, Cmode=101x.
5062       OpCmode = 0xa;
5063       Imm = SplatBits >> 8;
5064       break;
5065     }
5066     return SDValue();
5067 
5068   case 32:
5069     // NEON's 32-bit VMOV supports splat values where:
5070     // * only one byte is nonzero, or
5071     // * the least significant byte is 0xff and the second byte is nonzero, or
5072     // * the least significant 2 bytes are 0xff and the third is nonzero.
5073     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5074     if ((SplatBits & ~0xff) == 0) {
5075       // Value = 0x000000nn: Op=x, Cmode=000x.
5076       OpCmode = 0;
5077       Imm = SplatBits;
5078       break;
5079     }
5080     if ((SplatBits & ~0xff00) == 0) {
5081       // Value = 0x0000nn00: Op=x, Cmode=001x.
5082       OpCmode = 0x2;
5083       Imm = SplatBits >> 8;
5084       break;
5085     }
5086     if ((SplatBits & ~0xff0000) == 0) {
5087       // Value = 0x00nn0000: Op=x, Cmode=010x.
5088       OpCmode = 0x4;
5089       Imm = SplatBits >> 16;
5090       break;
5091     }
5092     if ((SplatBits & ~0xff000000) == 0) {
5093       // Value = 0xnn000000: Op=x, Cmode=011x.
5094       OpCmode = 0x6;
5095       Imm = SplatBits >> 24;
5096       break;
5097     }
5098 
5099     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5100     if (type == OtherModImm) return SDValue();
5101 
5102     if ((SplatBits & ~0xffff) == 0 &&
5103         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5104       // Value = 0x0000nnff: Op=x, Cmode=1100.
5105       OpCmode = 0xc;
5106       Imm = SplatBits >> 8;
5107       break;
5108     }
5109 
5110     if ((SplatBits & ~0xffffff) == 0 &&
5111         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5112       // Value = 0x00nnffff: Op=x, Cmode=1101.
5113       OpCmode = 0xd;
5114       Imm = SplatBits >> 16;
5115       break;
5116     }
5117 
5118     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5119     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5120     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5121     // and fall through here to test for a valid 64-bit splat.  But, then the
5122     // caller would also need to check and handle the change in size.
5123     return SDValue();
5124 
5125   case 64: {
5126     if (type != VMOVModImm)
5127       return SDValue();
5128     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5129     uint64_t BitMask = 0xff;
5130     uint64_t Val = 0;
5131     unsigned ImmMask = 1;
5132     Imm = 0;
5133     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5134       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5135         Val |= BitMask;
5136         Imm |= ImmMask;
5137       } else if ((SplatBits & BitMask) != 0) {
5138         return SDValue();
5139       }
5140       BitMask <<= 8;
5141       ImmMask <<= 1;
5142     }
5143 
5144     if (DAG.getDataLayout().isBigEndian())
5145       // swap higher and lower 32 bit word
5146       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5147 
5148     // Op=1, Cmode=1110.
5149     OpCmode = 0x1e;
5150     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5151     break;
5152   }
5153 
5154   default:
5155     llvm_unreachable("unexpected size for isNEONModifiedImm");
5156   }
5157 
5158   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5159   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5160 }
5161 
5162 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5163                                            const ARMSubtarget *ST) const {
5164   if (!ST->hasVFP3())
5165     return SDValue();
5166 
5167   bool IsDouble = Op.getValueType() == MVT::f64;
5168   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5169 
5170   // Use the default (constant pool) lowering for double constants when we have
5171   // an SP-only FPU
5172   if (IsDouble && Subtarget->isFPOnlySP())
5173     return SDValue();
5174 
5175   // Try splatting with a VMOV.f32...
5176   const APFloat &FPVal = CFP->getValueAPF();
5177   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5178 
5179   if (ImmVal != -1) {
5180     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5181       // We have code in place to select a valid ConstantFP already, no need to
5182       // do any mangling.
5183       return Op;
5184     }
5185 
5186     // It's a float and we are trying to use NEON operations where
5187     // possible. Lower it to a splat followed by an extract.
5188     SDLoc DL(Op);
5189     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5190     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5191                                       NewVal);
5192     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5193                        DAG.getConstant(0, DL, MVT::i32));
5194   }
5195 
5196   // The rest of our options are NEON only, make sure that's allowed before
5197   // proceeding..
5198   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5199     return SDValue();
5200 
5201   EVT VMovVT;
5202   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5203 
5204   // It wouldn't really be worth bothering for doubles except for one very
5205   // important value, which does happen to match: 0.0. So make sure we don't do
5206   // anything stupid.
5207   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5208     return SDValue();
5209 
5210   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5211   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5212                                      VMovVT, false, VMOVModImm);
5213   if (NewVal != SDValue()) {
5214     SDLoc DL(Op);
5215     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5216                                       NewVal);
5217     if (IsDouble)
5218       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5219 
5220     // It's a float: cast and extract a vector element.
5221     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5222                                        VecConstant);
5223     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5224                        DAG.getConstant(0, DL, MVT::i32));
5225   }
5226 
5227   // Finally, try a VMVN.i32
5228   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5229                              false, VMVNModImm);
5230   if (NewVal != SDValue()) {
5231     SDLoc DL(Op);
5232     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5233 
5234     if (IsDouble)
5235       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5236 
5237     // It's a float: cast and extract a vector element.
5238     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5239                                        VecConstant);
5240     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5241                        DAG.getConstant(0, DL, MVT::i32));
5242   }
5243 
5244   return SDValue();
5245 }
5246 
5247 // check if an VEXT instruction can handle the shuffle mask when the
5248 // vector sources of the shuffle are the same.
5249 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5250   unsigned NumElts = VT.getVectorNumElements();
5251 
5252   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5253   if (M[0] < 0)
5254     return false;
5255 
5256   Imm = M[0];
5257 
5258   // If this is a VEXT shuffle, the immediate value is the index of the first
5259   // element.  The other shuffle indices must be the successive elements after
5260   // the first one.
5261   unsigned ExpectedElt = Imm;
5262   for (unsigned i = 1; i < NumElts; ++i) {
5263     // Increment the expected index.  If it wraps around, just follow it
5264     // back to index zero and keep going.
5265     ++ExpectedElt;
5266     if (ExpectedElt == NumElts)
5267       ExpectedElt = 0;
5268 
5269     if (M[i] < 0) continue; // ignore UNDEF indices
5270     if (ExpectedElt != static_cast<unsigned>(M[i]))
5271       return false;
5272   }
5273 
5274   return true;
5275 }
5276 
5277 
5278 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5279                        bool &ReverseVEXT, unsigned &Imm) {
5280   unsigned NumElts = VT.getVectorNumElements();
5281   ReverseVEXT = false;
5282 
5283   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5284   if (M[0] < 0)
5285     return false;
5286 
5287   Imm = M[0];
5288 
5289   // If this is a VEXT shuffle, the immediate value is the index of the first
5290   // element.  The other shuffle indices must be the successive elements after
5291   // the first one.
5292   unsigned ExpectedElt = Imm;
5293   for (unsigned i = 1; i < NumElts; ++i) {
5294     // Increment the expected index.  If it wraps around, it may still be
5295     // a VEXT but the source vectors must be swapped.
5296     ExpectedElt += 1;
5297     if (ExpectedElt == NumElts * 2) {
5298       ExpectedElt = 0;
5299       ReverseVEXT = true;
5300     }
5301 
5302     if (M[i] < 0) continue; // ignore UNDEF indices
5303     if (ExpectedElt != static_cast<unsigned>(M[i]))
5304       return false;
5305   }
5306 
5307   // Adjust the index value if the source operands will be swapped.
5308   if (ReverseVEXT)
5309     Imm -= NumElts;
5310 
5311   return true;
5312 }
5313 
5314 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5315 /// instruction with the specified blocksize.  (The order of the elements
5316 /// within each block of the vector is reversed.)
5317 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5318   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5319          "Only possible block sizes for VREV are: 16, 32, 64");
5320 
5321   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5322   if (EltSz == 64)
5323     return false;
5324 
5325   unsigned NumElts = VT.getVectorNumElements();
5326   unsigned BlockElts = M[0] + 1;
5327   // If the first shuffle index is UNDEF, be optimistic.
5328   if (M[0] < 0)
5329     BlockElts = BlockSize / EltSz;
5330 
5331   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5332     return false;
5333 
5334   for (unsigned i = 0; i < NumElts; ++i) {
5335     if (M[i] < 0) continue; // ignore UNDEF indices
5336     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5337       return false;
5338   }
5339 
5340   return true;
5341 }
5342 
5343 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5344   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5345   // range, then 0 is placed into the resulting vector. So pretty much any mask
5346   // of 8 elements can work here.
5347   return VT == MVT::v8i8 && M.size() == 8;
5348 }
5349 
5350 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5351 // checking that pairs of elements in the shuffle mask represent the same index
5352 // in each vector, incrementing the expected index by 2 at each step.
5353 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5354 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5355 //  v2={e,f,g,h}
5356 // WhichResult gives the offset for each element in the mask based on which
5357 // of the two results it belongs to.
5358 //
5359 // The transpose can be represented either as:
5360 // result1 = shufflevector v1, v2, result1_shuffle_mask
5361 // result2 = shufflevector v1, v2, result2_shuffle_mask
5362 // where v1/v2 and the shuffle masks have the same number of elements
5363 // (here WhichResult (see below) indicates which result is being checked)
5364 //
5365 // or as:
5366 // results = shufflevector v1, v2, shuffle_mask
5367 // where both results are returned in one vector and the shuffle mask has twice
5368 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5369 // want to check the low half and high half of the shuffle mask as if it were
5370 // the other case
5371 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5372   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5373   if (EltSz == 64)
5374     return false;
5375 
5376   unsigned NumElts = VT.getVectorNumElements();
5377   if (M.size() != NumElts && M.size() != NumElts*2)
5378     return false;
5379 
5380   // If the mask is twice as long as the input vector then we need to check the
5381   // upper and lower parts of the mask with a matching value for WhichResult
5382   // FIXME: A mask with only even values will be rejected in case the first
5383   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5384   // M[0] is used to determine WhichResult
5385   for (unsigned i = 0; i < M.size(); i += NumElts) {
5386     if (M.size() == NumElts * 2)
5387       WhichResult = i / NumElts;
5388     else
5389       WhichResult = M[i] == 0 ? 0 : 1;
5390     for (unsigned j = 0; j < NumElts; j += 2) {
5391       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5392           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5393         return false;
5394     }
5395   }
5396 
5397   if (M.size() == NumElts*2)
5398     WhichResult = 0;
5399 
5400   return true;
5401 }
5402 
5403 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5404 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5405 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5406 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5407   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5408   if (EltSz == 64)
5409     return false;
5410 
5411   unsigned NumElts = VT.getVectorNumElements();
5412   if (M.size() != NumElts && M.size() != NumElts*2)
5413     return false;
5414 
5415   for (unsigned i = 0; i < M.size(); i += NumElts) {
5416     if (M.size() == NumElts * 2)
5417       WhichResult = i / NumElts;
5418     else
5419       WhichResult = M[i] == 0 ? 0 : 1;
5420     for (unsigned j = 0; j < NumElts; j += 2) {
5421       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5422           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5423         return false;
5424     }
5425   }
5426 
5427   if (M.size() == NumElts*2)
5428     WhichResult = 0;
5429 
5430   return true;
5431 }
5432 
5433 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5434 // that the mask elements are either all even and in steps of size 2 or all odd
5435 // and in steps of size 2.
5436 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5437 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5438 //  v2={e,f,g,h}
5439 // Requires similar checks to that of isVTRNMask with
5440 // respect the how results are returned.
5441 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5442   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5443   if (EltSz == 64)
5444     return false;
5445 
5446   unsigned NumElts = VT.getVectorNumElements();
5447   if (M.size() != NumElts && M.size() != NumElts*2)
5448     return false;
5449 
5450   for (unsigned i = 0; i < M.size(); i += NumElts) {
5451     WhichResult = M[i] == 0 ? 0 : 1;
5452     for (unsigned j = 0; j < NumElts; ++j) {
5453       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5454         return false;
5455     }
5456   }
5457 
5458   if (M.size() == NumElts*2)
5459     WhichResult = 0;
5460 
5461   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5462   if (VT.is64BitVector() && EltSz == 32)
5463     return false;
5464 
5465   return true;
5466 }
5467 
5468 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5469 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5470 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5471 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5472   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5473   if (EltSz == 64)
5474     return false;
5475 
5476   unsigned NumElts = VT.getVectorNumElements();
5477   if (M.size() != NumElts && M.size() != NumElts*2)
5478     return false;
5479 
5480   unsigned Half = NumElts / 2;
5481   for (unsigned i = 0; i < M.size(); i += NumElts) {
5482     WhichResult = M[i] == 0 ? 0 : 1;
5483     for (unsigned j = 0; j < NumElts; j += Half) {
5484       unsigned Idx = WhichResult;
5485       for (unsigned k = 0; k < Half; ++k) {
5486         int MIdx = M[i + j + k];
5487         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5488           return false;
5489         Idx += 2;
5490       }
5491     }
5492   }
5493 
5494   if (M.size() == NumElts*2)
5495     WhichResult = 0;
5496 
5497   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5498   if (VT.is64BitVector() && EltSz == 32)
5499     return false;
5500 
5501   return true;
5502 }
5503 
5504 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5505 // that pairs of elements of the shufflemask represent the same index in each
5506 // vector incrementing sequentially through the vectors.
5507 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5508 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5509 //  v2={e,f,g,h}
5510 // Requires similar checks to that of isVTRNMask with respect the how results
5511 // are returned.
5512 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5513   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5514   if (EltSz == 64)
5515     return false;
5516 
5517   unsigned NumElts = VT.getVectorNumElements();
5518   if (M.size() != NumElts && M.size() != NumElts*2)
5519     return false;
5520 
5521   for (unsigned i = 0; i < M.size(); i += NumElts) {
5522     WhichResult = M[i] == 0 ? 0 : 1;
5523     unsigned Idx = WhichResult * NumElts / 2;
5524     for (unsigned j = 0; j < NumElts; j += 2) {
5525       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5526           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5527         return false;
5528       Idx += 1;
5529     }
5530   }
5531 
5532   if (M.size() == NumElts*2)
5533     WhichResult = 0;
5534 
5535   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5536   if (VT.is64BitVector() && EltSz == 32)
5537     return false;
5538 
5539   return true;
5540 }
5541 
5542 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5543 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5544 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5545 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5546   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5547   if (EltSz == 64)
5548     return false;
5549 
5550   unsigned NumElts = VT.getVectorNumElements();
5551   if (M.size() != NumElts && M.size() != NumElts*2)
5552     return false;
5553 
5554   for (unsigned i = 0; i < M.size(); i += NumElts) {
5555     WhichResult = M[i] == 0 ? 0 : 1;
5556     unsigned Idx = WhichResult * NumElts / 2;
5557     for (unsigned j = 0; j < NumElts; j += 2) {
5558       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5559           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5560         return false;
5561       Idx += 1;
5562     }
5563   }
5564 
5565   if (M.size() == NumElts*2)
5566     WhichResult = 0;
5567 
5568   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5569   if (VT.is64BitVector() && EltSz == 32)
5570     return false;
5571 
5572   return true;
5573 }
5574 
5575 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5576 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5577 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5578                                            unsigned &WhichResult,
5579                                            bool &isV_UNDEF) {
5580   isV_UNDEF = false;
5581   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5582     return ARMISD::VTRN;
5583   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5584     return ARMISD::VUZP;
5585   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5586     return ARMISD::VZIP;
5587 
5588   isV_UNDEF = true;
5589   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5590     return ARMISD::VTRN;
5591   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5592     return ARMISD::VUZP;
5593   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5594     return ARMISD::VZIP;
5595 
5596   return 0;
5597 }
5598 
5599 /// \return true if this is a reverse operation on an vector.
5600 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5601   unsigned NumElts = VT.getVectorNumElements();
5602   // Make sure the mask has the right size.
5603   if (NumElts != M.size())
5604       return false;
5605 
5606   // Look for <15, ..., 3, -1, 1, 0>.
5607   for (unsigned i = 0; i != NumElts; ++i)
5608     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5609       return false;
5610 
5611   return true;
5612 }
5613 
5614 // If N is an integer constant that can be moved into a register in one
5615 // instruction, return an SDValue of such a constant (will become a MOV
5616 // instruction).  Otherwise return null.
5617 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5618                                      const ARMSubtarget *ST, const SDLoc &dl) {
5619   uint64_t Val;
5620   if (!isa<ConstantSDNode>(N))
5621     return SDValue();
5622   Val = cast<ConstantSDNode>(N)->getZExtValue();
5623 
5624   if (ST->isThumb1Only()) {
5625     if (Val <= 255 || ~Val <= 255)
5626       return DAG.getConstant(Val, dl, MVT::i32);
5627   } else {
5628     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5629       return DAG.getConstant(Val, dl, MVT::i32);
5630   }
5631   return SDValue();
5632 }
5633 
5634 // If this is a case we can't handle, return null and let the default
5635 // expansion code take care of it.
5636 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5637                                              const ARMSubtarget *ST) const {
5638   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5639   SDLoc dl(Op);
5640   EVT VT = Op.getValueType();
5641 
5642   APInt SplatBits, SplatUndef;
5643   unsigned SplatBitSize;
5644   bool HasAnyUndefs;
5645   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5646     if (SplatBitSize <= 64) {
5647       // Check if an immediate VMOV works.
5648       EVT VmovVT;
5649       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5650                                       SplatUndef.getZExtValue(), SplatBitSize,
5651                                       DAG, dl, VmovVT, VT.is128BitVector(),
5652                                       VMOVModImm);
5653       if (Val.getNode()) {
5654         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5655         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5656       }
5657 
5658       // Try an immediate VMVN.
5659       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5660       Val = isNEONModifiedImm(NegatedImm,
5661                                       SplatUndef.getZExtValue(), SplatBitSize,
5662                                       DAG, dl, VmovVT, VT.is128BitVector(),
5663                                       VMVNModImm);
5664       if (Val.getNode()) {
5665         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5666         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5667       }
5668 
5669       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5670       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5671         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5672         if (ImmVal != -1) {
5673           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5674           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5675         }
5676       }
5677     }
5678   }
5679 
5680   // Scan through the operands to see if only one value is used.
5681   //
5682   // As an optimisation, even if more than one value is used it may be more
5683   // profitable to splat with one value then change some lanes.
5684   //
5685   // Heuristically we decide to do this if the vector has a "dominant" value,
5686   // defined as splatted to more than half of the lanes.
5687   unsigned NumElts = VT.getVectorNumElements();
5688   bool isOnlyLowElement = true;
5689   bool usesOnlyOneValue = true;
5690   bool hasDominantValue = false;
5691   bool isConstant = true;
5692 
5693   // Map of the number of times a particular SDValue appears in the
5694   // element list.
5695   DenseMap<SDValue, unsigned> ValueCounts;
5696   SDValue Value;
5697   for (unsigned i = 0; i < NumElts; ++i) {
5698     SDValue V = Op.getOperand(i);
5699     if (V.isUndef())
5700       continue;
5701     if (i > 0)
5702       isOnlyLowElement = false;
5703     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5704       isConstant = false;
5705 
5706     ValueCounts.insert(std::make_pair(V, 0));
5707     unsigned &Count = ValueCounts[V];
5708 
5709     // Is this value dominant? (takes up more than half of the lanes)
5710     if (++Count > (NumElts / 2)) {
5711       hasDominantValue = true;
5712       Value = V;
5713     }
5714   }
5715   if (ValueCounts.size() != 1)
5716     usesOnlyOneValue = false;
5717   if (!Value.getNode() && ValueCounts.size() > 0)
5718     Value = ValueCounts.begin()->first;
5719 
5720   if (ValueCounts.size() == 0)
5721     return DAG.getUNDEF(VT);
5722 
5723   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5724   // Keep going if we are hitting this case.
5725   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5726     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5727 
5728   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5729 
5730   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5731   // i32 and try again.
5732   if (hasDominantValue && EltSize <= 32) {
5733     if (!isConstant) {
5734       SDValue N;
5735 
5736       // If we are VDUPing a value that comes directly from a vector, that will
5737       // cause an unnecessary move to and from a GPR, where instead we could
5738       // just use VDUPLANE. We can only do this if the lane being extracted
5739       // is at a constant index, as the VDUP from lane instructions only have
5740       // constant-index forms.
5741       ConstantSDNode *constIndex;
5742       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5743           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5744         // We need to create a new undef vector to use for the VDUPLANE if the
5745         // size of the vector from which we get the value is different than the
5746         // size of the vector that we need to create. We will insert the element
5747         // such that the register coalescer will remove unnecessary copies.
5748         if (VT != Value->getOperand(0).getValueType()) {
5749           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5750                              VT.getVectorNumElements();
5751           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5752                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5753                         Value, DAG.getConstant(index, dl, MVT::i32)),
5754                            DAG.getConstant(index, dl, MVT::i32));
5755         } else
5756           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5757                         Value->getOperand(0), Value->getOperand(1));
5758       } else
5759         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5760 
5761       if (!usesOnlyOneValue) {
5762         // The dominant value was splatted as 'N', but we now have to insert
5763         // all differing elements.
5764         for (unsigned I = 0; I < NumElts; ++I) {
5765           if (Op.getOperand(I) == Value)
5766             continue;
5767           SmallVector<SDValue, 3> Ops;
5768           Ops.push_back(N);
5769           Ops.push_back(Op.getOperand(I));
5770           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5771           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5772         }
5773       }
5774       return N;
5775     }
5776     if (VT.getVectorElementType().isFloatingPoint()) {
5777       SmallVector<SDValue, 8> Ops;
5778       for (unsigned i = 0; i < NumElts; ++i)
5779         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5780                                   Op.getOperand(i)));
5781       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5782       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
5783       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5784       if (Val.getNode())
5785         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5786     }
5787     if (usesOnlyOneValue) {
5788       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5789       if (isConstant && Val.getNode())
5790         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5791     }
5792   }
5793 
5794   // If all elements are constants and the case above didn't get hit, fall back
5795   // to the default expansion, which will generate a load from the constant
5796   // pool.
5797   if (isConstant)
5798     return SDValue();
5799 
5800   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5801   if (NumElts >= 4) {
5802     SDValue shuffle = ReconstructShuffle(Op, DAG);
5803     if (shuffle != SDValue())
5804       return shuffle;
5805   }
5806 
5807   // Vectors with 32- or 64-bit elements can be built by directly assigning
5808   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5809   // will be legalized.
5810   if (EltSize >= 32) {
5811     // Do the expansion with floating-point types, since that is what the VFP
5812     // registers are defined to use, and since i64 is not legal.
5813     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5814     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5815     SmallVector<SDValue, 8> Ops;
5816     for (unsigned i = 0; i < NumElts; ++i)
5817       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5818     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5819     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5820   }
5821 
5822   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5823   // know the default expansion would otherwise fall back on something even
5824   // worse. For a vector with one or two non-undef values, that's
5825   // scalar_to_vector for the elements followed by a shuffle (provided the
5826   // shuffle is valid for the target) and materialization element by element
5827   // on the stack followed by a load for everything else.
5828   if (!isConstant && !usesOnlyOneValue) {
5829     SDValue Vec = DAG.getUNDEF(VT);
5830     for (unsigned i = 0 ; i < NumElts; ++i) {
5831       SDValue V = Op.getOperand(i);
5832       if (V.isUndef())
5833         continue;
5834       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5835       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5836     }
5837     return Vec;
5838   }
5839 
5840   return SDValue();
5841 }
5842 
5843 // Gather data to see if the operation can be modelled as a
5844 // shuffle in combination with VEXTs.
5845 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5846                                               SelectionDAG &DAG) const {
5847   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5848   SDLoc dl(Op);
5849   EVT VT = Op.getValueType();
5850   unsigned NumElts = VT.getVectorNumElements();
5851 
5852   struct ShuffleSourceInfo {
5853     SDValue Vec;
5854     unsigned MinElt;
5855     unsigned MaxElt;
5856 
5857     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5858     // be compatible with the shuffle we intend to construct. As a result
5859     // ShuffleVec will be some sliding window into the original Vec.
5860     SDValue ShuffleVec;
5861 
5862     // Code should guarantee that element i in Vec starts at element "WindowBase
5863     // + i * WindowScale in ShuffleVec".
5864     int WindowBase;
5865     int WindowScale;
5866 
5867     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5868     ShuffleSourceInfo(SDValue Vec)
5869         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5870           WindowScale(1) {}
5871   };
5872 
5873   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5874   // node.
5875   SmallVector<ShuffleSourceInfo, 2> Sources;
5876   for (unsigned i = 0; i < NumElts; ++i) {
5877     SDValue V = Op.getOperand(i);
5878     if (V.isUndef())
5879       continue;
5880     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5881       // A shuffle can only come from building a vector from various
5882       // elements of other vectors.
5883       return SDValue();
5884     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5885       // Furthermore, shuffles require a constant mask, whereas extractelts
5886       // accept variable indices.
5887       return SDValue();
5888     }
5889 
5890     // Add this element source to the list if it's not already there.
5891     SDValue SourceVec = V.getOperand(0);
5892     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5893     if (Source == Sources.end())
5894       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5895 
5896     // Update the minimum and maximum lane number seen.
5897     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5898     Source->MinElt = std::min(Source->MinElt, EltNo);
5899     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5900   }
5901 
5902   // Currently only do something sane when at most two source vectors
5903   // are involved.
5904   if (Sources.size() > 2)
5905     return SDValue();
5906 
5907   // Find out the smallest element size among result and two sources, and use
5908   // it as element size to build the shuffle_vector.
5909   EVT SmallestEltTy = VT.getVectorElementType();
5910   for (auto &Source : Sources) {
5911     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5912     if (SrcEltTy.bitsLT(SmallestEltTy))
5913       SmallestEltTy = SrcEltTy;
5914   }
5915   unsigned ResMultiplier =
5916       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5917   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5918   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5919 
5920   // If the source vector is too wide or too narrow, we may nevertheless be able
5921   // to construct a compatible shuffle either by concatenating it with UNDEF or
5922   // extracting a suitable range of elements.
5923   for (auto &Src : Sources) {
5924     EVT SrcVT = Src.ShuffleVec.getValueType();
5925 
5926     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5927       continue;
5928 
5929     // This stage of the search produces a source with the same element type as
5930     // the original, but with a total width matching the BUILD_VECTOR output.
5931     EVT EltVT = SrcVT.getVectorElementType();
5932     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5933     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5934 
5935     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5936       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5937         return SDValue();
5938       // We can pad out the smaller vector for free, so if it's part of a
5939       // shuffle...
5940       Src.ShuffleVec =
5941           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5942                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5943       continue;
5944     }
5945 
5946     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5947       return SDValue();
5948 
5949     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5950       // Span too large for a VEXT to cope
5951       return SDValue();
5952     }
5953 
5954     if (Src.MinElt >= NumSrcElts) {
5955       // The extraction can just take the second half
5956       Src.ShuffleVec =
5957           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5958                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5959       Src.WindowBase = -NumSrcElts;
5960     } else if (Src.MaxElt < NumSrcElts) {
5961       // The extraction can just take the first half
5962       Src.ShuffleVec =
5963           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5964                       DAG.getConstant(0, dl, MVT::i32));
5965     } else {
5966       // An actual VEXT is needed
5967       SDValue VEXTSrc1 =
5968           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5969                       DAG.getConstant(0, dl, MVT::i32));
5970       SDValue VEXTSrc2 =
5971           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5972                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5973 
5974       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5975                                    VEXTSrc2,
5976                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5977       Src.WindowBase = -Src.MinElt;
5978     }
5979   }
5980 
5981   // Another possible incompatibility occurs from the vector element types. We
5982   // can fix this by bitcasting the source vectors to the same type we intend
5983   // for the shuffle.
5984   for (auto &Src : Sources) {
5985     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5986     if (SrcEltTy == SmallestEltTy)
5987       continue;
5988     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5989     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5990     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5991     Src.WindowBase *= Src.WindowScale;
5992   }
5993 
5994   // Final sanity check before we try to actually produce a shuffle.
5995   DEBUG(
5996     for (auto Src : Sources)
5997       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5998   );
5999 
6000   // The stars all align, our next step is to produce the mask for the shuffle.
6001   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6002   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
6003   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6004     SDValue Entry = Op.getOperand(i);
6005     if (Entry.isUndef())
6006       continue;
6007 
6008     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
6009     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6010 
6011     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6012     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6013     // segment.
6014     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6015     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6016                                VT.getVectorElementType().getSizeInBits());
6017     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6018 
6019     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6020     // starting at the appropriate offset.
6021     int *LaneMask = &Mask[i * ResMultiplier];
6022 
6023     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6024     ExtractBase += NumElts * (Src - Sources.begin());
6025     for (int j = 0; j < LanesDefined; ++j)
6026       LaneMask[j] = ExtractBase + j;
6027   }
6028 
6029   // Final check before we try to produce nonsense...
6030   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6031     return SDValue();
6032 
6033   // We can't handle more than two sources. This should have already
6034   // been checked before this point.
6035   assert(Sources.size() <= 2 && "Too many sources!");
6036 
6037   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6038   for (unsigned i = 0; i < Sources.size(); ++i)
6039     ShuffleOps[i] = Sources[i].ShuffleVec;
6040 
6041   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6042                                          ShuffleOps[1], Mask);
6043   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6044 }
6045 
6046 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6047 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6048 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6049 /// are assumed to be legal.
6050 bool
6051 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6052                                       EVT VT) const {
6053   if (VT.getVectorNumElements() == 4 &&
6054       (VT.is128BitVector() || VT.is64BitVector())) {
6055     unsigned PFIndexes[4];
6056     for (unsigned i = 0; i != 4; ++i) {
6057       if (M[i] < 0)
6058         PFIndexes[i] = 8;
6059       else
6060         PFIndexes[i] = M[i];
6061     }
6062 
6063     // Compute the index in the perfect shuffle table.
6064     unsigned PFTableIndex =
6065       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6066     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6067     unsigned Cost = (PFEntry >> 30);
6068 
6069     if (Cost <= 4)
6070       return true;
6071   }
6072 
6073   bool ReverseVEXT, isV_UNDEF;
6074   unsigned Imm, WhichResult;
6075 
6076   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6077   return (EltSize >= 32 ||
6078           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6079           isVREVMask(M, VT, 64) ||
6080           isVREVMask(M, VT, 32) ||
6081           isVREVMask(M, VT, 16) ||
6082           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6083           isVTBLMask(M, VT) ||
6084           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6085           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6086 }
6087 
6088 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6089 /// the specified operations to build the shuffle.
6090 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6091                                       SDValue RHS, SelectionDAG &DAG,
6092                                       const SDLoc &dl) {
6093   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6094   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6095   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6096 
6097   enum {
6098     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6099     OP_VREV,
6100     OP_VDUP0,
6101     OP_VDUP1,
6102     OP_VDUP2,
6103     OP_VDUP3,
6104     OP_VEXT1,
6105     OP_VEXT2,
6106     OP_VEXT3,
6107     OP_VUZPL, // VUZP, left result
6108     OP_VUZPR, // VUZP, right result
6109     OP_VZIPL, // VZIP, left result
6110     OP_VZIPR, // VZIP, right result
6111     OP_VTRNL, // VTRN, left result
6112     OP_VTRNR  // VTRN, right result
6113   };
6114 
6115   if (OpNum == OP_COPY) {
6116     if (LHSID == (1*9+2)*9+3) return LHS;
6117     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6118     return RHS;
6119   }
6120 
6121   SDValue OpLHS, OpRHS;
6122   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6123   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6124   EVT VT = OpLHS.getValueType();
6125 
6126   switch (OpNum) {
6127   default: llvm_unreachable("Unknown shuffle opcode!");
6128   case OP_VREV:
6129     // VREV divides the vector in half and swaps within the half.
6130     if (VT.getVectorElementType() == MVT::i32 ||
6131         VT.getVectorElementType() == MVT::f32)
6132       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6133     // vrev <4 x i16> -> VREV32
6134     if (VT.getVectorElementType() == MVT::i16)
6135       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6136     // vrev <4 x i8> -> VREV16
6137     assert(VT.getVectorElementType() == MVT::i8);
6138     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6139   case OP_VDUP0:
6140   case OP_VDUP1:
6141   case OP_VDUP2:
6142   case OP_VDUP3:
6143     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6144                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6145   case OP_VEXT1:
6146   case OP_VEXT2:
6147   case OP_VEXT3:
6148     return DAG.getNode(ARMISD::VEXT, dl, VT,
6149                        OpLHS, OpRHS,
6150                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6151   case OP_VUZPL:
6152   case OP_VUZPR:
6153     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6154                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6155   case OP_VZIPL:
6156   case OP_VZIPR:
6157     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6158                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6159   case OP_VTRNL:
6160   case OP_VTRNR:
6161     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6162                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6163   }
6164 }
6165 
6166 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6167                                        ArrayRef<int> ShuffleMask,
6168                                        SelectionDAG &DAG) {
6169   // Check to see if we can use the VTBL instruction.
6170   SDValue V1 = Op.getOperand(0);
6171   SDValue V2 = Op.getOperand(1);
6172   SDLoc DL(Op);
6173 
6174   SmallVector<SDValue, 8> VTBLMask;
6175   for (ArrayRef<int>::iterator
6176          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6177     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6178 
6179   if (V2.getNode()->isUndef())
6180     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6181                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6182 
6183   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6184                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6185 }
6186 
6187 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6188                                                       SelectionDAG &DAG) {
6189   SDLoc DL(Op);
6190   SDValue OpLHS = Op.getOperand(0);
6191   EVT VT = OpLHS.getValueType();
6192 
6193   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6194          "Expect an v8i16/v16i8 type");
6195   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6196   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6197   // extract the first 8 bytes into the top double word and the last 8 bytes
6198   // into the bottom double word. The v8i16 case is similar.
6199   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6200   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6201                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6202 }
6203 
6204 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6205   SDValue V1 = Op.getOperand(0);
6206   SDValue V2 = Op.getOperand(1);
6207   SDLoc dl(Op);
6208   EVT VT = Op.getValueType();
6209   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6210 
6211   // Convert shuffles that are directly supported on NEON to target-specific
6212   // DAG nodes, instead of keeping them as shuffles and matching them again
6213   // during code selection.  This is more efficient and avoids the possibility
6214   // of inconsistencies between legalization and selection.
6215   // FIXME: floating-point vectors should be canonicalized to integer vectors
6216   // of the same time so that they get CSEd properly.
6217   ArrayRef<int> ShuffleMask = SVN->getMask();
6218 
6219   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6220   if (EltSize <= 32) {
6221     if (SVN->isSplat()) {
6222       int Lane = SVN->getSplatIndex();
6223       // If this is undef splat, generate it via "just" vdup, if possible.
6224       if (Lane == -1) Lane = 0;
6225 
6226       // Test if V1 is a SCALAR_TO_VECTOR.
6227       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6228         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6229       }
6230       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6231       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6232       // reaches it).
6233       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6234           !isa<ConstantSDNode>(V1.getOperand(0))) {
6235         bool IsScalarToVector = true;
6236         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6237           if (!V1.getOperand(i).isUndef()) {
6238             IsScalarToVector = false;
6239             break;
6240           }
6241         if (IsScalarToVector)
6242           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6243       }
6244       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6245                          DAG.getConstant(Lane, dl, MVT::i32));
6246     }
6247 
6248     bool ReverseVEXT;
6249     unsigned Imm;
6250     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6251       if (ReverseVEXT)
6252         std::swap(V1, V2);
6253       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6254                          DAG.getConstant(Imm, dl, MVT::i32));
6255     }
6256 
6257     if (isVREVMask(ShuffleMask, VT, 64))
6258       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6259     if (isVREVMask(ShuffleMask, VT, 32))
6260       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6261     if (isVREVMask(ShuffleMask, VT, 16))
6262       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6263 
6264     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6265       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6266                          DAG.getConstant(Imm, dl, MVT::i32));
6267     }
6268 
6269     // Check for Neon shuffles that modify both input vectors in place.
6270     // If both results are used, i.e., if there are two shuffles with the same
6271     // source operands and with masks corresponding to both results of one of
6272     // these operations, DAG memoization will ensure that a single node is
6273     // used for both shuffles.
6274     unsigned WhichResult;
6275     bool isV_UNDEF;
6276     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6277             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6278       if (isV_UNDEF)
6279         V2 = V1;
6280       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6281           .getValue(WhichResult);
6282     }
6283 
6284     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6285     // shuffles that produce a result larger than their operands with:
6286     //   shuffle(concat(v1, undef), concat(v2, undef))
6287     // ->
6288     //   shuffle(concat(v1, v2), undef)
6289     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6290     //
6291     // This is useful in the general case, but there are special cases where
6292     // native shuffles produce larger results: the two-result ops.
6293     //
6294     // Look through the concat when lowering them:
6295     //   shuffle(concat(v1, v2), undef)
6296     // ->
6297     //   concat(VZIP(v1, v2):0, :1)
6298     //
6299     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6300       SDValue SubV1 = V1->getOperand(0);
6301       SDValue SubV2 = V1->getOperand(1);
6302       EVT SubVT = SubV1.getValueType();
6303 
6304       // We expect these to have been canonicalized to -1.
6305       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6306         return i < (int)VT.getVectorNumElements();
6307       }) && "Unexpected shuffle index into UNDEF operand!");
6308 
6309       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6310               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6311         if (isV_UNDEF)
6312           SubV2 = SubV1;
6313         assert((WhichResult == 0) &&
6314                "In-place shuffle of concat can only have one result!");
6315         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6316                                   SubV1, SubV2);
6317         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6318                            Res.getValue(1));
6319       }
6320     }
6321   }
6322 
6323   // If the shuffle is not directly supported and it has 4 elements, use
6324   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6325   unsigned NumElts = VT.getVectorNumElements();
6326   if (NumElts == 4) {
6327     unsigned PFIndexes[4];
6328     for (unsigned i = 0; i != 4; ++i) {
6329       if (ShuffleMask[i] < 0)
6330         PFIndexes[i] = 8;
6331       else
6332         PFIndexes[i] = ShuffleMask[i];
6333     }
6334 
6335     // Compute the index in the perfect shuffle table.
6336     unsigned PFTableIndex =
6337       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6338     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6339     unsigned Cost = (PFEntry >> 30);
6340 
6341     if (Cost <= 4)
6342       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6343   }
6344 
6345   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6346   if (EltSize >= 32) {
6347     // Do the expansion with floating-point types, since that is what the VFP
6348     // registers are defined to use, and since i64 is not legal.
6349     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6350     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6351     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6352     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6353     SmallVector<SDValue, 8> Ops;
6354     for (unsigned i = 0; i < NumElts; ++i) {
6355       if (ShuffleMask[i] < 0)
6356         Ops.push_back(DAG.getUNDEF(EltVT));
6357       else
6358         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6359                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6360                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6361                                                   dl, MVT::i32)));
6362     }
6363     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6364     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6365   }
6366 
6367   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6368     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6369 
6370   if (VT == MVT::v8i8)
6371     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6372       return NewOp;
6373 
6374   return SDValue();
6375 }
6376 
6377 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6378   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6379   SDValue Lane = Op.getOperand(2);
6380   if (!isa<ConstantSDNode>(Lane))
6381     return SDValue();
6382 
6383   return Op;
6384 }
6385 
6386 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6387   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6388   SDValue Lane = Op.getOperand(1);
6389   if (!isa<ConstantSDNode>(Lane))
6390     return SDValue();
6391 
6392   SDValue Vec = Op.getOperand(0);
6393   if (Op.getValueType() == MVT::i32 &&
6394       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6395     SDLoc dl(Op);
6396     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6397   }
6398 
6399   return Op;
6400 }
6401 
6402 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6403   // The only time a CONCAT_VECTORS operation can have legal types is when
6404   // two 64-bit vectors are concatenated to a 128-bit vector.
6405   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6406          "unexpected CONCAT_VECTORS");
6407   SDLoc dl(Op);
6408   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6409   SDValue Op0 = Op.getOperand(0);
6410   SDValue Op1 = Op.getOperand(1);
6411   if (!Op0.isUndef())
6412     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6413                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6414                       DAG.getIntPtrConstant(0, dl));
6415   if (!Op1.isUndef())
6416     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6417                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6418                       DAG.getIntPtrConstant(1, dl));
6419   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6420 }
6421 
6422 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6423 /// element has been zero/sign-extended, depending on the isSigned parameter,
6424 /// from an integer type half its size.
6425 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6426                                    bool isSigned) {
6427   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6428   EVT VT = N->getValueType(0);
6429   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6430     SDNode *BVN = N->getOperand(0).getNode();
6431     if (BVN->getValueType(0) != MVT::v4i32 ||
6432         BVN->getOpcode() != ISD::BUILD_VECTOR)
6433       return false;
6434     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6435     unsigned HiElt = 1 - LoElt;
6436     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6437     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6438     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6439     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6440     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6441       return false;
6442     if (isSigned) {
6443       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6444           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6445         return true;
6446     } else {
6447       if (Hi0->isNullValue() && Hi1->isNullValue())
6448         return true;
6449     }
6450     return false;
6451   }
6452 
6453   if (N->getOpcode() != ISD::BUILD_VECTOR)
6454     return false;
6455 
6456   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6457     SDNode *Elt = N->getOperand(i).getNode();
6458     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6459       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6460       unsigned HalfSize = EltSize / 2;
6461       if (isSigned) {
6462         if (!isIntN(HalfSize, C->getSExtValue()))
6463           return false;
6464       } else {
6465         if (!isUIntN(HalfSize, C->getZExtValue()))
6466           return false;
6467       }
6468       continue;
6469     }
6470     return false;
6471   }
6472 
6473   return true;
6474 }
6475 
6476 /// isSignExtended - Check if a node is a vector value that is sign-extended
6477 /// or a constant BUILD_VECTOR with sign-extended elements.
6478 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6479   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6480     return true;
6481   if (isExtendedBUILD_VECTOR(N, DAG, true))
6482     return true;
6483   return false;
6484 }
6485 
6486 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6487 /// or a constant BUILD_VECTOR with zero-extended elements.
6488 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6489   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6490     return true;
6491   if (isExtendedBUILD_VECTOR(N, DAG, false))
6492     return true;
6493   return false;
6494 }
6495 
6496 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6497   if (OrigVT.getSizeInBits() >= 64)
6498     return OrigVT;
6499 
6500   assert(OrigVT.isSimple() && "Expecting a simple value type");
6501 
6502   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6503   switch (OrigSimpleTy) {
6504   default: llvm_unreachable("Unexpected Vector Type");
6505   case MVT::v2i8:
6506   case MVT::v2i16:
6507      return MVT::v2i32;
6508   case MVT::v4i8:
6509     return  MVT::v4i16;
6510   }
6511 }
6512 
6513 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6514 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6515 /// We insert the required extension here to get the vector to fill a D register.
6516 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6517                                             const EVT &OrigTy,
6518                                             const EVT &ExtTy,
6519                                             unsigned ExtOpcode) {
6520   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6521   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6522   // 64-bits we need to insert a new extension so that it will be 64-bits.
6523   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6524   if (OrigTy.getSizeInBits() >= 64)
6525     return N;
6526 
6527   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6528   EVT NewVT = getExtensionTo64Bits(OrigTy);
6529 
6530   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6531 }
6532 
6533 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6534 /// does not do any sign/zero extension. If the original vector is less
6535 /// than 64 bits, an appropriate extension will be added after the load to
6536 /// reach a total size of 64 bits. We have to add the extension separately
6537 /// because ARM does not have a sign/zero extending load for vectors.
6538 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6539   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6540 
6541   // The load already has the right type.
6542   if (ExtendedTy == LD->getMemoryVT())
6543     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6544                        LD->getBasePtr(), LD->getPointerInfo(),
6545                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6546 
6547   // We need to create a zextload/sextload. We cannot just create a load
6548   // followed by a zext/zext node because LowerMUL is also run during normal
6549   // operation legalization where we can't create illegal types.
6550   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6551                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6552                         LD->getMemoryVT(), LD->getAlignment(),
6553                         LD->getMemOperand()->getFlags());
6554 }
6555 
6556 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6557 /// extending load, or BUILD_VECTOR with extended elements, return the
6558 /// unextended value. The unextended vector should be 64 bits so that it can
6559 /// be used as an operand to a VMULL instruction. If the original vector size
6560 /// before extension is less than 64 bits we add a an extension to resize
6561 /// the vector to 64 bits.
6562 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6563   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6564     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6565                                         N->getOperand(0)->getValueType(0),
6566                                         N->getValueType(0),
6567                                         N->getOpcode());
6568 
6569   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6570     return SkipLoadExtensionForVMULL(LD, DAG);
6571 
6572   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6573   // have been legalized as a BITCAST from v4i32.
6574   if (N->getOpcode() == ISD::BITCAST) {
6575     SDNode *BVN = N->getOperand(0).getNode();
6576     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6577            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6578     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6579     return DAG.getBuildVector(
6580         MVT::v2i32, SDLoc(N),
6581         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
6582   }
6583   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6584   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6585   EVT VT = N->getValueType(0);
6586   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6587   unsigned NumElts = VT.getVectorNumElements();
6588   MVT TruncVT = MVT::getIntegerVT(EltSize);
6589   SmallVector<SDValue, 8> Ops;
6590   SDLoc dl(N);
6591   for (unsigned i = 0; i != NumElts; ++i) {
6592     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6593     const APInt &CInt = C->getAPIntValue();
6594     // Element types smaller than 32 bits are not legal, so use i32 elements.
6595     // The values are implicitly truncated so sext vs. zext doesn't matter.
6596     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6597   }
6598   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
6599 }
6600 
6601 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6602   unsigned Opcode = N->getOpcode();
6603   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6604     SDNode *N0 = N->getOperand(0).getNode();
6605     SDNode *N1 = N->getOperand(1).getNode();
6606     return N0->hasOneUse() && N1->hasOneUse() &&
6607       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6608   }
6609   return false;
6610 }
6611 
6612 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6613   unsigned Opcode = N->getOpcode();
6614   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6615     SDNode *N0 = N->getOperand(0).getNode();
6616     SDNode *N1 = N->getOperand(1).getNode();
6617     return N0->hasOneUse() && N1->hasOneUse() &&
6618       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6619   }
6620   return false;
6621 }
6622 
6623 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6624   // Multiplications are only custom-lowered for 128-bit vectors so that
6625   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6626   EVT VT = Op.getValueType();
6627   assert(VT.is128BitVector() && VT.isInteger() &&
6628          "unexpected type for custom-lowering ISD::MUL");
6629   SDNode *N0 = Op.getOperand(0).getNode();
6630   SDNode *N1 = Op.getOperand(1).getNode();
6631   unsigned NewOpc = 0;
6632   bool isMLA = false;
6633   bool isN0SExt = isSignExtended(N0, DAG);
6634   bool isN1SExt = isSignExtended(N1, DAG);
6635   if (isN0SExt && isN1SExt)
6636     NewOpc = ARMISD::VMULLs;
6637   else {
6638     bool isN0ZExt = isZeroExtended(N0, DAG);
6639     bool isN1ZExt = isZeroExtended(N1, DAG);
6640     if (isN0ZExt && isN1ZExt)
6641       NewOpc = ARMISD::VMULLu;
6642     else if (isN1SExt || isN1ZExt) {
6643       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6644       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6645       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6646         NewOpc = ARMISD::VMULLs;
6647         isMLA = true;
6648       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6649         NewOpc = ARMISD::VMULLu;
6650         isMLA = true;
6651       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6652         std::swap(N0, N1);
6653         NewOpc = ARMISD::VMULLu;
6654         isMLA = true;
6655       }
6656     }
6657 
6658     if (!NewOpc) {
6659       if (VT == MVT::v2i64)
6660         // Fall through to expand this.  It is not legal.
6661         return SDValue();
6662       else
6663         // Other vector multiplications are legal.
6664         return Op;
6665     }
6666   }
6667 
6668   // Legalize to a VMULL instruction.
6669   SDLoc DL(Op);
6670   SDValue Op0;
6671   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6672   if (!isMLA) {
6673     Op0 = SkipExtensionForVMULL(N0, DAG);
6674     assert(Op0.getValueType().is64BitVector() &&
6675            Op1.getValueType().is64BitVector() &&
6676            "unexpected types for extended operands to VMULL");
6677     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6678   }
6679 
6680   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6681   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6682   //   vmull q0, d4, d6
6683   //   vmlal q0, d5, d6
6684   // is faster than
6685   //   vaddl q0, d4, d5
6686   //   vmovl q1, d6
6687   //   vmul  q0, q0, q1
6688   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6689   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6690   EVT Op1VT = Op1.getValueType();
6691   return DAG.getNode(N0->getOpcode(), DL, VT,
6692                      DAG.getNode(NewOpc, DL, VT,
6693                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6694                      DAG.getNode(NewOpc, DL, VT,
6695                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6696 }
6697 
6698 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
6699                               SelectionDAG &DAG) {
6700   // TODO: Should this propagate fast-math-flags?
6701 
6702   // Convert to float
6703   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6704   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6705   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6706   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6707   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6708   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6709   // Get reciprocal estimate.
6710   // float4 recip = vrecpeq_f32(yf);
6711   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6712                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6713                    Y);
6714   // Because char has a smaller range than uchar, we can actually get away
6715   // without any newton steps.  This requires that we use a weird bias
6716   // of 0xb000, however (again, this has been exhaustively tested).
6717   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6718   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6719   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6720   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
6721   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6722   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6723   // Convert back to short.
6724   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6725   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6726   return X;
6727 }
6728 
6729 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
6730                                SelectionDAG &DAG) {
6731   // TODO: Should this propagate fast-math-flags?
6732 
6733   SDValue N2;
6734   // Convert to float.
6735   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6736   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6737   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6738   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6739   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6740   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6741 
6742   // Use reciprocal estimate and one refinement step.
6743   // float4 recip = vrecpeq_f32(yf);
6744   // recip *= vrecpsq_f32(yf, recip);
6745   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6746                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6747                    N1);
6748   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6749                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6750                    N1, N2);
6751   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6752   // Because short has a smaller range than ushort, we can actually get away
6753   // with only a single newton step.  This requires that we use a weird bias
6754   // of 89, however (again, this has been exhaustively tested).
6755   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6756   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6757   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6758   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
6759   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6760   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6761   // Convert back to integer and return.
6762   // return vmovn_s32(vcvt_s32_f32(result));
6763   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6764   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6765   return N0;
6766 }
6767 
6768 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6769   EVT VT = Op.getValueType();
6770   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6771          "unexpected type for custom-lowering ISD::SDIV");
6772 
6773   SDLoc dl(Op);
6774   SDValue N0 = Op.getOperand(0);
6775   SDValue N1 = Op.getOperand(1);
6776   SDValue N2, N3;
6777 
6778   if (VT == MVT::v8i8) {
6779     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6780     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6781 
6782     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6783                      DAG.getIntPtrConstant(4, dl));
6784     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6785                      DAG.getIntPtrConstant(4, dl));
6786     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6787                      DAG.getIntPtrConstant(0, dl));
6788     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6789                      DAG.getIntPtrConstant(0, dl));
6790 
6791     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6792     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6793 
6794     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6795     N0 = LowerCONCAT_VECTORS(N0, DAG);
6796 
6797     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6798     return N0;
6799   }
6800   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6801 }
6802 
6803 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6804   // TODO: Should this propagate fast-math-flags?
6805   EVT VT = Op.getValueType();
6806   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6807          "unexpected type for custom-lowering ISD::UDIV");
6808 
6809   SDLoc dl(Op);
6810   SDValue N0 = Op.getOperand(0);
6811   SDValue N1 = Op.getOperand(1);
6812   SDValue N2, N3;
6813 
6814   if (VT == MVT::v8i8) {
6815     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6816     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6817 
6818     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6819                      DAG.getIntPtrConstant(4, dl));
6820     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6821                      DAG.getIntPtrConstant(4, dl));
6822     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6823                      DAG.getIntPtrConstant(0, dl));
6824     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6825                      DAG.getIntPtrConstant(0, dl));
6826 
6827     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6828     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6829 
6830     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6831     N0 = LowerCONCAT_VECTORS(N0, DAG);
6832 
6833     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6834                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6835                                      MVT::i32),
6836                      N0);
6837     return N0;
6838   }
6839 
6840   // v4i16 sdiv ... Convert to float.
6841   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6842   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6843   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6844   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6845   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6846   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6847 
6848   // Use reciprocal estimate and two refinement steps.
6849   // float4 recip = vrecpeq_f32(yf);
6850   // recip *= vrecpsq_f32(yf, recip);
6851   // recip *= vrecpsq_f32(yf, recip);
6852   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6853                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6854                    BN1);
6855   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6856                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6857                    BN1, N2);
6858   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6859   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6860                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6861                    BN1, N2);
6862   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6863   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6864   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6865   // and that it will never cause us to return an answer too large).
6866   // float4 result = as_float4(as_int4(xf*recip) + 2);
6867   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6868   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6869   N1 = DAG.getConstant(2, dl, MVT::v4i32);
6870   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6871   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6872   // Convert back to integer and return.
6873   // return vmovn_u32(vcvt_s32_f32(result));
6874   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6875   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6876   return N0;
6877 }
6878 
6879 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6880   EVT VT = Op.getNode()->getValueType(0);
6881   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6882 
6883   unsigned Opc;
6884   bool ExtraOp = false;
6885   switch (Op.getOpcode()) {
6886   default: llvm_unreachable("Invalid code");
6887   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6888   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6889   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6890   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6891   }
6892 
6893   if (!ExtraOp)
6894     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6895                        Op.getOperand(1));
6896   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6897                      Op.getOperand(1), Op.getOperand(2));
6898 }
6899 
6900 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6901   assert(Subtarget->isTargetDarwin());
6902 
6903   // For iOS, we want to call an alternative entry point: __sincos_stret,
6904   // return values are passed via sret.
6905   SDLoc dl(Op);
6906   SDValue Arg = Op.getOperand(0);
6907   EVT ArgVT = Arg.getValueType();
6908   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6909   auto PtrVT = getPointerTy(DAG.getDataLayout());
6910 
6911   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6913 
6914   // Pair of floats / doubles used to pass the result.
6915   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6916   auto &DL = DAG.getDataLayout();
6917 
6918   ArgListTy Args;
6919   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6920   SDValue SRet;
6921   if (ShouldUseSRet) {
6922     // Create stack object for sret.
6923     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6924     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6925     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
6926     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6927 
6928     ArgListEntry Entry;
6929     Entry.Node = SRet;
6930     Entry.Ty = RetTy->getPointerTo();
6931     Entry.isSExt = false;
6932     Entry.isZExt = false;
6933     Entry.isSRet = true;
6934     Args.push_back(Entry);
6935     RetTy = Type::getVoidTy(*DAG.getContext());
6936   }
6937 
6938   ArgListEntry Entry;
6939   Entry.Node = Arg;
6940   Entry.Ty = ArgTy;
6941   Entry.isSExt = false;
6942   Entry.isZExt = false;
6943   Args.push_back(Entry);
6944 
6945   const char *LibcallName =
6946       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6947   RTLIB::Libcall LC =
6948       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6949   CallingConv::ID CC = getLibcallCallingConv(LC);
6950   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6951 
6952   TargetLowering::CallLoweringInfo CLI(DAG);
6953   CLI.setDebugLoc(dl)
6954       .setChain(DAG.getEntryNode())
6955       .setCallee(CC, RetTy, Callee, std::move(Args))
6956       .setDiscardResult(ShouldUseSRet);
6957   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6958 
6959   if (!ShouldUseSRet)
6960     return CallResult.first;
6961 
6962   SDValue LoadSin =
6963       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
6964 
6965   // Address of cos field.
6966   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6967                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6968   SDValue LoadCos =
6969       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
6970 
6971   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6972   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6973                      LoadSin.getValue(0), LoadCos.getValue(0));
6974 }
6975 
6976 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6977                                                   bool Signed,
6978                                                   SDValue &Chain) const {
6979   EVT VT = Op.getValueType();
6980   assert((VT == MVT::i32 || VT == MVT::i64) &&
6981          "unexpected type for custom lowering DIV");
6982   SDLoc dl(Op);
6983 
6984   const auto &DL = DAG.getDataLayout();
6985   const auto &TLI = DAG.getTargetLoweringInfo();
6986 
6987   const char *Name = nullptr;
6988   if (Signed)
6989     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6990   else
6991     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6992 
6993   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6994 
6995   ARMTargetLowering::ArgListTy Args;
6996 
6997   for (auto AI : {1, 0}) {
6998     ArgListEntry Arg;
6999     Arg.Node = Op.getOperand(AI);
7000     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7001     Args.push_back(Arg);
7002   }
7003 
7004   CallLoweringInfo CLI(DAG);
7005   CLI.setDebugLoc(dl)
7006     .setChain(Chain)
7007     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7008                ES, std::move(Args));
7009 
7010   return LowerCallTo(CLI).first;
7011 }
7012 
7013 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7014                                             bool Signed) const {
7015   assert(Op.getValueType() == MVT::i32 &&
7016          "unexpected type for custom lowering DIV");
7017   SDLoc dl(Op);
7018 
7019   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7020                                DAG.getEntryNode(), Op.getOperand(1));
7021 
7022   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7023 }
7024 
7025 void ARMTargetLowering::ExpandDIV_Windows(
7026     SDValue Op, SelectionDAG &DAG, bool Signed,
7027     SmallVectorImpl<SDValue> &Results) const {
7028   const auto &DL = DAG.getDataLayout();
7029   const auto &TLI = DAG.getTargetLoweringInfo();
7030 
7031   assert(Op.getValueType() == MVT::i64 &&
7032          "unexpected type for custom lowering DIV");
7033   SDLoc dl(Op);
7034 
7035   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
7036                            DAG.getConstant(0, dl, MVT::i32));
7037   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
7038                            DAG.getConstant(1, dl, MVT::i32));
7039   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
7040 
7041   SDValue DBZCHK =
7042       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
7043 
7044   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7045 
7046   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7047   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7048                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7049   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7050 
7051   Results.push_back(Lower);
7052   Results.push_back(Upper);
7053 }
7054 
7055 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7056   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7057     // Acquire/Release load/store is not legal for targets without a dmb or
7058     // equivalent available.
7059     return SDValue();
7060 
7061   // Monotonic load/store is legal for all targets.
7062   return Op;
7063 }
7064 
7065 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7066                                     SmallVectorImpl<SDValue> &Results,
7067                                     SelectionDAG &DAG,
7068                                     const ARMSubtarget *Subtarget) {
7069   SDLoc DL(N);
7070   // Under Power Management extensions, the cycle-count is:
7071   //    mrc p15, #0, <Rt>, c9, c13, #0
7072   SDValue Ops[] = { N->getOperand(0), // Chain
7073                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7074                     DAG.getConstant(15, DL, MVT::i32),
7075                     DAG.getConstant(0, DL, MVT::i32),
7076                     DAG.getConstant(9, DL, MVT::i32),
7077                     DAG.getConstant(13, DL, MVT::i32),
7078                     DAG.getConstant(0, DL, MVT::i32)
7079   };
7080 
7081   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7082                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7083   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7084                                 DAG.getConstant(0, DL, MVT::i32)));
7085   Results.push_back(Cycles32.getValue(1));
7086 }
7087 
7088 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7089   SDLoc dl(V.getNode());
7090   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7091   SDValue VHi = DAG.getAnyExtOrTrunc(
7092       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7093       dl, MVT::i32);
7094   SDValue RegClass =
7095       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7096   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7097   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7098   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7099   return SDValue(
7100       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7101 }
7102 
7103 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7104                                        SmallVectorImpl<SDValue> & Results,
7105                                        SelectionDAG &DAG) {
7106   assert(N->getValueType(0) == MVT::i64 &&
7107          "AtomicCmpSwap on types less than 64 should be legal");
7108   SDValue Ops[] = {N->getOperand(1),
7109                    createGPRPairNode(DAG, N->getOperand(2)),
7110                    createGPRPairNode(DAG, N->getOperand(3)),
7111                    N->getOperand(0)};
7112   SDNode *CmpSwap = DAG.getMachineNode(
7113       ARM::CMP_SWAP_64, SDLoc(N),
7114       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7115 
7116   MachineFunction &MF = DAG.getMachineFunction();
7117   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7118   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7119   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7120 
7121   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7122                                                SDValue(CmpSwap, 0)));
7123   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7124                                                SDValue(CmpSwap, 0)));
7125   Results.push_back(SDValue(CmpSwap, 2));
7126 }
7127 
7128 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7129   switch (Op.getOpcode()) {
7130   default: llvm_unreachable("Don't know how to custom lower this!");
7131   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7132   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
7133   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7134   case ISD::GlobalAddress:
7135     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7136     default: llvm_unreachable("unknown object format");
7137     case Triple::COFF:
7138       return LowerGlobalAddressWindows(Op, DAG);
7139     case Triple::ELF:
7140       return LowerGlobalAddressELF(Op, DAG);
7141     case Triple::MachO:
7142       return LowerGlobalAddressDarwin(Op, DAG);
7143     }
7144   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7145   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7146   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7147   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7148   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7149   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7150   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7151   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7152   case ISD::SINT_TO_FP:
7153   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7154   case ISD::FP_TO_SINT:
7155   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7156   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7157   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7158   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7159   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7160   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7161   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7162   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7163                                                                Subtarget);
7164   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7165   case ISD::SHL:
7166   case ISD::SRL:
7167   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7168   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7169   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7170   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7171   case ISD::SRL_PARTS:
7172   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7173   case ISD::CTTZ:
7174   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7175   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7176   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7177   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7178   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7179   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7180   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7181   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7182   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7183   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7184   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7185   case ISD::MUL:           return LowerMUL(Op, DAG);
7186   case ISD::SDIV:
7187     if (Subtarget->isTargetWindows())
7188       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7189     return LowerSDIV(Op, DAG);
7190   case ISD::UDIV:
7191     if (Subtarget->isTargetWindows())
7192       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7193     return LowerUDIV(Op, DAG);
7194   case ISD::ADDC:
7195   case ISD::ADDE:
7196   case ISD::SUBC:
7197   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7198   case ISD::SADDO:
7199   case ISD::UADDO:
7200   case ISD::SSUBO:
7201   case ISD::USUBO:
7202     return LowerXALUO(Op, DAG);
7203   case ISD::ATOMIC_LOAD:
7204   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7205   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7206   case ISD::SDIVREM:
7207   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7208   case ISD::DYNAMIC_STACKALLOC:
7209     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7210       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7211     llvm_unreachable("Don't know how to custom lower this!");
7212   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7213   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7214   case ARMISD::WIN__DBZCHK: return SDValue();
7215   }
7216 }
7217 
7218 /// ReplaceNodeResults - Replace the results of node with an illegal result
7219 /// type with new values built out of custom code.
7220 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7221                                            SmallVectorImpl<SDValue> &Results,
7222                                            SelectionDAG &DAG) const {
7223   SDValue Res;
7224   switch (N->getOpcode()) {
7225   default:
7226     llvm_unreachable("Don't know how to custom expand this!");
7227   case ISD::READ_REGISTER:
7228     ExpandREAD_REGISTER(N, Results, DAG);
7229     break;
7230   case ISD::BITCAST:
7231     Res = ExpandBITCAST(N, DAG);
7232     break;
7233   case ISD::SRL:
7234   case ISD::SRA:
7235     Res = Expand64BitShift(N, DAG, Subtarget);
7236     break;
7237   case ISD::SREM:
7238   case ISD::UREM:
7239     Res = LowerREM(N, DAG);
7240     break;
7241   case ISD::SDIVREM:
7242   case ISD::UDIVREM:
7243     Res = LowerDivRem(SDValue(N, 0), DAG);
7244     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7245     Results.push_back(Res.getValue(0));
7246     Results.push_back(Res.getValue(1));
7247     return;
7248   case ISD::READCYCLECOUNTER:
7249     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7250     return;
7251   case ISD::UDIV:
7252   case ISD::SDIV:
7253     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7254     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7255                              Results);
7256   case ISD::ATOMIC_CMP_SWAP:
7257     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7258     return;
7259   }
7260   if (Res.getNode())
7261     Results.push_back(Res);
7262 }
7263 
7264 //===----------------------------------------------------------------------===//
7265 //                           ARM Scheduler Hooks
7266 //===----------------------------------------------------------------------===//
7267 
7268 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7269 /// registers the function context.
7270 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7271                                                MachineBasicBlock *MBB,
7272                                                MachineBasicBlock *DispatchBB,
7273                                                int FI) const {
7274   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7275   DebugLoc dl = MI.getDebugLoc();
7276   MachineFunction *MF = MBB->getParent();
7277   MachineRegisterInfo *MRI = &MF->getRegInfo();
7278   MachineConstantPool *MCP = MF->getConstantPool();
7279   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7280   const Function *F = MF->getFunction();
7281 
7282   bool isThumb = Subtarget->isThumb();
7283   bool isThumb2 = Subtarget->isThumb2();
7284 
7285   unsigned PCLabelId = AFI->createPICLabelUId();
7286   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7287   ARMConstantPoolValue *CPV =
7288     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7289   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7290 
7291   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7292                                            : &ARM::GPRRegClass;
7293 
7294   // Grab constant pool and fixed stack memory operands.
7295   MachineMemOperand *CPMMO =
7296       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7297                                MachineMemOperand::MOLoad, 4, 4);
7298 
7299   MachineMemOperand *FIMMOSt =
7300       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7301                                MachineMemOperand::MOStore, 4, 4);
7302 
7303   // Load the address of the dispatch MBB into the jump buffer.
7304   if (isThumb2) {
7305     // Incoming value: jbuf
7306     //   ldr.n  r5, LCPI1_1
7307     //   orr    r5, r5, #1
7308     //   add    r5, pc
7309     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7310     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7311     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7312                    .addConstantPoolIndex(CPI)
7313                    .addMemOperand(CPMMO));
7314     // Set the low bit because of thumb mode.
7315     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7316     AddDefaultCC(
7317       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7318                      .addReg(NewVReg1, RegState::Kill)
7319                      .addImm(0x01)));
7320     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7321     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7322       .addReg(NewVReg2, RegState::Kill)
7323       .addImm(PCLabelId);
7324     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7325                    .addReg(NewVReg3, RegState::Kill)
7326                    .addFrameIndex(FI)
7327                    .addImm(36)  // &jbuf[1] :: pc
7328                    .addMemOperand(FIMMOSt));
7329   } else if (isThumb) {
7330     // Incoming value: jbuf
7331     //   ldr.n  r1, LCPI1_4
7332     //   add    r1, pc
7333     //   mov    r2, #1
7334     //   orrs   r1, r2
7335     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7336     //   str    r1, [r2]
7337     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7338     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7339                    .addConstantPoolIndex(CPI)
7340                    .addMemOperand(CPMMO));
7341     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7342     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7343       .addReg(NewVReg1, RegState::Kill)
7344       .addImm(PCLabelId);
7345     // Set the low bit because of thumb mode.
7346     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7347     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7348                    .addReg(ARM::CPSR, RegState::Define)
7349                    .addImm(1));
7350     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7351     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7352                    .addReg(ARM::CPSR, RegState::Define)
7353                    .addReg(NewVReg2, RegState::Kill)
7354                    .addReg(NewVReg3, RegState::Kill));
7355     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7356     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7357             .addFrameIndex(FI)
7358             .addImm(36); // &jbuf[1] :: pc
7359     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7360                    .addReg(NewVReg4, RegState::Kill)
7361                    .addReg(NewVReg5, RegState::Kill)
7362                    .addImm(0)
7363                    .addMemOperand(FIMMOSt));
7364   } else {
7365     // Incoming value: jbuf
7366     //   ldr  r1, LCPI1_1
7367     //   add  r1, pc, r1
7368     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7369     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7370     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7371                    .addConstantPoolIndex(CPI)
7372                    .addImm(0)
7373                    .addMemOperand(CPMMO));
7374     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7375     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7376                    .addReg(NewVReg1, RegState::Kill)
7377                    .addImm(PCLabelId));
7378     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7379                    .addReg(NewVReg2, RegState::Kill)
7380                    .addFrameIndex(FI)
7381                    .addImm(36)  // &jbuf[1] :: pc
7382                    .addMemOperand(FIMMOSt));
7383   }
7384 }
7385 
7386 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7387                                               MachineBasicBlock *MBB) const {
7388   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7389   DebugLoc dl = MI.getDebugLoc();
7390   MachineFunction *MF = MBB->getParent();
7391   MachineRegisterInfo *MRI = &MF->getRegInfo();
7392   MachineFrameInfo &MFI = MF->getFrameInfo();
7393   int FI = MFI.getFunctionContextIndex();
7394 
7395   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7396                                                         : &ARM::GPRnopcRegClass;
7397 
7398   // Get a mapping of the call site numbers to all of the landing pads they're
7399   // associated with.
7400   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7401   unsigned MaxCSNum = 0;
7402   MachineModuleInfo &MMI = MF->getMMI();
7403   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7404        ++BB) {
7405     if (!BB->isEHPad()) continue;
7406 
7407     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7408     // pad.
7409     for (MachineBasicBlock::iterator
7410            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7411       if (!II->isEHLabel()) continue;
7412 
7413       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7414       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7415 
7416       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7417       for (SmallVectorImpl<unsigned>::iterator
7418              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7419            CSI != CSE; ++CSI) {
7420         CallSiteNumToLPad[*CSI].push_back(&*BB);
7421         MaxCSNum = std::max(MaxCSNum, *CSI);
7422       }
7423       break;
7424     }
7425   }
7426 
7427   // Get an ordered list of the machine basic blocks for the jump table.
7428   std::vector<MachineBasicBlock*> LPadList;
7429   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7430   LPadList.reserve(CallSiteNumToLPad.size());
7431   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7432     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7433     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7434            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7435       LPadList.push_back(*II);
7436       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7437     }
7438   }
7439 
7440   assert(!LPadList.empty() &&
7441          "No landing pad destinations for the dispatch jump table!");
7442 
7443   // Create the jump table and associated information.
7444   MachineJumpTableInfo *JTI =
7445     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7446   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7447 
7448   // Create the MBBs for the dispatch code.
7449 
7450   // Shove the dispatch's address into the return slot in the function context.
7451   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7452   DispatchBB->setIsEHPad();
7453 
7454   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7455   unsigned trap_opcode;
7456   if (Subtarget->isThumb())
7457     trap_opcode = ARM::tTRAP;
7458   else
7459     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7460 
7461   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7462   DispatchBB->addSuccessor(TrapBB);
7463 
7464   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7465   DispatchBB->addSuccessor(DispContBB);
7466 
7467   // Insert and MBBs.
7468   MF->insert(MF->end(), DispatchBB);
7469   MF->insert(MF->end(), DispContBB);
7470   MF->insert(MF->end(), TrapBB);
7471 
7472   // Insert code into the entry block that creates and registers the function
7473   // context.
7474   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7475 
7476   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7477       MachinePointerInfo::getFixedStack(*MF, FI),
7478       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7479 
7480   MachineInstrBuilder MIB;
7481   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7482 
7483   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7484   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7485 
7486   // Add a register mask with no preserved registers.  This results in all
7487   // registers being marked as clobbered.
7488   MIB.addRegMask(RI.getNoPreservedMask());
7489 
7490   bool IsPositionIndependent = isPositionIndependent();
7491   unsigned NumLPads = LPadList.size();
7492   if (Subtarget->isThumb2()) {
7493     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7494     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7495                    .addFrameIndex(FI)
7496                    .addImm(4)
7497                    .addMemOperand(FIMMOLd));
7498 
7499     if (NumLPads < 256) {
7500       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7501                      .addReg(NewVReg1)
7502                      .addImm(LPadList.size()));
7503     } else {
7504       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7505       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7506                      .addImm(NumLPads & 0xFFFF));
7507 
7508       unsigned VReg2 = VReg1;
7509       if ((NumLPads & 0xFFFF0000) != 0) {
7510         VReg2 = MRI->createVirtualRegister(TRC);
7511         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7512                        .addReg(VReg1)
7513                        .addImm(NumLPads >> 16));
7514       }
7515 
7516       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7517                      .addReg(NewVReg1)
7518                      .addReg(VReg2));
7519     }
7520 
7521     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7522       .addMBB(TrapBB)
7523       .addImm(ARMCC::HI)
7524       .addReg(ARM::CPSR);
7525 
7526     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7527     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7528                    .addJumpTableIndex(MJTI));
7529 
7530     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7531     AddDefaultCC(
7532       AddDefaultPred(
7533         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7534         .addReg(NewVReg3, RegState::Kill)
7535         .addReg(NewVReg1)
7536         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7537 
7538     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7539       .addReg(NewVReg4, RegState::Kill)
7540       .addReg(NewVReg1)
7541       .addJumpTableIndex(MJTI);
7542   } else if (Subtarget->isThumb()) {
7543     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7544     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7545                    .addFrameIndex(FI)
7546                    .addImm(1)
7547                    .addMemOperand(FIMMOLd));
7548 
7549     if (NumLPads < 256) {
7550       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7551                      .addReg(NewVReg1)
7552                      .addImm(NumLPads));
7553     } else {
7554       MachineConstantPool *ConstantPool = MF->getConstantPool();
7555       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7556       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7557 
7558       // MachineConstantPool wants an explicit alignment.
7559       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7560       if (Align == 0)
7561         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7562       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7563 
7564       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7565       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7566                      .addReg(VReg1, RegState::Define)
7567                      .addConstantPoolIndex(Idx));
7568       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7569                      .addReg(NewVReg1)
7570                      .addReg(VReg1));
7571     }
7572 
7573     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7574       .addMBB(TrapBB)
7575       .addImm(ARMCC::HI)
7576       .addReg(ARM::CPSR);
7577 
7578     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7579     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7580                    .addReg(ARM::CPSR, RegState::Define)
7581                    .addReg(NewVReg1)
7582                    .addImm(2));
7583 
7584     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7585     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7586                    .addJumpTableIndex(MJTI));
7587 
7588     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7589     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7590                    .addReg(ARM::CPSR, RegState::Define)
7591                    .addReg(NewVReg2, RegState::Kill)
7592                    .addReg(NewVReg3));
7593 
7594     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7595         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7596 
7597     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7598     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7599                    .addReg(NewVReg4, RegState::Kill)
7600                    .addImm(0)
7601                    .addMemOperand(JTMMOLd));
7602 
7603     unsigned NewVReg6 = NewVReg5;
7604     if (IsPositionIndependent) {
7605       NewVReg6 = MRI->createVirtualRegister(TRC);
7606       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7607                      .addReg(ARM::CPSR, RegState::Define)
7608                      .addReg(NewVReg5, RegState::Kill)
7609                      .addReg(NewVReg3));
7610     }
7611 
7612     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7613       .addReg(NewVReg6, RegState::Kill)
7614       .addJumpTableIndex(MJTI);
7615   } else {
7616     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7617     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7618                    .addFrameIndex(FI)
7619                    .addImm(4)
7620                    .addMemOperand(FIMMOLd));
7621 
7622     if (NumLPads < 256) {
7623       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7624                      .addReg(NewVReg1)
7625                      .addImm(NumLPads));
7626     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7627       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7628       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7629                      .addImm(NumLPads & 0xFFFF));
7630 
7631       unsigned VReg2 = VReg1;
7632       if ((NumLPads & 0xFFFF0000) != 0) {
7633         VReg2 = MRI->createVirtualRegister(TRC);
7634         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7635                        .addReg(VReg1)
7636                        .addImm(NumLPads >> 16));
7637       }
7638 
7639       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7640                      .addReg(NewVReg1)
7641                      .addReg(VReg2));
7642     } else {
7643       MachineConstantPool *ConstantPool = MF->getConstantPool();
7644       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7645       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7646 
7647       // MachineConstantPool wants an explicit alignment.
7648       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7649       if (Align == 0)
7650         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7651       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7652 
7653       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7654       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7655                      .addReg(VReg1, RegState::Define)
7656                      .addConstantPoolIndex(Idx)
7657                      .addImm(0));
7658       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7659                      .addReg(NewVReg1)
7660                      .addReg(VReg1, RegState::Kill));
7661     }
7662 
7663     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7664       .addMBB(TrapBB)
7665       .addImm(ARMCC::HI)
7666       .addReg(ARM::CPSR);
7667 
7668     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7669     AddDefaultCC(
7670       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7671                      .addReg(NewVReg1)
7672                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7673     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7674     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7675                    .addJumpTableIndex(MJTI));
7676 
7677     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7678         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7679     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7680     AddDefaultPred(
7681       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7682       .addReg(NewVReg3, RegState::Kill)
7683       .addReg(NewVReg4)
7684       .addImm(0)
7685       .addMemOperand(JTMMOLd));
7686 
7687     if (IsPositionIndependent) {
7688       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7689         .addReg(NewVReg5, RegState::Kill)
7690         .addReg(NewVReg4)
7691         .addJumpTableIndex(MJTI);
7692     } else {
7693       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7694         .addReg(NewVReg5, RegState::Kill)
7695         .addJumpTableIndex(MJTI);
7696     }
7697   }
7698 
7699   // Add the jump table entries as successors to the MBB.
7700   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7701   for (std::vector<MachineBasicBlock*>::iterator
7702          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7703     MachineBasicBlock *CurMBB = *I;
7704     if (SeenMBBs.insert(CurMBB).second)
7705       DispContBB->addSuccessor(CurMBB);
7706   }
7707 
7708   // N.B. the order the invoke BBs are processed in doesn't matter here.
7709   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7710   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7711   for (MachineBasicBlock *BB : InvokeBBs) {
7712 
7713     // Remove the landing pad successor from the invoke block and replace it
7714     // with the new dispatch block.
7715     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7716                                                   BB->succ_end());
7717     while (!Successors.empty()) {
7718       MachineBasicBlock *SMBB = Successors.pop_back_val();
7719       if (SMBB->isEHPad()) {
7720         BB->removeSuccessor(SMBB);
7721         MBBLPads.push_back(SMBB);
7722       }
7723     }
7724 
7725     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7726     BB->normalizeSuccProbs();
7727 
7728     // Find the invoke call and mark all of the callee-saved registers as
7729     // 'implicit defined' so that they're spilled. This prevents code from
7730     // moving instructions to before the EH block, where they will never be
7731     // executed.
7732     for (MachineBasicBlock::reverse_iterator
7733            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7734       if (!II->isCall()) continue;
7735 
7736       DenseMap<unsigned, bool> DefRegs;
7737       for (MachineInstr::mop_iterator
7738              OI = II->operands_begin(), OE = II->operands_end();
7739            OI != OE; ++OI) {
7740         if (!OI->isReg()) continue;
7741         DefRegs[OI->getReg()] = true;
7742       }
7743 
7744       MachineInstrBuilder MIB(*MF, &*II);
7745 
7746       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7747         unsigned Reg = SavedRegs[i];
7748         if (Subtarget->isThumb2() &&
7749             !ARM::tGPRRegClass.contains(Reg) &&
7750             !ARM::hGPRRegClass.contains(Reg))
7751           continue;
7752         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7753           continue;
7754         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7755           continue;
7756         if (!DefRegs[Reg])
7757           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7758       }
7759 
7760       break;
7761     }
7762   }
7763 
7764   // Mark all former landing pads as non-landing pads. The dispatch is the only
7765   // landing pad now.
7766   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7767          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7768     (*I)->setIsEHPad(false);
7769 
7770   // The instruction is gone now.
7771   MI.eraseFromParent();
7772 }
7773 
7774 static
7775 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7776   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7777        E = MBB->succ_end(); I != E; ++I)
7778     if (*I != Succ)
7779       return *I;
7780   llvm_unreachable("Expecting a BB with two successors!");
7781 }
7782 
7783 /// Return the load opcode for a given load size. If load size >= 8,
7784 /// neon opcode will be returned.
7785 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7786   if (LdSize >= 8)
7787     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7788                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7789   if (IsThumb1)
7790     return LdSize == 4 ? ARM::tLDRi
7791                        : LdSize == 2 ? ARM::tLDRHi
7792                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7793   if (IsThumb2)
7794     return LdSize == 4 ? ARM::t2LDR_POST
7795                        : LdSize == 2 ? ARM::t2LDRH_POST
7796                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7797   return LdSize == 4 ? ARM::LDR_POST_IMM
7798                      : LdSize == 2 ? ARM::LDRH_POST
7799                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7800 }
7801 
7802 /// Return the store opcode for a given store size. If store size >= 8,
7803 /// neon opcode will be returned.
7804 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7805   if (StSize >= 8)
7806     return StSize == 16 ? ARM::VST1q32wb_fixed
7807                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7808   if (IsThumb1)
7809     return StSize == 4 ? ARM::tSTRi
7810                        : StSize == 2 ? ARM::tSTRHi
7811                                      : StSize == 1 ? ARM::tSTRBi : 0;
7812   if (IsThumb2)
7813     return StSize == 4 ? ARM::t2STR_POST
7814                        : StSize == 2 ? ARM::t2STRH_POST
7815                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7816   return StSize == 4 ? ARM::STR_POST_IMM
7817                      : StSize == 2 ? ARM::STRH_POST
7818                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7819 }
7820 
7821 /// Emit a post-increment load operation with given size. The instructions
7822 /// will be added to BB at Pos.
7823 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
7824                        const TargetInstrInfo *TII, const DebugLoc &dl,
7825                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7826                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7827   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7828   assert(LdOpc != 0 && "Should have a load opcode");
7829   if (LdSize >= 8) {
7830     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7831                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7832                        .addImm(0));
7833   } else if (IsThumb1) {
7834     // load + update AddrIn
7835     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7836                        .addReg(AddrIn).addImm(0));
7837     MachineInstrBuilder MIB =
7838         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7839     MIB = AddDefaultT1CC(MIB);
7840     MIB.addReg(AddrIn).addImm(LdSize);
7841     AddDefaultPred(MIB);
7842   } else if (IsThumb2) {
7843     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7844                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7845                        .addImm(LdSize));
7846   } else { // arm
7847     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7848                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7849                        .addReg(0).addImm(LdSize));
7850   }
7851 }
7852 
7853 /// Emit a post-increment store operation with given size. The instructions
7854 /// will be added to BB at Pos.
7855 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
7856                        const TargetInstrInfo *TII, const DebugLoc &dl,
7857                        unsigned StSize, unsigned Data, unsigned AddrIn,
7858                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7859   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7860   assert(StOpc != 0 && "Should have a store opcode");
7861   if (StSize >= 8) {
7862     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7863                        .addReg(AddrIn).addImm(0).addReg(Data));
7864   } else if (IsThumb1) {
7865     // store + update AddrIn
7866     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7867                        .addReg(AddrIn).addImm(0));
7868     MachineInstrBuilder MIB =
7869         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7870     MIB = AddDefaultT1CC(MIB);
7871     MIB.addReg(AddrIn).addImm(StSize);
7872     AddDefaultPred(MIB);
7873   } else if (IsThumb2) {
7874     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7875                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7876   } else { // arm
7877     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7878                        .addReg(Data).addReg(AddrIn).addReg(0)
7879                        .addImm(StSize));
7880   }
7881 }
7882 
7883 MachineBasicBlock *
7884 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
7885                                    MachineBasicBlock *BB) const {
7886   // This pseudo instruction has 3 operands: dst, src, size
7887   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7888   // Otherwise, we will generate unrolled scalar copies.
7889   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7890   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7891   MachineFunction::iterator It = ++BB->getIterator();
7892 
7893   unsigned dest = MI.getOperand(0).getReg();
7894   unsigned src = MI.getOperand(1).getReg();
7895   unsigned SizeVal = MI.getOperand(2).getImm();
7896   unsigned Align = MI.getOperand(3).getImm();
7897   DebugLoc dl = MI.getDebugLoc();
7898 
7899   MachineFunction *MF = BB->getParent();
7900   MachineRegisterInfo &MRI = MF->getRegInfo();
7901   unsigned UnitSize = 0;
7902   const TargetRegisterClass *TRC = nullptr;
7903   const TargetRegisterClass *VecTRC = nullptr;
7904 
7905   bool IsThumb1 = Subtarget->isThumb1Only();
7906   bool IsThumb2 = Subtarget->isThumb2();
7907   bool IsThumb = Subtarget->isThumb();
7908 
7909   if (Align & 1) {
7910     UnitSize = 1;
7911   } else if (Align & 2) {
7912     UnitSize = 2;
7913   } else {
7914     // Check whether we can use NEON instructions.
7915     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7916         Subtarget->hasNEON()) {
7917       if ((Align % 16 == 0) && SizeVal >= 16)
7918         UnitSize = 16;
7919       else if ((Align % 8 == 0) && SizeVal >= 8)
7920         UnitSize = 8;
7921     }
7922     // Can't use NEON instructions.
7923     if (UnitSize == 0)
7924       UnitSize = 4;
7925   }
7926 
7927   // Select the correct opcode and register class for unit size load/store
7928   bool IsNeon = UnitSize >= 8;
7929   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7930   if (IsNeon)
7931     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7932                             : UnitSize == 8 ? &ARM::DPRRegClass
7933                                             : nullptr;
7934 
7935   unsigned BytesLeft = SizeVal % UnitSize;
7936   unsigned LoopSize = SizeVal - BytesLeft;
7937 
7938   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7939     // Use LDR and STR to copy.
7940     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7941     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7942     unsigned srcIn = src;
7943     unsigned destIn = dest;
7944     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7945       unsigned srcOut = MRI.createVirtualRegister(TRC);
7946       unsigned destOut = MRI.createVirtualRegister(TRC);
7947       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7948       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7949                  IsThumb1, IsThumb2);
7950       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7951                  IsThumb1, IsThumb2);
7952       srcIn = srcOut;
7953       destIn = destOut;
7954     }
7955 
7956     // Handle the leftover bytes with LDRB and STRB.
7957     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7958     // [destOut] = STRB_POST(scratch, destIn, 1)
7959     for (unsigned i = 0; i < BytesLeft; i++) {
7960       unsigned srcOut = MRI.createVirtualRegister(TRC);
7961       unsigned destOut = MRI.createVirtualRegister(TRC);
7962       unsigned scratch = MRI.createVirtualRegister(TRC);
7963       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7964                  IsThumb1, IsThumb2);
7965       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7966                  IsThumb1, IsThumb2);
7967       srcIn = srcOut;
7968       destIn = destOut;
7969     }
7970     MI.eraseFromParent(); // The instruction is gone now.
7971     return BB;
7972   }
7973 
7974   // Expand the pseudo op to a loop.
7975   // thisMBB:
7976   //   ...
7977   //   movw varEnd, # --> with thumb2
7978   //   movt varEnd, #
7979   //   ldrcp varEnd, idx --> without thumb2
7980   //   fallthrough --> loopMBB
7981   // loopMBB:
7982   //   PHI varPhi, varEnd, varLoop
7983   //   PHI srcPhi, src, srcLoop
7984   //   PHI destPhi, dst, destLoop
7985   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7986   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7987   //   subs varLoop, varPhi, #UnitSize
7988   //   bne loopMBB
7989   //   fallthrough --> exitMBB
7990   // exitMBB:
7991   //   epilogue to handle left-over bytes
7992   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7993   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7994   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7995   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7996   MF->insert(It, loopMBB);
7997   MF->insert(It, exitMBB);
7998 
7999   // Transfer the remainder of BB and its successor edges to exitMBB.
8000   exitMBB->splice(exitMBB->begin(), BB,
8001                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8002   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8003 
8004   // Load an immediate to varEnd.
8005   unsigned varEnd = MRI.createVirtualRegister(TRC);
8006   if (Subtarget->useMovt(*MF)) {
8007     unsigned Vtmp = varEnd;
8008     if ((LoopSize & 0xFFFF0000) != 0)
8009       Vtmp = MRI.createVirtualRegister(TRC);
8010     AddDefaultPred(BuildMI(BB, dl,
8011                            TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16),
8012                            Vtmp).addImm(LoopSize & 0xFFFF));
8013 
8014     if ((LoopSize & 0xFFFF0000) != 0)
8015       AddDefaultPred(BuildMI(BB, dl,
8016                              TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16),
8017                              varEnd)
8018                          .addReg(Vtmp)
8019                          .addImm(LoopSize >> 16));
8020   } else {
8021     MachineConstantPool *ConstantPool = MF->getConstantPool();
8022     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8023     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8024 
8025     // MachineConstantPool wants an explicit alignment.
8026     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8027     if (Align == 0)
8028       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8029     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8030 
8031     if (IsThumb)
8032       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
8033           varEnd, RegState::Define).addConstantPoolIndex(Idx));
8034     else
8035       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
8036           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
8037   }
8038   BB->addSuccessor(loopMBB);
8039 
8040   // Generate the loop body:
8041   //   varPhi = PHI(varLoop, varEnd)
8042   //   srcPhi = PHI(srcLoop, src)
8043   //   destPhi = PHI(destLoop, dst)
8044   MachineBasicBlock *entryBB = BB;
8045   BB = loopMBB;
8046   unsigned varLoop = MRI.createVirtualRegister(TRC);
8047   unsigned varPhi = MRI.createVirtualRegister(TRC);
8048   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8049   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8050   unsigned destLoop = MRI.createVirtualRegister(TRC);
8051   unsigned destPhi = MRI.createVirtualRegister(TRC);
8052 
8053   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8054     .addReg(varLoop).addMBB(loopMBB)
8055     .addReg(varEnd).addMBB(entryBB);
8056   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8057     .addReg(srcLoop).addMBB(loopMBB)
8058     .addReg(src).addMBB(entryBB);
8059   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8060     .addReg(destLoop).addMBB(loopMBB)
8061     .addReg(dest).addMBB(entryBB);
8062 
8063   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8064   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8065   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8066   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8067              IsThumb1, IsThumb2);
8068   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8069              IsThumb1, IsThumb2);
8070 
8071   // Decrement loop variable by UnitSize.
8072   if (IsThumb1) {
8073     MachineInstrBuilder MIB =
8074         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
8075     MIB = AddDefaultT1CC(MIB);
8076     MIB.addReg(varPhi).addImm(UnitSize);
8077     AddDefaultPred(MIB);
8078   } else {
8079     MachineInstrBuilder MIB =
8080         BuildMI(*BB, BB->end(), dl,
8081                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8082     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
8083     MIB->getOperand(5).setReg(ARM::CPSR);
8084     MIB->getOperand(5).setIsDef(true);
8085   }
8086   BuildMI(*BB, BB->end(), dl,
8087           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8088       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8089 
8090   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8091   BB->addSuccessor(loopMBB);
8092   BB->addSuccessor(exitMBB);
8093 
8094   // Add epilogue to handle BytesLeft.
8095   BB = exitMBB;
8096   auto StartOfExit = exitMBB->begin();
8097 
8098   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8099   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8100   unsigned srcIn = srcLoop;
8101   unsigned destIn = destLoop;
8102   for (unsigned i = 0; i < BytesLeft; i++) {
8103     unsigned srcOut = MRI.createVirtualRegister(TRC);
8104     unsigned destOut = MRI.createVirtualRegister(TRC);
8105     unsigned scratch = MRI.createVirtualRegister(TRC);
8106     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8107                IsThumb1, IsThumb2);
8108     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8109                IsThumb1, IsThumb2);
8110     srcIn = srcOut;
8111     destIn = destOut;
8112   }
8113 
8114   MI.eraseFromParent(); // The instruction is gone now.
8115   return BB;
8116 }
8117 
8118 MachineBasicBlock *
8119 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8120                                        MachineBasicBlock *MBB) const {
8121   const TargetMachine &TM = getTargetMachine();
8122   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8123   DebugLoc DL = MI.getDebugLoc();
8124 
8125   assert(Subtarget->isTargetWindows() &&
8126          "__chkstk is only supported on Windows");
8127   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8128 
8129   // __chkstk takes the number of words to allocate on the stack in R4, and
8130   // returns the stack adjustment in number of bytes in R4.  This will not
8131   // clober any other registers (other than the obvious lr).
8132   //
8133   // Although, technically, IP should be considered a register which may be
8134   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8135   // thumb-2 environment, so there is no interworking required.  As a result, we
8136   // do not expect a veneer to be emitted by the linker, clobbering IP.
8137   //
8138   // Each module receives its own copy of __chkstk, so no import thunk is
8139   // required, again, ensuring that IP is not clobbered.
8140   //
8141   // Finally, although some linkers may theoretically provide a trampoline for
8142   // out of range calls (which is quite common due to a 32M range limitation of
8143   // branches for Thumb), we can generate the long-call version via
8144   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8145   // IP.
8146 
8147   switch (TM.getCodeModel()) {
8148   case CodeModel::Small:
8149   case CodeModel::Medium:
8150   case CodeModel::Default:
8151   case CodeModel::Kernel:
8152     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8153       .addImm((unsigned)ARMCC::AL).addReg(0)
8154       .addExternalSymbol("__chkstk")
8155       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8156       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8157       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8158     break;
8159   case CodeModel::Large:
8160   case CodeModel::JITDefault: {
8161     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8162     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8163 
8164     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8165       .addExternalSymbol("__chkstk");
8166     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8167       .addImm((unsigned)ARMCC::AL).addReg(0)
8168       .addReg(Reg, RegState::Kill)
8169       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8170       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8171       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8172     break;
8173   }
8174   }
8175 
8176   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
8177                                       ARM::SP)
8178                          .addReg(ARM::SP, RegState::Kill)
8179                          .addReg(ARM::R4, RegState::Kill)
8180                          .setMIFlags(MachineInstr::FrameSetup)));
8181 
8182   MI.eraseFromParent();
8183   return MBB;
8184 }
8185 
8186 MachineBasicBlock *
8187 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8188                                        MachineBasicBlock *MBB) const {
8189   DebugLoc DL = MI.getDebugLoc();
8190   MachineFunction *MF = MBB->getParent();
8191   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8192 
8193   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8194   MF->insert(++MBB->getIterator(), ContBB);
8195   ContBB->splice(ContBB->begin(), MBB,
8196                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8197   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8198 
8199   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8200   MF->push_back(TrapBB);
8201   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
8202   MBB->addSuccessor(TrapBB);
8203 
8204   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
8205       .addReg(MI.getOperand(0).getReg())
8206       .addMBB(TrapBB);
8207   AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB));
8208   MBB->addSuccessor(ContBB);
8209 
8210   MI.eraseFromParent();
8211   return ContBB;
8212 }
8213 
8214 MachineBasicBlock *
8215 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8216                                                MachineBasicBlock *BB) const {
8217   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8218   DebugLoc dl = MI.getDebugLoc();
8219   bool isThumb2 = Subtarget->isThumb2();
8220   switch (MI.getOpcode()) {
8221   default: {
8222     MI.dump();
8223     llvm_unreachable("Unexpected instr type to insert");
8224   }
8225 
8226   // Thumb1 post-indexed loads are really just single-register LDMs.
8227   case ARM::tLDR_postidx: {
8228     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8229       .addOperand(MI.getOperand(1)) // Rn_wb
8230       .addOperand(MI.getOperand(2)) // Rn
8231       .addOperand(MI.getOperand(3)) // PredImm
8232       .addOperand(MI.getOperand(4)) // PredReg
8233       .addOperand(MI.getOperand(0)); // Rt
8234     MI.eraseFromParent();
8235     return BB;
8236   }
8237 
8238   // The Thumb2 pre-indexed stores have the same MI operands, they just
8239   // define them differently in the .td files from the isel patterns, so
8240   // they need pseudos.
8241   case ARM::t2STR_preidx:
8242     MI.setDesc(TII->get(ARM::t2STR_PRE));
8243     return BB;
8244   case ARM::t2STRB_preidx:
8245     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8246     return BB;
8247   case ARM::t2STRH_preidx:
8248     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8249     return BB;
8250 
8251   case ARM::STRi_preidx:
8252   case ARM::STRBi_preidx: {
8253     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8254                                                          : ARM::STRB_PRE_IMM;
8255     // Decode the offset.
8256     unsigned Offset = MI.getOperand(4).getImm();
8257     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8258     Offset = ARM_AM::getAM2Offset(Offset);
8259     if (isSub)
8260       Offset = -Offset;
8261 
8262     MachineMemOperand *MMO = *MI.memoperands_begin();
8263     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8264         .addOperand(MI.getOperand(0)) // Rn_wb
8265         .addOperand(MI.getOperand(1)) // Rt
8266         .addOperand(MI.getOperand(2)) // Rn
8267         .addImm(Offset)               // offset (skip GPR==zero_reg)
8268         .addOperand(MI.getOperand(5)) // pred
8269         .addOperand(MI.getOperand(6))
8270         .addMemOperand(MMO);
8271     MI.eraseFromParent();
8272     return BB;
8273   }
8274   case ARM::STRr_preidx:
8275   case ARM::STRBr_preidx:
8276   case ARM::STRH_preidx: {
8277     unsigned NewOpc;
8278     switch (MI.getOpcode()) {
8279     default: llvm_unreachable("unexpected opcode!");
8280     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8281     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8282     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8283     }
8284     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8285     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8286       MIB.addOperand(MI.getOperand(i));
8287     MI.eraseFromParent();
8288     return BB;
8289   }
8290 
8291   case ARM::tMOVCCr_pseudo: {
8292     // To "insert" a SELECT_CC instruction, we actually have to insert the
8293     // diamond control-flow pattern.  The incoming instruction knows the
8294     // destination vreg to set, the condition code register to branch on, the
8295     // true/false values to select between, and a branch opcode to use.
8296     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8297     MachineFunction::iterator It = ++BB->getIterator();
8298 
8299     //  thisMBB:
8300     //  ...
8301     //   TrueVal = ...
8302     //   cmpTY ccX, r1, r2
8303     //   bCC copy1MBB
8304     //   fallthrough --> copy0MBB
8305     MachineBasicBlock *thisMBB  = BB;
8306     MachineFunction *F = BB->getParent();
8307     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8308     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8309     F->insert(It, copy0MBB);
8310     F->insert(It, sinkMBB);
8311 
8312     // Transfer the remainder of BB and its successor edges to sinkMBB.
8313     sinkMBB->splice(sinkMBB->begin(), BB,
8314                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8315     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8316 
8317     BB->addSuccessor(copy0MBB);
8318     BB->addSuccessor(sinkMBB);
8319 
8320     BuildMI(BB, dl, TII->get(ARM::tBcc))
8321         .addMBB(sinkMBB)
8322         .addImm(MI.getOperand(3).getImm())
8323         .addReg(MI.getOperand(4).getReg());
8324 
8325     //  copy0MBB:
8326     //   %FalseValue = ...
8327     //   # fallthrough to sinkMBB
8328     BB = copy0MBB;
8329 
8330     // Update machine-CFG edges
8331     BB->addSuccessor(sinkMBB);
8332 
8333     //  sinkMBB:
8334     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8335     //  ...
8336     BB = sinkMBB;
8337     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8338         .addReg(MI.getOperand(1).getReg())
8339         .addMBB(copy0MBB)
8340         .addReg(MI.getOperand(2).getReg())
8341         .addMBB(thisMBB);
8342 
8343     MI.eraseFromParent(); // The pseudo instruction is gone now.
8344     return BB;
8345   }
8346 
8347   case ARM::BCCi64:
8348   case ARM::BCCZi64: {
8349     // If there is an unconditional branch to the other successor, remove it.
8350     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8351 
8352     // Compare both parts that make up the double comparison separately for
8353     // equality.
8354     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8355 
8356     unsigned LHS1 = MI.getOperand(1).getReg();
8357     unsigned LHS2 = MI.getOperand(2).getReg();
8358     if (RHSisZero) {
8359       AddDefaultPred(BuildMI(BB, dl,
8360                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8361                      .addReg(LHS1).addImm(0));
8362       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8363         .addReg(LHS2).addImm(0)
8364         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8365     } else {
8366       unsigned RHS1 = MI.getOperand(3).getReg();
8367       unsigned RHS2 = MI.getOperand(4).getReg();
8368       AddDefaultPred(BuildMI(BB, dl,
8369                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8370                      .addReg(LHS1).addReg(RHS1));
8371       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8372         .addReg(LHS2).addReg(RHS2)
8373         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8374     }
8375 
8376     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8377     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8378     if (MI.getOperand(0).getImm() == ARMCC::NE)
8379       std::swap(destMBB, exitMBB);
8380 
8381     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8382       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8383     if (isThumb2)
8384       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8385     else
8386       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8387 
8388     MI.eraseFromParent(); // The pseudo instruction is gone now.
8389     return BB;
8390   }
8391 
8392   case ARM::Int_eh_sjlj_setjmp:
8393   case ARM::Int_eh_sjlj_setjmp_nofp:
8394   case ARM::tInt_eh_sjlj_setjmp:
8395   case ARM::t2Int_eh_sjlj_setjmp:
8396   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8397     return BB;
8398 
8399   case ARM::Int_eh_sjlj_setup_dispatch:
8400     EmitSjLjDispatchBlock(MI, BB);
8401     return BB;
8402 
8403   case ARM::ABS:
8404   case ARM::t2ABS: {
8405     // To insert an ABS instruction, we have to insert the
8406     // diamond control-flow pattern.  The incoming instruction knows the
8407     // source vreg to test against 0, the destination vreg to set,
8408     // the condition code register to branch on, the
8409     // true/false values to select between, and a branch opcode to use.
8410     // It transforms
8411     //     V1 = ABS V0
8412     // into
8413     //     V2 = MOVS V0
8414     //     BCC                      (branch to SinkBB if V0 >= 0)
8415     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8416     //     SinkBB: V1 = PHI(V2, V3)
8417     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8418     MachineFunction::iterator BBI = ++BB->getIterator();
8419     MachineFunction *Fn = BB->getParent();
8420     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8421     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8422     Fn->insert(BBI, RSBBB);
8423     Fn->insert(BBI, SinkBB);
8424 
8425     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8426     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8427     bool ABSSrcKIll = MI.getOperand(1).isKill();
8428     bool isThumb2 = Subtarget->isThumb2();
8429     MachineRegisterInfo &MRI = Fn->getRegInfo();
8430     // In Thumb mode S must not be specified if source register is the SP or
8431     // PC and if destination register is the SP, so restrict register class
8432     unsigned NewRsbDstReg =
8433       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8434 
8435     // Transfer the remainder of BB and its successor edges to sinkMBB.
8436     SinkBB->splice(SinkBB->begin(), BB,
8437                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8438     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8439 
8440     BB->addSuccessor(RSBBB);
8441     BB->addSuccessor(SinkBB);
8442 
8443     // fall through to SinkMBB
8444     RSBBB->addSuccessor(SinkBB);
8445 
8446     // insert a cmp at the end of BB
8447     AddDefaultPred(BuildMI(BB, dl,
8448                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8449                    .addReg(ABSSrcReg).addImm(0));
8450 
8451     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8452     BuildMI(BB, dl,
8453       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8454       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8455 
8456     // insert rsbri in RSBBB
8457     // Note: BCC and rsbri will be converted into predicated rsbmi
8458     // by if-conversion pass
8459     BuildMI(*RSBBB, RSBBB->begin(), dl,
8460       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8461       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8462       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8463 
8464     // insert PHI in SinkBB,
8465     // reuse ABSDstReg to not change uses of ABS instruction
8466     BuildMI(*SinkBB, SinkBB->begin(), dl,
8467       TII->get(ARM::PHI), ABSDstReg)
8468       .addReg(NewRsbDstReg).addMBB(RSBBB)
8469       .addReg(ABSSrcReg).addMBB(BB);
8470 
8471     // remove ABS instruction
8472     MI.eraseFromParent();
8473 
8474     // return last added BB
8475     return SinkBB;
8476   }
8477   case ARM::COPY_STRUCT_BYVAL_I32:
8478     ++NumLoopByVals;
8479     return EmitStructByval(MI, BB);
8480   case ARM::WIN__CHKSTK:
8481     return EmitLowered__chkstk(MI, BB);
8482   case ARM::WIN__DBZCHK:
8483     return EmitLowered__dbzchk(MI, BB);
8484   }
8485 }
8486 
8487 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8488 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8489 /// instead of as a custom inserter because we need the use list from the SDNode.
8490 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8491                                     MachineInstr &MI, const SDNode *Node) {
8492   bool isThumb1 = Subtarget->isThumb1Only();
8493 
8494   DebugLoc DL = MI.getDebugLoc();
8495   MachineFunction *MF = MI.getParent()->getParent();
8496   MachineRegisterInfo &MRI = MF->getRegInfo();
8497   MachineInstrBuilder MIB(*MF, MI);
8498 
8499   // If the new dst/src is unused mark it as dead.
8500   if (!Node->hasAnyUseOfValue(0)) {
8501     MI.getOperand(0).setIsDead(true);
8502   }
8503   if (!Node->hasAnyUseOfValue(1)) {
8504     MI.getOperand(1).setIsDead(true);
8505   }
8506 
8507   // The MEMCPY both defines and kills the scratch registers.
8508   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
8509     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8510                                                          : &ARM::GPRRegClass);
8511     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8512   }
8513 }
8514 
8515 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8516                                                       SDNode *Node) const {
8517   if (MI.getOpcode() == ARM::MEMCPY) {
8518     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8519     return;
8520   }
8521 
8522   const MCInstrDesc *MCID = &MI.getDesc();
8523   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8524   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8525   // operand is still set to noreg. If needed, set the optional operand's
8526   // register to CPSR, and remove the redundant implicit def.
8527   //
8528   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8529 
8530   // Rename pseudo opcodes.
8531   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
8532   if (NewOpc) {
8533     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8534     MCID = &TII->get(NewOpc);
8535 
8536     assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
8537            "converted opcode should be the same except for cc_out");
8538 
8539     MI.setDesc(*MCID);
8540 
8541     // Add the optional cc_out operand
8542     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8543   }
8544   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8545 
8546   // Any ARM instruction that sets the 's' bit should specify an optional
8547   // "cc_out" operand in the last operand position.
8548   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8549     assert(!NewOpc && "Optional cc_out operand required");
8550     return;
8551   }
8552   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8553   // since we already have an optional CPSR def.
8554   bool definesCPSR = false;
8555   bool deadCPSR = false;
8556   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
8557        ++i) {
8558     const MachineOperand &MO = MI.getOperand(i);
8559     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8560       definesCPSR = true;
8561       if (MO.isDead())
8562         deadCPSR = true;
8563       MI.RemoveOperand(i);
8564       break;
8565     }
8566   }
8567   if (!definesCPSR) {
8568     assert(!NewOpc && "Optional cc_out operand required");
8569     return;
8570   }
8571   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8572   if (deadCPSR) {
8573     assert(!MI.getOperand(ccOutIdx).getReg() &&
8574            "expect uninitialized optional cc_out operand");
8575     return;
8576   }
8577 
8578   // If this instruction was defined with an optional CPSR def and its dag node
8579   // had a live implicit CPSR def, then activate the optional CPSR def.
8580   MachineOperand &MO = MI.getOperand(ccOutIdx);
8581   MO.setReg(ARM::CPSR);
8582   MO.setIsDef(true);
8583 }
8584 
8585 //===----------------------------------------------------------------------===//
8586 //                           ARM Optimization Hooks
8587 //===----------------------------------------------------------------------===//
8588 
8589 // Helper function that checks if N is a null or all ones constant.
8590 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8591   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8592 }
8593 
8594 // Return true if N is conditionally 0 or all ones.
8595 // Detects these expressions where cc is an i1 value:
8596 //
8597 //   (select cc 0, y)   [AllOnes=0]
8598 //   (select cc y, 0)   [AllOnes=0]
8599 //   (zext cc)          [AllOnes=0]
8600 //   (sext cc)          [AllOnes=0/1]
8601 //   (select cc -1, y)  [AllOnes=1]
8602 //   (select cc y, -1)  [AllOnes=1]
8603 //
8604 // Invert is set when N is the null/all ones constant when CC is false.
8605 // OtherOp is set to the alternative value of N.
8606 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8607                                        SDValue &CC, bool &Invert,
8608                                        SDValue &OtherOp,
8609                                        SelectionDAG &DAG) {
8610   switch (N->getOpcode()) {
8611   default: return false;
8612   case ISD::SELECT: {
8613     CC = N->getOperand(0);
8614     SDValue N1 = N->getOperand(1);
8615     SDValue N2 = N->getOperand(2);
8616     if (isZeroOrAllOnes(N1, AllOnes)) {
8617       Invert = false;
8618       OtherOp = N2;
8619       return true;
8620     }
8621     if (isZeroOrAllOnes(N2, AllOnes)) {
8622       Invert = true;
8623       OtherOp = N1;
8624       return true;
8625     }
8626     return false;
8627   }
8628   case ISD::ZERO_EXTEND:
8629     // (zext cc) can never be the all ones value.
8630     if (AllOnes)
8631       return false;
8632     // Fall through.
8633   case ISD::SIGN_EXTEND: {
8634     SDLoc dl(N);
8635     EVT VT = N->getValueType(0);
8636     CC = N->getOperand(0);
8637     if (CC.getValueType() != MVT::i1)
8638       return false;
8639     Invert = !AllOnes;
8640     if (AllOnes)
8641       // When looking for an AllOnes constant, N is an sext, and the 'other'
8642       // value is 0.
8643       OtherOp = DAG.getConstant(0, dl, VT);
8644     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8645       // When looking for a 0 constant, N can be zext or sext.
8646       OtherOp = DAG.getConstant(1, dl, VT);
8647     else
8648       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8649                                 VT);
8650     return true;
8651   }
8652   }
8653 }
8654 
8655 // Combine a constant select operand into its use:
8656 //
8657 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8658 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8659 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8660 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8661 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8662 //
8663 // The transform is rejected if the select doesn't have a constant operand that
8664 // is null, or all ones when AllOnes is set.
8665 //
8666 // Also recognize sext/zext from i1:
8667 //
8668 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8669 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8670 //
8671 // These transformations eventually create predicated instructions.
8672 //
8673 // @param N       The node to transform.
8674 // @param Slct    The N operand that is a select.
8675 // @param OtherOp The other N operand (x above).
8676 // @param DCI     Context.
8677 // @param AllOnes Require the select constant to be all ones instead of null.
8678 // @returns The new node, or SDValue() on failure.
8679 static
8680 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8681                             TargetLowering::DAGCombinerInfo &DCI,
8682                             bool AllOnes = false) {
8683   SelectionDAG &DAG = DCI.DAG;
8684   EVT VT = N->getValueType(0);
8685   SDValue NonConstantVal;
8686   SDValue CCOp;
8687   bool SwapSelectOps;
8688   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8689                                   NonConstantVal, DAG))
8690     return SDValue();
8691 
8692   // Slct is now know to be the desired identity constant when CC is true.
8693   SDValue TrueVal = OtherOp;
8694   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8695                                  OtherOp, NonConstantVal);
8696   // Unless SwapSelectOps says CC should be false.
8697   if (SwapSelectOps)
8698     std::swap(TrueVal, FalseVal);
8699 
8700   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8701                      CCOp, TrueVal, FalseVal);
8702 }
8703 
8704 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8705 static
8706 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8707                                        TargetLowering::DAGCombinerInfo &DCI) {
8708   SDValue N0 = N->getOperand(0);
8709   SDValue N1 = N->getOperand(1);
8710   if (N0.getNode()->hasOneUse())
8711     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
8712       return Result;
8713   if (N1.getNode()->hasOneUse())
8714     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
8715       return Result;
8716   return SDValue();
8717 }
8718 
8719 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8720 // (only after legalization).
8721 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8722                                  TargetLowering::DAGCombinerInfo &DCI,
8723                                  const ARMSubtarget *Subtarget) {
8724 
8725   // Only perform optimization if after legalize, and if NEON is available. We
8726   // also expected both operands to be BUILD_VECTORs.
8727   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8728       || N0.getOpcode() != ISD::BUILD_VECTOR
8729       || N1.getOpcode() != ISD::BUILD_VECTOR)
8730     return SDValue();
8731 
8732   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8733   EVT VT = N->getValueType(0);
8734   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8735     return SDValue();
8736 
8737   // Check that the vector operands are of the right form.
8738   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8739   // operands, where N is the size of the formed vector.
8740   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8741   // index such that we have a pair wise add pattern.
8742 
8743   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8744   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8745     return SDValue();
8746   SDValue Vec = N0->getOperand(0)->getOperand(0);
8747   SDNode *V = Vec.getNode();
8748   unsigned nextIndex = 0;
8749 
8750   // For each operands to the ADD which are BUILD_VECTORs,
8751   // check to see if each of their operands are an EXTRACT_VECTOR with
8752   // the same vector and appropriate index.
8753   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8754     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8755         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8756 
8757       SDValue ExtVec0 = N0->getOperand(i);
8758       SDValue ExtVec1 = N1->getOperand(i);
8759 
8760       // First operand is the vector, verify its the same.
8761       if (V != ExtVec0->getOperand(0).getNode() ||
8762           V != ExtVec1->getOperand(0).getNode())
8763         return SDValue();
8764 
8765       // Second is the constant, verify its correct.
8766       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8767       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8768 
8769       // For the constant, we want to see all the even or all the odd.
8770       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8771           || C1->getZExtValue() != nextIndex+1)
8772         return SDValue();
8773 
8774       // Increment index.
8775       nextIndex+=2;
8776     } else
8777       return SDValue();
8778   }
8779 
8780   // Create VPADDL node.
8781   SelectionDAG &DAG = DCI.DAG;
8782   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8783 
8784   SDLoc dl(N);
8785 
8786   // Build operand list.
8787   SmallVector<SDValue, 8> Ops;
8788   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8789                                 TLI.getPointerTy(DAG.getDataLayout())));
8790 
8791   // Input is the vector.
8792   Ops.push_back(Vec);
8793 
8794   // Get widened type and narrowed type.
8795   MVT widenType;
8796   unsigned numElem = VT.getVectorNumElements();
8797 
8798   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8799   switch (inputLaneType.getSimpleVT().SimpleTy) {
8800     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8801     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8802     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8803     default:
8804       llvm_unreachable("Invalid vector element type for padd optimization.");
8805   }
8806 
8807   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8808   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8809   return DAG.getNode(ExtOp, dl, VT, tmp);
8810 }
8811 
8812 static SDValue findMUL_LOHI(SDValue V) {
8813   if (V->getOpcode() == ISD::UMUL_LOHI ||
8814       V->getOpcode() == ISD::SMUL_LOHI)
8815     return V;
8816   return SDValue();
8817 }
8818 
8819 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8820                                      TargetLowering::DAGCombinerInfo &DCI,
8821                                      const ARMSubtarget *Subtarget) {
8822 
8823   // Look for multiply add opportunities.
8824   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8825   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8826   // a glue link from the first add to the second add.
8827   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8828   // a S/UMLAL instruction.
8829   //                  UMUL_LOHI
8830   //                 / :lo    \ :hi
8831   //                /          \          [no multiline comment]
8832   //    loAdd ->  ADDE         |
8833   //                 \ :glue  /
8834   //                  \      /
8835   //                    ADDC   <- hiAdd
8836   //
8837   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8838   SDValue AddcOp0 = AddcNode->getOperand(0);
8839   SDValue AddcOp1 = AddcNode->getOperand(1);
8840 
8841   // Check if the two operands are from the same mul_lohi node.
8842   if (AddcOp0.getNode() == AddcOp1.getNode())
8843     return SDValue();
8844 
8845   assert(AddcNode->getNumValues() == 2 &&
8846          AddcNode->getValueType(0) == MVT::i32 &&
8847          "Expect ADDC with two result values. First: i32");
8848 
8849   // Check that we have a glued ADDC node.
8850   if (AddcNode->getValueType(1) != MVT::Glue)
8851     return SDValue();
8852 
8853   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8854   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8855       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8856       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8857       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8858     return SDValue();
8859 
8860   // Look for the glued ADDE.
8861   SDNode* AddeNode = AddcNode->getGluedUser();
8862   if (!AddeNode)
8863     return SDValue();
8864 
8865   // Make sure it is really an ADDE.
8866   if (AddeNode->getOpcode() != ISD::ADDE)
8867     return SDValue();
8868 
8869   assert(AddeNode->getNumOperands() == 3 &&
8870          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8871          "ADDE node has the wrong inputs");
8872 
8873   // Check for the triangle shape.
8874   SDValue AddeOp0 = AddeNode->getOperand(0);
8875   SDValue AddeOp1 = AddeNode->getOperand(1);
8876 
8877   // Make sure that the ADDE operands are not coming from the same node.
8878   if (AddeOp0.getNode() == AddeOp1.getNode())
8879     return SDValue();
8880 
8881   // Find the MUL_LOHI node walking up ADDE's operands.
8882   bool IsLeftOperandMUL = false;
8883   SDValue MULOp = findMUL_LOHI(AddeOp0);
8884   if (MULOp == SDValue())
8885    MULOp = findMUL_LOHI(AddeOp1);
8886   else
8887     IsLeftOperandMUL = true;
8888   if (MULOp == SDValue())
8889     return SDValue();
8890 
8891   // Figure out the right opcode.
8892   unsigned Opc = MULOp->getOpcode();
8893   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8894 
8895   // Figure out the high and low input values to the MLAL node.
8896   SDValue* HiAdd = nullptr;
8897   SDValue* LoMul = nullptr;
8898   SDValue* LowAdd = nullptr;
8899 
8900   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8901   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8902     return SDValue();
8903 
8904   if (IsLeftOperandMUL)
8905     HiAdd = &AddeOp1;
8906   else
8907     HiAdd = &AddeOp0;
8908 
8909 
8910   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8911   // whose low result is fed to the ADDC we are checking.
8912 
8913   if (AddcOp0 == MULOp.getValue(0)) {
8914     LoMul = &AddcOp0;
8915     LowAdd = &AddcOp1;
8916   }
8917   if (AddcOp1 == MULOp.getValue(0)) {
8918     LoMul = &AddcOp1;
8919     LowAdd = &AddcOp0;
8920   }
8921 
8922   if (!LoMul)
8923     return SDValue();
8924 
8925   // Create the merged node.
8926   SelectionDAG &DAG = DCI.DAG;
8927 
8928   // Build operand list.
8929   SmallVector<SDValue, 8> Ops;
8930   Ops.push_back(LoMul->getOperand(0));
8931   Ops.push_back(LoMul->getOperand(1));
8932   Ops.push_back(*LowAdd);
8933   Ops.push_back(*HiAdd);
8934 
8935   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8936                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8937 
8938   // Replace the ADDs' nodes uses by the MLA node's values.
8939   SDValue HiMLALResult(MLALNode.getNode(), 1);
8940   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8941 
8942   SDValue LoMLALResult(MLALNode.getNode(), 0);
8943   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8944 
8945   // Return original node to notify the driver to stop replacing.
8946   SDValue resNode(AddcNode, 0);
8947   return resNode;
8948 }
8949 
8950 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode,
8951                                       TargetLowering::DAGCombinerInfo &DCI,
8952                                       const ARMSubtarget *Subtarget) {
8953   // UMAAL is similar to UMLAL except that it adds two unsigned values.
8954   // While trying to combine for the other MLAL nodes, first search for the
8955   // chance to use UMAAL. Check if Addc uses another addc node which can first
8956   // be combined into a UMLAL. The other pattern is AddcNode being combined
8957   // into an UMLAL and then using another addc is handled in ISelDAGToDAG.
8958 
8959   if (!Subtarget->hasV6Ops() ||
8960       (Subtarget->isThumb() && !Subtarget->hasThumb2()))
8961     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8962 
8963   SDNode *PrevAddc = nullptr;
8964   if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC)
8965     PrevAddc = AddcNode->getOperand(0).getNode();
8966   else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC)
8967     PrevAddc = AddcNode->getOperand(1).getNode();
8968 
8969   // If there's no addc chains, just return a search for any MLAL.
8970   if (PrevAddc == nullptr)
8971     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8972 
8973   // Try to convert the addc operand to an MLAL and if that fails try to
8974   // combine AddcNode.
8975   SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget);
8976   if (MLAL != SDValue(PrevAddc, 0))
8977     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8978 
8979   // Find the converted UMAAL or quit if it doesn't exist.
8980   SDNode *UmlalNode = nullptr;
8981   SDValue AddHi;
8982   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
8983     UmlalNode = AddcNode->getOperand(0).getNode();
8984     AddHi = AddcNode->getOperand(1);
8985   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
8986     UmlalNode = AddcNode->getOperand(1).getNode();
8987     AddHi = AddcNode->getOperand(0);
8988   } else {
8989     return SDValue();
8990   }
8991 
8992   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
8993   // the ADDC as well as Zero.
8994   auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3));
8995 
8996   if (!Zero || Zero->getZExtValue() != 0)
8997     return SDValue();
8998 
8999   // Check that we have a glued ADDC node.
9000   if (AddcNode->getValueType(1) != MVT::Glue)
9001     return SDValue();
9002 
9003   // Look for the glued ADDE.
9004   SDNode* AddeNode = AddcNode->getGluedUser();
9005   if (!AddeNode)
9006     return SDValue();
9007 
9008   if ((AddeNode->getOperand(0).getNode() == Zero &&
9009        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9010       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9011        AddeNode->getOperand(1).getNode() == Zero)) {
9012 
9013     SelectionDAG &DAG = DCI.DAG;
9014     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9015                       UmlalNode->getOperand(2), AddHi };
9016     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9017                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9018 
9019     // Replace the ADDs' nodes uses by the UMAAL node's values.
9020     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9021     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9022 
9023     // Return original node to notify the driver to stop replacing.
9024     return SDValue(AddcNode, 0);
9025   }
9026   return SDValue();
9027 }
9028 
9029 /// PerformADDCCombine - Target-specific dag combine transform from
9030 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or
9031 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9032 static SDValue PerformADDCCombine(SDNode *N,
9033                                  TargetLowering::DAGCombinerInfo &DCI,
9034                                  const ARMSubtarget *Subtarget) {
9035 
9036   if (Subtarget->isThumb1Only()) return SDValue();
9037 
9038   // Only perform the checks after legalize when the pattern is available.
9039   if (DCI.isBeforeLegalize()) return SDValue();
9040 
9041   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9042 }
9043 
9044 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9045 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9046 /// called with the default operands, and if that fails, with commuted
9047 /// operands.
9048 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9049                                           TargetLowering::DAGCombinerInfo &DCI,
9050                                           const ARMSubtarget *Subtarget){
9051 
9052   // Attempt to create vpaddl for this add.
9053   if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
9054     return Result;
9055 
9056   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9057   if (N0.getNode()->hasOneUse())
9058     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9059       return Result;
9060   return SDValue();
9061 }
9062 
9063 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9064 ///
9065 static SDValue PerformADDCombine(SDNode *N,
9066                                  TargetLowering::DAGCombinerInfo &DCI,
9067                                  const ARMSubtarget *Subtarget) {
9068   SDValue N0 = N->getOperand(0);
9069   SDValue N1 = N->getOperand(1);
9070 
9071   // First try with the default operand order.
9072   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9073     return Result;
9074 
9075   // If that didn't work, try again with the operands commuted.
9076   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9077 }
9078 
9079 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9080 ///
9081 static SDValue PerformSUBCombine(SDNode *N,
9082                                  TargetLowering::DAGCombinerInfo &DCI) {
9083   SDValue N0 = N->getOperand(0);
9084   SDValue N1 = N->getOperand(1);
9085 
9086   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9087   if (N1.getNode()->hasOneUse())
9088     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9089       return Result;
9090 
9091   return SDValue();
9092 }
9093 
9094 /// PerformVMULCombine
9095 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9096 /// special multiplier accumulator forwarding.
9097 ///   vmul d3, d0, d2
9098 ///   vmla d3, d1, d2
9099 /// is faster than
9100 ///   vadd d3, d0, d1
9101 ///   vmul d3, d3, d2
9102 //  However, for (A + B) * (A + B),
9103 //    vadd d2, d0, d1
9104 //    vmul d3, d0, d2
9105 //    vmla d3, d1, d2
9106 //  is slower than
9107 //    vadd d2, d0, d1
9108 //    vmul d3, d2, d2
9109 static SDValue PerformVMULCombine(SDNode *N,
9110                                   TargetLowering::DAGCombinerInfo &DCI,
9111                                   const ARMSubtarget *Subtarget) {
9112   if (!Subtarget->hasVMLxForwarding())
9113     return SDValue();
9114 
9115   SelectionDAG &DAG = DCI.DAG;
9116   SDValue N0 = N->getOperand(0);
9117   SDValue N1 = N->getOperand(1);
9118   unsigned Opcode = N0.getOpcode();
9119   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9120       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9121     Opcode = N1.getOpcode();
9122     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9123         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9124       return SDValue();
9125     std::swap(N0, N1);
9126   }
9127 
9128   if (N0 == N1)
9129     return SDValue();
9130 
9131   EVT VT = N->getValueType(0);
9132   SDLoc DL(N);
9133   SDValue N00 = N0->getOperand(0);
9134   SDValue N01 = N0->getOperand(1);
9135   return DAG.getNode(Opcode, DL, VT,
9136                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9137                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9138 }
9139 
9140 static SDValue PerformMULCombine(SDNode *N,
9141                                  TargetLowering::DAGCombinerInfo &DCI,
9142                                  const ARMSubtarget *Subtarget) {
9143   SelectionDAG &DAG = DCI.DAG;
9144 
9145   if (Subtarget->isThumb1Only())
9146     return SDValue();
9147 
9148   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9149     return SDValue();
9150 
9151   EVT VT = N->getValueType(0);
9152   if (VT.is64BitVector() || VT.is128BitVector())
9153     return PerformVMULCombine(N, DCI, Subtarget);
9154   if (VT != MVT::i32)
9155     return SDValue();
9156 
9157   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9158   if (!C)
9159     return SDValue();
9160 
9161   int64_t MulAmt = C->getSExtValue();
9162   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9163 
9164   ShiftAmt = ShiftAmt & (32 - 1);
9165   SDValue V = N->getOperand(0);
9166   SDLoc DL(N);
9167 
9168   SDValue Res;
9169   MulAmt >>= ShiftAmt;
9170 
9171   if (MulAmt >= 0) {
9172     if (isPowerOf2_32(MulAmt - 1)) {
9173       // (mul x, 2^N + 1) => (add (shl x, N), x)
9174       Res = DAG.getNode(ISD::ADD, DL, VT,
9175                         V,
9176                         DAG.getNode(ISD::SHL, DL, VT,
9177                                     V,
9178                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9179                                                     MVT::i32)));
9180     } else if (isPowerOf2_32(MulAmt + 1)) {
9181       // (mul x, 2^N - 1) => (sub (shl x, N), x)
9182       Res = DAG.getNode(ISD::SUB, DL, VT,
9183                         DAG.getNode(ISD::SHL, DL, VT,
9184                                     V,
9185                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
9186                                                     MVT::i32)),
9187                         V);
9188     } else
9189       return SDValue();
9190   } else {
9191     uint64_t MulAmtAbs = -MulAmt;
9192     if (isPowerOf2_32(MulAmtAbs + 1)) {
9193       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9194       Res = DAG.getNode(ISD::SUB, DL, VT,
9195                         V,
9196                         DAG.getNode(ISD::SHL, DL, VT,
9197                                     V,
9198                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9199                                                     MVT::i32)));
9200     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9201       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9202       Res = DAG.getNode(ISD::ADD, DL, VT,
9203                         V,
9204                         DAG.getNode(ISD::SHL, DL, VT,
9205                                     V,
9206                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9207                                                     MVT::i32)));
9208       Res = DAG.getNode(ISD::SUB, DL, VT,
9209                         DAG.getConstant(0, DL, MVT::i32), Res);
9210 
9211     } else
9212       return SDValue();
9213   }
9214 
9215   if (ShiftAmt != 0)
9216     Res = DAG.getNode(ISD::SHL, DL, VT,
9217                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9218 
9219   // Do not add new nodes to DAG combiner worklist.
9220   DCI.CombineTo(N, Res, false);
9221   return SDValue();
9222 }
9223 
9224 static SDValue PerformANDCombine(SDNode *N,
9225                                  TargetLowering::DAGCombinerInfo &DCI,
9226                                  const ARMSubtarget *Subtarget) {
9227 
9228   // Attempt to use immediate-form VBIC
9229   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9230   SDLoc dl(N);
9231   EVT VT = N->getValueType(0);
9232   SelectionDAG &DAG = DCI.DAG;
9233 
9234   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9235     return SDValue();
9236 
9237   APInt SplatBits, SplatUndef;
9238   unsigned SplatBitSize;
9239   bool HasAnyUndefs;
9240   if (BVN &&
9241       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9242     if (SplatBitSize <= 64) {
9243       EVT VbicVT;
9244       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9245                                       SplatUndef.getZExtValue(), SplatBitSize,
9246                                       DAG, dl, VbicVT, VT.is128BitVector(),
9247                                       OtherModImm);
9248       if (Val.getNode()) {
9249         SDValue Input =
9250           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9251         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9252         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9253       }
9254     }
9255   }
9256 
9257   if (!Subtarget->isThumb1Only()) {
9258     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9259     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9260       return Result;
9261   }
9262 
9263   return SDValue();
9264 }
9265 
9266 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
9267 static SDValue PerformORCombine(SDNode *N,
9268                                 TargetLowering::DAGCombinerInfo &DCI,
9269                                 const ARMSubtarget *Subtarget) {
9270   // Attempt to use immediate-form VORR
9271   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9272   SDLoc dl(N);
9273   EVT VT = N->getValueType(0);
9274   SelectionDAG &DAG = DCI.DAG;
9275 
9276   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9277     return SDValue();
9278 
9279   APInt SplatBits, SplatUndef;
9280   unsigned SplatBitSize;
9281   bool HasAnyUndefs;
9282   if (BVN && Subtarget->hasNEON() &&
9283       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9284     if (SplatBitSize <= 64) {
9285       EVT VorrVT;
9286       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9287                                       SplatUndef.getZExtValue(), SplatBitSize,
9288                                       DAG, dl, VorrVT, VT.is128BitVector(),
9289                                       OtherModImm);
9290       if (Val.getNode()) {
9291         SDValue Input =
9292           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9293         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9294         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9295       }
9296     }
9297   }
9298 
9299   if (!Subtarget->isThumb1Only()) {
9300     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9301     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9302       return Result;
9303   }
9304 
9305   // The code below optimizes (or (and X, Y), Z).
9306   // The AND operand needs to have a single user to make these optimizations
9307   // profitable.
9308   SDValue N0 = N->getOperand(0);
9309   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9310     return SDValue();
9311   SDValue N1 = N->getOperand(1);
9312 
9313   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9314   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9315       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9316     APInt SplatUndef;
9317     unsigned SplatBitSize;
9318     bool HasAnyUndefs;
9319 
9320     APInt SplatBits0, SplatBits1;
9321     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9322     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9323     // Ensure that the second operand of both ands are constants
9324     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9325                                       HasAnyUndefs) && !HasAnyUndefs) {
9326         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9327                                           HasAnyUndefs) && !HasAnyUndefs) {
9328             // Ensure that the bit width of the constants are the same and that
9329             // the splat arguments are logical inverses as per the pattern we
9330             // are trying to simplify.
9331             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9332                 SplatBits0 == ~SplatBits1) {
9333                 // Canonicalize the vector type to make instruction selection
9334                 // simpler.
9335                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9336                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9337                                              N0->getOperand(1),
9338                                              N0->getOperand(0),
9339                                              N1->getOperand(0));
9340                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9341             }
9342         }
9343     }
9344   }
9345 
9346   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9347   // reasonable.
9348 
9349   // BFI is only available on V6T2+
9350   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9351     return SDValue();
9352 
9353   SDLoc DL(N);
9354   // 1) or (and A, mask), val => ARMbfi A, val, mask
9355   //      iff (val & mask) == val
9356   //
9357   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9358   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9359   //          && mask == ~mask2
9360   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9361   //          && ~mask == mask2
9362   //  (i.e., copy a bitfield value into another bitfield of the same width)
9363 
9364   if (VT != MVT::i32)
9365     return SDValue();
9366 
9367   SDValue N00 = N0.getOperand(0);
9368 
9369   // The value and the mask need to be constants so we can verify this is
9370   // actually a bitfield set. If the mask is 0xffff, we can do better
9371   // via a movt instruction, so don't use BFI in that case.
9372   SDValue MaskOp = N0.getOperand(1);
9373   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9374   if (!MaskC)
9375     return SDValue();
9376   unsigned Mask = MaskC->getZExtValue();
9377   if (Mask == 0xffff)
9378     return SDValue();
9379   SDValue Res;
9380   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9381   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9382   if (N1C) {
9383     unsigned Val = N1C->getZExtValue();
9384     if ((Val & ~Mask) != Val)
9385       return SDValue();
9386 
9387     if (ARM::isBitFieldInvertedMask(Mask)) {
9388       Val >>= countTrailingZeros(~Mask);
9389 
9390       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9391                         DAG.getConstant(Val, DL, MVT::i32),
9392                         DAG.getConstant(Mask, DL, MVT::i32));
9393 
9394       // Do not add new nodes to DAG combiner worklist.
9395       DCI.CombineTo(N, Res, false);
9396       return SDValue();
9397     }
9398   } else if (N1.getOpcode() == ISD::AND) {
9399     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9400     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9401     if (!N11C)
9402       return SDValue();
9403     unsigned Mask2 = N11C->getZExtValue();
9404 
9405     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9406     // as is to match.
9407     if (ARM::isBitFieldInvertedMask(Mask) &&
9408         (Mask == ~Mask2)) {
9409       // The pack halfword instruction works better for masks that fit it,
9410       // so use that when it's available.
9411       if (Subtarget->hasT2ExtractPack() &&
9412           (Mask == 0xffff || Mask == 0xffff0000))
9413         return SDValue();
9414       // 2a
9415       unsigned amt = countTrailingZeros(Mask2);
9416       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9417                         DAG.getConstant(amt, DL, MVT::i32));
9418       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9419                         DAG.getConstant(Mask, DL, MVT::i32));
9420       // Do not add new nodes to DAG combiner worklist.
9421       DCI.CombineTo(N, Res, false);
9422       return SDValue();
9423     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9424                (~Mask == Mask2)) {
9425       // The pack halfword instruction works better for masks that fit it,
9426       // so use that when it's available.
9427       if (Subtarget->hasT2ExtractPack() &&
9428           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9429         return SDValue();
9430       // 2b
9431       unsigned lsb = countTrailingZeros(Mask);
9432       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9433                         DAG.getConstant(lsb, DL, MVT::i32));
9434       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9435                         DAG.getConstant(Mask2, DL, MVT::i32));
9436       // Do not add new nodes to DAG combiner worklist.
9437       DCI.CombineTo(N, Res, false);
9438       return SDValue();
9439     }
9440   }
9441 
9442   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9443       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9444       ARM::isBitFieldInvertedMask(~Mask)) {
9445     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9446     // where lsb(mask) == #shamt and masked bits of B are known zero.
9447     SDValue ShAmt = N00.getOperand(1);
9448     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9449     unsigned LSB = countTrailingZeros(Mask);
9450     if (ShAmtC != LSB)
9451       return SDValue();
9452 
9453     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9454                       DAG.getConstant(~Mask, DL, MVT::i32));
9455 
9456     // Do not add new nodes to DAG combiner worklist.
9457     DCI.CombineTo(N, Res, false);
9458   }
9459 
9460   return SDValue();
9461 }
9462 
9463 static SDValue PerformXORCombine(SDNode *N,
9464                                  TargetLowering::DAGCombinerInfo &DCI,
9465                                  const ARMSubtarget *Subtarget) {
9466   EVT VT = N->getValueType(0);
9467   SelectionDAG &DAG = DCI.DAG;
9468 
9469   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9470     return SDValue();
9471 
9472   if (!Subtarget->isThumb1Only()) {
9473     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9474     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9475       return Result;
9476   }
9477 
9478   return SDValue();
9479 }
9480 
9481 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9482 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9483 // their position in "to" (Rd).
9484 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9485   assert(N->getOpcode() == ARMISD::BFI);
9486 
9487   SDValue From = N->getOperand(1);
9488   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9489   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9490 
9491   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9492   // #C in the base of the SHR.
9493   if (From->getOpcode() == ISD::SRL &&
9494       isa<ConstantSDNode>(From->getOperand(1))) {
9495     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9496     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9497     FromMask <<= Shift.getLimitedValue(31);
9498     From = From->getOperand(0);
9499   }
9500 
9501   return From;
9502 }
9503 
9504 // If A and B contain one contiguous set of bits, does A | B == A . B?
9505 //
9506 // Neither A nor B must be zero.
9507 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9508   unsigned LastActiveBitInA =  A.countTrailingZeros();
9509   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9510   return LastActiveBitInA - 1 == FirstActiveBitInB;
9511 }
9512 
9513 static SDValue FindBFIToCombineWith(SDNode *N) {
9514   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9515   // if one exists.
9516   APInt ToMask, FromMask;
9517   SDValue From = ParseBFI(N, ToMask, FromMask);
9518   SDValue To = N->getOperand(0);
9519 
9520   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9521   // aren't compatible, but not if they set the same bit in their destination as
9522   // we do (or that of any BFI we're going to combine with).
9523   SDValue V = To;
9524   APInt CombinedToMask = ToMask;
9525   while (V.getOpcode() == ARMISD::BFI) {
9526     APInt NewToMask, NewFromMask;
9527     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9528     if (NewFrom != From) {
9529       // This BFI has a different base. Keep going.
9530       CombinedToMask |= NewToMask;
9531       V = V.getOperand(0);
9532       continue;
9533     }
9534 
9535     // Do the written bits conflict with any we've seen so far?
9536     if ((NewToMask & CombinedToMask).getBoolValue())
9537       // Conflicting bits - bail out because going further is unsafe.
9538       return SDValue();
9539 
9540     // Are the new bits contiguous when combined with the old bits?
9541     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9542         BitsProperlyConcatenate(FromMask, NewFromMask))
9543       return V;
9544     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9545         BitsProperlyConcatenate(NewFromMask, FromMask))
9546       return V;
9547 
9548     // We've seen a write to some bits, so track it.
9549     CombinedToMask |= NewToMask;
9550     // Keep going...
9551     V = V.getOperand(0);
9552   }
9553 
9554   return SDValue();
9555 }
9556 
9557 static SDValue PerformBFICombine(SDNode *N,
9558                                  TargetLowering::DAGCombinerInfo &DCI) {
9559   SDValue N1 = N->getOperand(1);
9560   if (N1.getOpcode() == ISD::AND) {
9561     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9562     // the bits being cleared by the AND are not demanded by the BFI.
9563     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9564     if (!N11C)
9565       return SDValue();
9566     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9567     unsigned LSB = countTrailingZeros(~InvMask);
9568     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9569     assert(Width <
9570                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9571            "undefined behavior");
9572     unsigned Mask = (1u << Width) - 1;
9573     unsigned Mask2 = N11C->getZExtValue();
9574     if ((Mask & (~Mask2)) == 0)
9575       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9576                              N->getOperand(0), N1.getOperand(0),
9577                              N->getOperand(2));
9578   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9579     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9580     // Keep track of any consecutive bits set that all come from the same base
9581     // value. We can combine these together into a single BFI.
9582     SDValue CombineBFI = FindBFIToCombineWith(N);
9583     if (CombineBFI == SDValue())
9584       return SDValue();
9585 
9586     // We've found a BFI.
9587     APInt ToMask1, FromMask1;
9588     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9589 
9590     APInt ToMask2, FromMask2;
9591     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9592     assert(From1 == From2);
9593     (void)From2;
9594 
9595     // First, unlink CombineBFI.
9596     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9597     // Then create a new BFI, combining the two together.
9598     APInt NewFromMask = FromMask1 | FromMask2;
9599     APInt NewToMask = ToMask1 | ToMask2;
9600 
9601     EVT VT = N->getValueType(0);
9602     SDLoc dl(N);
9603 
9604     if (NewFromMask[0] == 0)
9605       From1 = DCI.DAG.getNode(
9606         ISD::SRL, dl, VT, From1,
9607         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9608     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9609                            DCI.DAG.getConstant(~NewToMask, dl, VT));
9610   }
9611   return SDValue();
9612 }
9613 
9614 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9615 /// ARMISD::VMOVRRD.
9616 static SDValue PerformVMOVRRDCombine(SDNode *N,
9617                                      TargetLowering::DAGCombinerInfo &DCI,
9618                                      const ARMSubtarget *Subtarget) {
9619   // vmovrrd(vmovdrr x, y) -> x,y
9620   SDValue InDouble = N->getOperand(0);
9621   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9622     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9623 
9624   // vmovrrd(load f64) -> (load i32), (load i32)
9625   SDNode *InNode = InDouble.getNode();
9626   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9627       InNode->getValueType(0) == MVT::f64 &&
9628       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9629       !cast<LoadSDNode>(InNode)->isVolatile()) {
9630     // TODO: Should this be done for non-FrameIndex operands?
9631     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9632 
9633     SelectionDAG &DAG = DCI.DAG;
9634     SDLoc DL(LD);
9635     SDValue BasePtr = LD->getBasePtr();
9636     SDValue NewLD1 =
9637         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
9638                     LD->getAlignment(), LD->getMemOperand()->getFlags());
9639 
9640     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9641                                     DAG.getConstant(4, DL, MVT::i32));
9642     SDValue NewLD2 = DAG.getLoad(
9643         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
9644         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
9645 
9646     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9647     if (DCI.DAG.getDataLayout().isBigEndian())
9648       std::swap (NewLD1, NewLD2);
9649     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9650     return Result;
9651   }
9652 
9653   return SDValue();
9654 }
9655 
9656 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9657 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9658 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9659   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9660   SDValue Op0 = N->getOperand(0);
9661   SDValue Op1 = N->getOperand(1);
9662   if (Op0.getOpcode() == ISD::BITCAST)
9663     Op0 = Op0.getOperand(0);
9664   if (Op1.getOpcode() == ISD::BITCAST)
9665     Op1 = Op1.getOperand(0);
9666   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9667       Op0.getNode() == Op1.getNode() &&
9668       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9669     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9670                        N->getValueType(0), Op0.getOperand(0));
9671   return SDValue();
9672 }
9673 
9674 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9675 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9676 /// i64 vector to have f64 elements, since the value can then be loaded
9677 /// directly into a VFP register.
9678 static bool hasNormalLoadOperand(SDNode *N) {
9679   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9680   for (unsigned i = 0; i < NumElts; ++i) {
9681     SDNode *Elt = N->getOperand(i).getNode();
9682     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9683       return true;
9684   }
9685   return false;
9686 }
9687 
9688 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9689 /// ISD::BUILD_VECTOR.
9690 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9691                                           TargetLowering::DAGCombinerInfo &DCI,
9692                                           const ARMSubtarget *Subtarget) {
9693   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9694   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9695   // into a pair of GPRs, which is fine when the value is used as a scalar,
9696   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9697   SelectionDAG &DAG = DCI.DAG;
9698   if (N->getNumOperands() == 2)
9699     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
9700       return RV;
9701 
9702   // Load i64 elements as f64 values so that type legalization does not split
9703   // them up into i32 values.
9704   EVT VT = N->getValueType(0);
9705   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9706     return SDValue();
9707   SDLoc dl(N);
9708   SmallVector<SDValue, 8> Ops;
9709   unsigned NumElts = VT.getVectorNumElements();
9710   for (unsigned i = 0; i < NumElts; ++i) {
9711     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9712     Ops.push_back(V);
9713     // Make the DAGCombiner fold the bitcast.
9714     DCI.AddToWorklist(V.getNode());
9715   }
9716   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9717   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
9718   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9719 }
9720 
9721 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9722 static SDValue
9723 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9724   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9725   // At that time, we may have inserted bitcasts from integer to float.
9726   // If these bitcasts have survived DAGCombine, change the lowering of this
9727   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9728   // force to use floating point types.
9729 
9730   // Make sure we can change the type of the vector.
9731   // This is possible iff:
9732   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9733   //    1.1. Vector is used only once.
9734   //    1.2. Use is a bit convert to an integer type.
9735   // 2. The size of its operands are 32-bits (64-bits are not legal).
9736   EVT VT = N->getValueType(0);
9737   EVT EltVT = VT.getVectorElementType();
9738 
9739   // Check 1.1. and 2.
9740   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9741     return SDValue();
9742 
9743   // By construction, the input type must be float.
9744   assert(EltVT == MVT::f32 && "Unexpected type!");
9745 
9746   // Check 1.2.
9747   SDNode *Use = *N->use_begin();
9748   if (Use->getOpcode() != ISD::BITCAST ||
9749       Use->getValueType(0).isFloatingPoint())
9750     return SDValue();
9751 
9752   // Check profitability.
9753   // Model is, if more than half of the relevant operands are bitcast from
9754   // i32, turn the build_vector into a sequence of insert_vector_elt.
9755   // Relevant operands are everything that is not statically
9756   // (i.e., at compile time) bitcasted.
9757   unsigned NumOfBitCastedElts = 0;
9758   unsigned NumElts = VT.getVectorNumElements();
9759   unsigned NumOfRelevantElts = NumElts;
9760   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9761     SDValue Elt = N->getOperand(Idx);
9762     if (Elt->getOpcode() == ISD::BITCAST) {
9763       // Assume only bit cast to i32 will go away.
9764       if (Elt->getOperand(0).getValueType() == MVT::i32)
9765         ++NumOfBitCastedElts;
9766     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
9767       // Constants are statically casted, thus do not count them as
9768       // relevant operands.
9769       --NumOfRelevantElts;
9770   }
9771 
9772   // Check if more than half of the elements require a non-free bitcast.
9773   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9774     return SDValue();
9775 
9776   SelectionDAG &DAG = DCI.DAG;
9777   // Create the new vector type.
9778   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9779   // Check if the type is legal.
9780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9781   if (!TLI.isTypeLegal(VecVT))
9782     return SDValue();
9783 
9784   // Combine:
9785   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9786   // => BITCAST INSERT_VECTOR_ELT
9787   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9788   //                      (BITCAST EN), N.
9789   SDValue Vec = DAG.getUNDEF(VecVT);
9790   SDLoc dl(N);
9791   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9792     SDValue V = N->getOperand(Idx);
9793     if (V.isUndef())
9794       continue;
9795     if (V.getOpcode() == ISD::BITCAST &&
9796         V->getOperand(0).getValueType() == MVT::i32)
9797       // Fold obvious case.
9798       V = V.getOperand(0);
9799     else {
9800       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9801       // Make the DAGCombiner fold the bitcasts.
9802       DCI.AddToWorklist(V.getNode());
9803     }
9804     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9805     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9806   }
9807   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9808   // Make the DAGCombiner fold the bitcasts.
9809   DCI.AddToWorklist(Vec.getNode());
9810   return Vec;
9811 }
9812 
9813 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9814 /// ISD::INSERT_VECTOR_ELT.
9815 static SDValue PerformInsertEltCombine(SDNode *N,
9816                                        TargetLowering::DAGCombinerInfo &DCI) {
9817   // Bitcast an i64 load inserted into a vector to f64.
9818   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9819   EVT VT = N->getValueType(0);
9820   SDNode *Elt = N->getOperand(1).getNode();
9821   if (VT.getVectorElementType() != MVT::i64 ||
9822       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9823     return SDValue();
9824 
9825   SelectionDAG &DAG = DCI.DAG;
9826   SDLoc dl(N);
9827   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9828                                  VT.getVectorNumElements());
9829   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9830   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9831   // Make the DAGCombiner fold the bitcasts.
9832   DCI.AddToWorklist(Vec.getNode());
9833   DCI.AddToWorklist(V.getNode());
9834   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9835                                Vec, V, N->getOperand(2));
9836   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9837 }
9838 
9839 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9840 /// ISD::VECTOR_SHUFFLE.
9841 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9842   // The LLVM shufflevector instruction does not require the shuffle mask
9843   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9844   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9845   // operands do not match the mask length, they are extended by concatenating
9846   // them with undef vectors.  That is probably the right thing for other
9847   // targets, but for NEON it is better to concatenate two double-register
9848   // size vector operands into a single quad-register size vector.  Do that
9849   // transformation here:
9850   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9851   //   shuffle(concat(v1, v2), undef)
9852   SDValue Op0 = N->getOperand(0);
9853   SDValue Op1 = N->getOperand(1);
9854   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9855       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9856       Op0.getNumOperands() != 2 ||
9857       Op1.getNumOperands() != 2)
9858     return SDValue();
9859   SDValue Concat0Op1 = Op0.getOperand(1);
9860   SDValue Concat1Op1 = Op1.getOperand(1);
9861   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
9862     return SDValue();
9863   // Skip the transformation if any of the types are illegal.
9864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9865   EVT VT = N->getValueType(0);
9866   if (!TLI.isTypeLegal(VT) ||
9867       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9868       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9869     return SDValue();
9870 
9871   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9872                                   Op0.getOperand(0), Op1.getOperand(0));
9873   // Translate the shuffle mask.
9874   SmallVector<int, 16> NewMask;
9875   unsigned NumElts = VT.getVectorNumElements();
9876   unsigned HalfElts = NumElts/2;
9877   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9878   for (unsigned n = 0; n < NumElts; ++n) {
9879     int MaskElt = SVN->getMaskElt(n);
9880     int NewElt = -1;
9881     if (MaskElt < (int)HalfElts)
9882       NewElt = MaskElt;
9883     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9884       NewElt = HalfElts + MaskElt - NumElts;
9885     NewMask.push_back(NewElt);
9886   }
9887   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9888                               DAG.getUNDEF(VT), NewMask);
9889 }
9890 
9891 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9892 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9893 /// base address updates.
9894 /// For generic load/stores, the memory type is assumed to be a vector.
9895 /// The caller is assumed to have checked legality.
9896 static SDValue CombineBaseUpdate(SDNode *N,
9897                                  TargetLowering::DAGCombinerInfo &DCI) {
9898   SelectionDAG &DAG = DCI.DAG;
9899   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9900                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9901   const bool isStore = N->getOpcode() == ISD::STORE;
9902   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9903   SDValue Addr = N->getOperand(AddrOpIdx);
9904   MemSDNode *MemN = cast<MemSDNode>(N);
9905   SDLoc dl(N);
9906 
9907   // Search for a use of the address operand that is an increment.
9908   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9909          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9910     SDNode *User = *UI;
9911     if (User->getOpcode() != ISD::ADD ||
9912         UI.getUse().getResNo() != Addr.getResNo())
9913       continue;
9914 
9915     // Check that the add is independent of the load/store.  Otherwise, folding
9916     // it would create a cycle.
9917     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9918       continue;
9919 
9920     // Find the new opcode for the updating load/store.
9921     bool isLoadOp = true;
9922     bool isLaneOp = false;
9923     unsigned NewOpc = 0;
9924     unsigned NumVecs = 0;
9925     if (isIntrinsic) {
9926       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9927       switch (IntNo) {
9928       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9929       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9930         NumVecs = 1; break;
9931       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9932         NumVecs = 2; break;
9933       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9934         NumVecs = 3; break;
9935       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9936         NumVecs = 4; break;
9937       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9938         NumVecs = 2; isLaneOp = true; break;
9939       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9940         NumVecs = 3; isLaneOp = true; break;
9941       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9942         NumVecs = 4; isLaneOp = true; break;
9943       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9944         NumVecs = 1; isLoadOp = false; break;
9945       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9946         NumVecs = 2; isLoadOp = false; break;
9947       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9948         NumVecs = 3; isLoadOp = false; break;
9949       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9950         NumVecs = 4; isLoadOp = false; break;
9951       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9952         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9953       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9954         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9955       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9956         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9957       }
9958     } else {
9959       isLaneOp = true;
9960       switch (N->getOpcode()) {
9961       default: llvm_unreachable("unexpected opcode for Neon base update");
9962       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9963       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9964       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9965       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9966         NumVecs = 1; isLaneOp = false; break;
9967       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9968         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9969       }
9970     }
9971 
9972     // Find the size of memory referenced by the load/store.
9973     EVT VecTy;
9974     if (isLoadOp) {
9975       VecTy = N->getValueType(0);
9976     } else if (isIntrinsic) {
9977       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9978     } else {
9979       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9980       VecTy = N->getOperand(1).getValueType();
9981     }
9982 
9983     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9984     if (isLaneOp)
9985       NumBytes /= VecTy.getVectorNumElements();
9986 
9987     // If the increment is a constant, it must match the memory ref size.
9988     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9989     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9990       uint64_t IncVal = CInc->getZExtValue();
9991       if (IncVal != NumBytes)
9992         continue;
9993     } else if (NumBytes >= 3 * 16) {
9994       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9995       // separate instructions that make it harder to use a non-constant update.
9996       continue;
9997     }
9998 
9999     // OK, we found an ADD we can fold into the base update.
10000     // Now, create a _UPD node, taking care of not breaking alignment.
10001 
10002     EVT AlignedVecTy = VecTy;
10003     unsigned Alignment = MemN->getAlignment();
10004 
10005     // If this is a less-than-standard-aligned load/store, change the type to
10006     // match the standard alignment.
10007     // The alignment is overlooked when selecting _UPD variants; and it's
10008     // easier to introduce bitcasts here than fix that.
10009     // There are 3 ways to get to this base-update combine:
10010     // - intrinsics: they are assumed to be properly aligned (to the standard
10011     //   alignment of the memory type), so we don't need to do anything.
10012     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10013     //   intrinsics, so, likewise, there's nothing to do.
10014     // - generic load/store instructions: the alignment is specified as an
10015     //   explicit operand, rather than implicitly as the standard alignment
10016     //   of the memory type (like the intrisics).  We need to change the
10017     //   memory type to match the explicit alignment.  That way, we don't
10018     //   generate non-standard-aligned ARMISD::VLDx nodes.
10019     if (isa<LSBaseSDNode>(N)) {
10020       if (Alignment == 0)
10021         Alignment = 1;
10022       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10023         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10024         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10025         assert(!isLaneOp && "Unexpected generic load/store lane.");
10026         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10027         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10028       }
10029       // Don't set an explicit alignment on regular load/stores that we want
10030       // to transform to VLD/VST 1_UPD nodes.
10031       // This matches the behavior of regular load/stores, which only get an
10032       // explicit alignment if the MMO alignment is larger than the standard
10033       // alignment of the memory type.
10034       // Intrinsics, however, always get an explicit alignment, set to the
10035       // alignment of the MMO.
10036       Alignment = 1;
10037     }
10038 
10039     // Create the new updating load/store node.
10040     // First, create an SDVTList for the new updating node's results.
10041     EVT Tys[6];
10042     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10043     unsigned n;
10044     for (n = 0; n < NumResultVecs; ++n)
10045       Tys[n] = AlignedVecTy;
10046     Tys[n++] = MVT::i32;
10047     Tys[n] = MVT::Other;
10048     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10049 
10050     // Then, gather the new node's operands.
10051     SmallVector<SDValue, 8> Ops;
10052     Ops.push_back(N->getOperand(0)); // incoming chain
10053     Ops.push_back(N->getOperand(AddrOpIdx));
10054     Ops.push_back(Inc);
10055 
10056     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10057       // Try to match the intrinsic's signature
10058       Ops.push_back(StN->getValue());
10059     } else {
10060       // Loads (and of course intrinsics) match the intrinsics' signature,
10061       // so just add all but the alignment operand.
10062       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10063         Ops.push_back(N->getOperand(i));
10064     }
10065 
10066     // For all node types, the alignment operand is always the last one.
10067     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10068 
10069     // If this is a non-standard-aligned STORE, the penultimate operand is the
10070     // stored value.  Bitcast it to the aligned type.
10071     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10072       SDValue &StVal = Ops[Ops.size()-2];
10073       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10074     }
10075 
10076     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
10077                                            Ops, AlignedVecTy,
10078                                            MemN->getMemOperand());
10079 
10080     // Update the uses.
10081     SmallVector<SDValue, 5> NewResults;
10082     for (unsigned i = 0; i < NumResultVecs; ++i)
10083       NewResults.push_back(SDValue(UpdN.getNode(), i));
10084 
10085     // If this is an non-standard-aligned LOAD, the first result is the loaded
10086     // value.  Bitcast it to the expected result type.
10087     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10088       SDValue &LdVal = NewResults[0];
10089       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10090     }
10091 
10092     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10093     DCI.CombineTo(N, NewResults);
10094     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10095 
10096     break;
10097   }
10098   return SDValue();
10099 }
10100 
10101 static SDValue PerformVLDCombine(SDNode *N,
10102                                  TargetLowering::DAGCombinerInfo &DCI) {
10103   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10104     return SDValue();
10105 
10106   return CombineBaseUpdate(N, DCI);
10107 }
10108 
10109 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10110 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10111 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10112 /// return true.
10113 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10114   SelectionDAG &DAG = DCI.DAG;
10115   EVT VT = N->getValueType(0);
10116   // vldN-dup instructions only support 64-bit vectors for N > 1.
10117   if (!VT.is64BitVector())
10118     return false;
10119 
10120   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10121   SDNode *VLD = N->getOperand(0).getNode();
10122   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10123     return false;
10124   unsigned NumVecs = 0;
10125   unsigned NewOpc = 0;
10126   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10127   if (IntNo == Intrinsic::arm_neon_vld2lane) {
10128     NumVecs = 2;
10129     NewOpc = ARMISD::VLD2DUP;
10130   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10131     NumVecs = 3;
10132     NewOpc = ARMISD::VLD3DUP;
10133   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10134     NumVecs = 4;
10135     NewOpc = ARMISD::VLD4DUP;
10136   } else {
10137     return false;
10138   }
10139 
10140   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10141   // numbers match the load.
10142   unsigned VLDLaneNo =
10143     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10144   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10145        UI != UE; ++UI) {
10146     // Ignore uses of the chain result.
10147     if (UI.getUse().getResNo() == NumVecs)
10148       continue;
10149     SDNode *User = *UI;
10150     if (User->getOpcode() != ARMISD::VDUPLANE ||
10151         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10152       return false;
10153   }
10154 
10155   // Create the vldN-dup node.
10156   EVT Tys[5];
10157   unsigned n;
10158   for (n = 0; n < NumVecs; ++n)
10159     Tys[n] = VT;
10160   Tys[n] = MVT::Other;
10161   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10162   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10163   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10164   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10165                                            Ops, VLDMemInt->getMemoryVT(),
10166                                            VLDMemInt->getMemOperand());
10167 
10168   // Update the uses.
10169   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10170        UI != UE; ++UI) {
10171     unsigned ResNo = UI.getUse().getResNo();
10172     // Ignore uses of the chain result.
10173     if (ResNo == NumVecs)
10174       continue;
10175     SDNode *User = *UI;
10176     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10177   }
10178 
10179   // Now the vldN-lane intrinsic is dead except for its chain result.
10180   // Update uses of the chain.
10181   std::vector<SDValue> VLDDupResults;
10182   for (unsigned n = 0; n < NumVecs; ++n)
10183     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10184   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10185   DCI.CombineTo(VLD, VLDDupResults);
10186 
10187   return true;
10188 }
10189 
10190 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10191 /// ARMISD::VDUPLANE.
10192 static SDValue PerformVDUPLANECombine(SDNode *N,
10193                                       TargetLowering::DAGCombinerInfo &DCI) {
10194   SDValue Op = N->getOperand(0);
10195 
10196   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
10197   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
10198   if (CombineVLDDUP(N, DCI))
10199     return SDValue(N, 0);
10200 
10201   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
10202   // redundant.  Ignore bit_converts for now; element sizes are checked below.
10203   while (Op.getOpcode() == ISD::BITCAST)
10204     Op = Op.getOperand(0);
10205   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
10206     return SDValue();
10207 
10208   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
10209   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
10210   // The canonical VMOV for a zero vector uses a 32-bit element size.
10211   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10212   unsigned EltBits;
10213   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
10214     EltSize = 8;
10215   EVT VT = N->getValueType(0);
10216   if (EltSize > VT.getVectorElementType().getSizeInBits())
10217     return SDValue();
10218 
10219   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
10220 }
10221 
10222 static SDValue PerformLOADCombine(SDNode *N,
10223                                   TargetLowering::DAGCombinerInfo &DCI) {
10224   EVT VT = N->getValueType(0);
10225 
10226   // If this is a legal vector load, try to combine it into a VLD1_UPD.
10227   if (ISD::isNormalLoad(N) && VT.isVector() &&
10228       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10229     return CombineBaseUpdate(N, DCI);
10230 
10231   return SDValue();
10232 }
10233 
10234 /// PerformSTORECombine - Target-specific dag combine xforms for
10235 /// ISD::STORE.
10236 static SDValue PerformSTORECombine(SDNode *N,
10237                                    TargetLowering::DAGCombinerInfo &DCI) {
10238   StoreSDNode *St = cast<StoreSDNode>(N);
10239   if (St->isVolatile())
10240     return SDValue();
10241 
10242   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
10243   // pack all of the elements in one place.  Next, store to memory in fewer
10244   // chunks.
10245   SDValue StVal = St->getValue();
10246   EVT VT = StVal.getValueType();
10247   if (St->isTruncatingStore() && VT.isVector()) {
10248     SelectionDAG &DAG = DCI.DAG;
10249     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10250     EVT StVT = St->getMemoryVT();
10251     unsigned NumElems = VT.getVectorNumElements();
10252     assert(StVT != VT && "Cannot truncate to the same type");
10253     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
10254     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
10255 
10256     // From, To sizes and ElemCount must be pow of two
10257     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
10258 
10259     // We are going to use the original vector elt for storing.
10260     // Accumulated smaller vector elements must be a multiple of the store size.
10261     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
10262 
10263     unsigned SizeRatio  = FromEltSz / ToEltSz;
10264     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
10265 
10266     // Create a type on which we perform the shuffle.
10267     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
10268                                      NumElems*SizeRatio);
10269     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
10270 
10271     SDLoc DL(St);
10272     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
10273     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
10274     for (unsigned i = 0; i < NumElems; ++i)
10275       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
10276                           ? (i + 1) * SizeRatio - 1
10277                           : i * SizeRatio;
10278 
10279     // Can't shuffle using an illegal type.
10280     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10281 
10282     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10283                                 DAG.getUNDEF(WideVec.getValueType()),
10284                                 ShuffleVec);
10285     // At this point all of the data is stored at the bottom of the
10286     // register. We now need to save it to mem.
10287 
10288     // Find the largest store unit
10289     MVT StoreType = MVT::i8;
10290     for (MVT Tp : MVT::integer_valuetypes()) {
10291       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10292         StoreType = Tp;
10293     }
10294     // Didn't find a legal store type.
10295     if (!TLI.isTypeLegal(StoreType))
10296       return SDValue();
10297 
10298     // Bitcast the original vector into a vector of store-size units
10299     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10300             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10301     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10302     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10303     SmallVector<SDValue, 8> Chains;
10304     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10305                                         TLI.getPointerTy(DAG.getDataLayout()));
10306     SDValue BasePtr = St->getBasePtr();
10307 
10308     // Perform one or more big stores into memory.
10309     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10310     for (unsigned I = 0; I < E; I++) {
10311       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10312                                    StoreType, ShuffWide,
10313                                    DAG.getIntPtrConstant(I, DL));
10314       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10315                                 St->getPointerInfo(), St->getAlignment(),
10316                                 St->getMemOperand()->getFlags());
10317       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10318                             Increment);
10319       Chains.push_back(Ch);
10320     }
10321     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10322   }
10323 
10324   if (!ISD::isNormalStore(St))
10325     return SDValue();
10326 
10327   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10328   // ARM stores of arguments in the same cache line.
10329   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10330       StVal.getNode()->hasOneUse()) {
10331     SelectionDAG  &DAG = DCI.DAG;
10332     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10333     SDLoc DL(St);
10334     SDValue BasePtr = St->getBasePtr();
10335     SDValue NewST1 = DAG.getStore(
10336         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
10337         BasePtr, St->getPointerInfo(), St->getAlignment(),
10338         St->getMemOperand()->getFlags());
10339 
10340     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10341                                     DAG.getConstant(4, DL, MVT::i32));
10342     return DAG.getStore(NewST1.getValue(0), DL,
10343                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10344                         OffsetPtr, St->getPointerInfo(),
10345                         std::min(4U, St->getAlignment() / 2),
10346                         St->getMemOperand()->getFlags());
10347   }
10348 
10349   if (StVal.getValueType() == MVT::i64 &&
10350       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10351 
10352     // Bitcast an i64 store extracted from a vector to f64.
10353     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10354     SelectionDAG &DAG = DCI.DAG;
10355     SDLoc dl(StVal);
10356     SDValue IntVec = StVal.getOperand(0);
10357     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10358                                    IntVec.getValueType().getVectorNumElements());
10359     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10360     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10361                                  Vec, StVal.getOperand(1));
10362     dl = SDLoc(N);
10363     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10364     // Make the DAGCombiner fold the bitcasts.
10365     DCI.AddToWorklist(Vec.getNode());
10366     DCI.AddToWorklist(ExtElt.getNode());
10367     DCI.AddToWorklist(V.getNode());
10368     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10369                         St->getPointerInfo(), St->getAlignment(),
10370                         St->getMemOperand()->getFlags(), St->getAAInfo());
10371   }
10372 
10373   // If this is a legal vector store, try to combine it into a VST1_UPD.
10374   if (ISD::isNormalStore(N) && VT.isVector() &&
10375       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10376     return CombineBaseUpdate(N, DCI);
10377 
10378   return SDValue();
10379 }
10380 
10381 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10382 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10383 /// when the VMUL has a constant operand that is a power of 2.
10384 ///
10385 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10386 ///  vmul.f32        d16, d17, d16
10387 ///  vcvt.s32.f32    d16, d16
10388 /// becomes:
10389 ///  vcvt.s32.f32    d16, d16, #3
10390 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10391                                   const ARMSubtarget *Subtarget) {
10392   if (!Subtarget->hasNEON())
10393     return SDValue();
10394 
10395   SDValue Op = N->getOperand(0);
10396   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10397       Op.getOpcode() != ISD::FMUL)
10398     return SDValue();
10399 
10400   SDValue ConstVec = Op->getOperand(1);
10401   if (!isa<BuildVectorSDNode>(ConstVec))
10402     return SDValue();
10403 
10404   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10405   uint32_t FloatBits = FloatTy.getSizeInBits();
10406   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10407   uint32_t IntBits = IntTy.getSizeInBits();
10408   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10409   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10410     // These instructions only exist converting from f32 to i32. We can handle
10411     // smaller integers by generating an extra truncate, but larger ones would
10412     // be lossy. We also can't handle more then 4 lanes, since these intructions
10413     // only support v2i32/v4i32 types.
10414     return SDValue();
10415   }
10416 
10417   BitVector UndefElements;
10418   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10419   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10420   if (C == -1 || C == 0 || C > 32)
10421     return SDValue();
10422 
10423   SDLoc dl(N);
10424   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10425   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10426     Intrinsic::arm_neon_vcvtfp2fxu;
10427   SDValue FixConv = DAG.getNode(
10428       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10429       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10430       DAG.getConstant(C, dl, MVT::i32));
10431 
10432   if (IntBits < FloatBits)
10433     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10434 
10435   return FixConv;
10436 }
10437 
10438 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10439 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10440 /// when the VDIV has a constant operand that is a power of 2.
10441 ///
10442 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10443 ///  vcvt.f32.s32    d16, d16
10444 ///  vdiv.f32        d16, d17, d16
10445 /// becomes:
10446 ///  vcvt.f32.s32    d16, d16, #3
10447 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10448                                   const ARMSubtarget *Subtarget) {
10449   if (!Subtarget->hasNEON())
10450     return SDValue();
10451 
10452   SDValue Op = N->getOperand(0);
10453   unsigned OpOpcode = Op.getNode()->getOpcode();
10454   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
10455       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10456     return SDValue();
10457 
10458   SDValue ConstVec = N->getOperand(1);
10459   if (!isa<BuildVectorSDNode>(ConstVec))
10460     return SDValue();
10461 
10462   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10463   uint32_t FloatBits = FloatTy.getSizeInBits();
10464   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10465   uint32_t IntBits = IntTy.getSizeInBits();
10466   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10467   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10468     // These instructions only exist converting from i32 to f32. We can handle
10469     // smaller integers by generating an extra extend, but larger ones would
10470     // be lossy. We also can't handle more then 4 lanes, since these intructions
10471     // only support v2i32/v4i32 types.
10472     return SDValue();
10473   }
10474 
10475   BitVector UndefElements;
10476   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10477   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10478   if (C == -1 || C == 0 || C > 32)
10479     return SDValue();
10480 
10481   SDLoc dl(N);
10482   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10483   SDValue ConvInput = Op.getOperand(0);
10484   if (IntBits < FloatBits)
10485     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10486                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10487                             ConvInput);
10488 
10489   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10490     Intrinsic::arm_neon_vcvtfxu2fp;
10491   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10492                      Op.getValueType(),
10493                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10494                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10495 }
10496 
10497 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10498 /// operand of a vector shift operation, where all the elements of the
10499 /// build_vector must have the same constant integer value.
10500 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10501   // Ignore bit_converts.
10502   while (Op.getOpcode() == ISD::BITCAST)
10503     Op = Op.getOperand(0);
10504   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10505   APInt SplatBits, SplatUndef;
10506   unsigned SplatBitSize;
10507   bool HasAnyUndefs;
10508   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10509                                       HasAnyUndefs, ElementBits) ||
10510       SplatBitSize > ElementBits)
10511     return false;
10512   Cnt = SplatBits.getSExtValue();
10513   return true;
10514 }
10515 
10516 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10517 /// operand of a vector shift left operation.  That value must be in the range:
10518 ///   0 <= Value < ElementBits for a left shift; or
10519 ///   0 <= Value <= ElementBits for a long left shift.
10520 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10521   assert(VT.isVector() && "vector shift count is not a vector type");
10522   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10523   if (! getVShiftImm(Op, ElementBits, Cnt))
10524     return false;
10525   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10526 }
10527 
10528 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10529 /// operand of a vector shift right operation.  For a shift opcode, the value
10530 /// is positive, but for an intrinsic the value count must be negative. The
10531 /// absolute value must be in the range:
10532 ///   1 <= |Value| <= ElementBits for a right shift; or
10533 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10534 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10535                          int64_t &Cnt) {
10536   assert(VT.isVector() && "vector shift count is not a vector type");
10537   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10538   if (! getVShiftImm(Op, ElementBits, Cnt))
10539     return false;
10540   if (!isIntrinsic)
10541     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10542   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10543     Cnt = -Cnt;
10544     return true;
10545   }
10546   return false;
10547 }
10548 
10549 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10550 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10551   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10552   switch (IntNo) {
10553   default:
10554     // Don't do anything for most intrinsics.
10555     break;
10556 
10557   // Vector shifts: check for immediate versions and lower them.
10558   // Note: This is done during DAG combining instead of DAG legalizing because
10559   // the build_vectors for 64-bit vector element shift counts are generally
10560   // not legal, and it is hard to see their values after they get legalized to
10561   // loads from a constant pool.
10562   case Intrinsic::arm_neon_vshifts:
10563   case Intrinsic::arm_neon_vshiftu:
10564   case Intrinsic::arm_neon_vrshifts:
10565   case Intrinsic::arm_neon_vrshiftu:
10566   case Intrinsic::arm_neon_vrshiftn:
10567   case Intrinsic::arm_neon_vqshifts:
10568   case Intrinsic::arm_neon_vqshiftu:
10569   case Intrinsic::arm_neon_vqshiftsu:
10570   case Intrinsic::arm_neon_vqshiftns:
10571   case Intrinsic::arm_neon_vqshiftnu:
10572   case Intrinsic::arm_neon_vqshiftnsu:
10573   case Intrinsic::arm_neon_vqrshiftns:
10574   case Intrinsic::arm_neon_vqrshiftnu:
10575   case Intrinsic::arm_neon_vqrshiftnsu: {
10576     EVT VT = N->getOperand(1).getValueType();
10577     int64_t Cnt;
10578     unsigned VShiftOpc = 0;
10579 
10580     switch (IntNo) {
10581     case Intrinsic::arm_neon_vshifts:
10582     case Intrinsic::arm_neon_vshiftu:
10583       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10584         VShiftOpc = ARMISD::VSHL;
10585         break;
10586       }
10587       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10588         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10589                      ARMISD::VSHRs : ARMISD::VSHRu);
10590         break;
10591       }
10592       return SDValue();
10593 
10594     case Intrinsic::arm_neon_vrshifts:
10595     case Intrinsic::arm_neon_vrshiftu:
10596       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10597         break;
10598       return SDValue();
10599 
10600     case Intrinsic::arm_neon_vqshifts:
10601     case Intrinsic::arm_neon_vqshiftu:
10602       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10603         break;
10604       return SDValue();
10605 
10606     case Intrinsic::arm_neon_vqshiftsu:
10607       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10608         break;
10609       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10610 
10611     case Intrinsic::arm_neon_vrshiftn:
10612     case Intrinsic::arm_neon_vqshiftns:
10613     case Intrinsic::arm_neon_vqshiftnu:
10614     case Intrinsic::arm_neon_vqshiftnsu:
10615     case Intrinsic::arm_neon_vqrshiftns:
10616     case Intrinsic::arm_neon_vqrshiftnu:
10617     case Intrinsic::arm_neon_vqrshiftnsu:
10618       // Narrowing shifts require an immediate right shift.
10619       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10620         break;
10621       llvm_unreachable("invalid shift count for narrowing vector shift "
10622                        "intrinsic");
10623 
10624     default:
10625       llvm_unreachable("unhandled vector shift");
10626     }
10627 
10628     switch (IntNo) {
10629     case Intrinsic::arm_neon_vshifts:
10630     case Intrinsic::arm_neon_vshiftu:
10631       // Opcode already set above.
10632       break;
10633     case Intrinsic::arm_neon_vrshifts:
10634       VShiftOpc = ARMISD::VRSHRs; break;
10635     case Intrinsic::arm_neon_vrshiftu:
10636       VShiftOpc = ARMISD::VRSHRu; break;
10637     case Intrinsic::arm_neon_vrshiftn:
10638       VShiftOpc = ARMISD::VRSHRN; break;
10639     case Intrinsic::arm_neon_vqshifts:
10640       VShiftOpc = ARMISD::VQSHLs; break;
10641     case Intrinsic::arm_neon_vqshiftu:
10642       VShiftOpc = ARMISD::VQSHLu; break;
10643     case Intrinsic::arm_neon_vqshiftsu:
10644       VShiftOpc = ARMISD::VQSHLsu; break;
10645     case Intrinsic::arm_neon_vqshiftns:
10646       VShiftOpc = ARMISD::VQSHRNs; break;
10647     case Intrinsic::arm_neon_vqshiftnu:
10648       VShiftOpc = ARMISD::VQSHRNu; break;
10649     case Intrinsic::arm_neon_vqshiftnsu:
10650       VShiftOpc = ARMISD::VQSHRNsu; break;
10651     case Intrinsic::arm_neon_vqrshiftns:
10652       VShiftOpc = ARMISD::VQRSHRNs; break;
10653     case Intrinsic::arm_neon_vqrshiftnu:
10654       VShiftOpc = ARMISD::VQRSHRNu; break;
10655     case Intrinsic::arm_neon_vqrshiftnsu:
10656       VShiftOpc = ARMISD::VQRSHRNsu; break;
10657     }
10658 
10659     SDLoc dl(N);
10660     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10661                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10662   }
10663 
10664   case Intrinsic::arm_neon_vshiftins: {
10665     EVT VT = N->getOperand(1).getValueType();
10666     int64_t Cnt;
10667     unsigned VShiftOpc = 0;
10668 
10669     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10670       VShiftOpc = ARMISD::VSLI;
10671     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10672       VShiftOpc = ARMISD::VSRI;
10673     else {
10674       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10675     }
10676 
10677     SDLoc dl(N);
10678     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10679                        N->getOperand(1), N->getOperand(2),
10680                        DAG.getConstant(Cnt, dl, MVT::i32));
10681   }
10682 
10683   case Intrinsic::arm_neon_vqrshifts:
10684   case Intrinsic::arm_neon_vqrshiftu:
10685     // No immediate versions of these to check for.
10686     break;
10687   }
10688 
10689   return SDValue();
10690 }
10691 
10692 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10693 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10694 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10695 /// vector element shift counts are generally not legal, and it is hard to see
10696 /// their values after they get legalized to loads from a constant pool.
10697 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10698                                    const ARMSubtarget *ST) {
10699   EVT VT = N->getValueType(0);
10700   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10701     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10702     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10703     SDValue N1 = N->getOperand(1);
10704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10705       SDValue N0 = N->getOperand(0);
10706       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10707           DAG.MaskedValueIsZero(N0.getOperand(0),
10708                                 APInt::getHighBitsSet(32, 16)))
10709         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10710     }
10711   }
10712 
10713   // Nothing to be done for scalar shifts.
10714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10715   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10716     return SDValue();
10717 
10718   assert(ST->hasNEON() && "unexpected vector shift");
10719   int64_t Cnt;
10720 
10721   switch (N->getOpcode()) {
10722   default: llvm_unreachable("unexpected shift opcode");
10723 
10724   case ISD::SHL:
10725     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10726       SDLoc dl(N);
10727       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10728                          DAG.getConstant(Cnt, dl, MVT::i32));
10729     }
10730     break;
10731 
10732   case ISD::SRA:
10733   case ISD::SRL:
10734     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10735       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10736                             ARMISD::VSHRs : ARMISD::VSHRu);
10737       SDLoc dl(N);
10738       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10739                          DAG.getConstant(Cnt, dl, MVT::i32));
10740     }
10741   }
10742   return SDValue();
10743 }
10744 
10745 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10746 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10747 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10748                                     const ARMSubtarget *ST) {
10749   SDValue N0 = N->getOperand(0);
10750 
10751   // Check for sign- and zero-extensions of vector extract operations of 8-
10752   // and 16-bit vector elements.  NEON supports these directly.  They are
10753   // handled during DAG combining because type legalization will promote them
10754   // to 32-bit types and it is messy to recognize the operations after that.
10755   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10756     SDValue Vec = N0.getOperand(0);
10757     SDValue Lane = N0.getOperand(1);
10758     EVT VT = N->getValueType(0);
10759     EVT EltVT = N0.getValueType();
10760     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10761 
10762     if (VT == MVT::i32 &&
10763         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10764         TLI.isTypeLegal(Vec.getValueType()) &&
10765         isa<ConstantSDNode>(Lane)) {
10766 
10767       unsigned Opc = 0;
10768       switch (N->getOpcode()) {
10769       default: llvm_unreachable("unexpected opcode");
10770       case ISD::SIGN_EXTEND:
10771         Opc = ARMISD::VGETLANEs;
10772         break;
10773       case ISD::ZERO_EXTEND:
10774       case ISD::ANY_EXTEND:
10775         Opc = ARMISD::VGETLANEu;
10776         break;
10777       }
10778       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10779     }
10780   }
10781 
10782   return SDValue();
10783 }
10784 
10785 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10786                              APInt &KnownOne) {
10787   if (Op.getOpcode() == ARMISD::BFI) {
10788     // Conservatively, we can recurse down the first operand
10789     // and just mask out all affected bits.
10790     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10791 
10792     // The operand to BFI is already a mask suitable for removing the bits it
10793     // sets.
10794     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10795     const APInt &Mask = CI->getAPIntValue();
10796     KnownZero &= Mask;
10797     KnownOne &= Mask;
10798     return;
10799   }
10800   if (Op.getOpcode() == ARMISD::CMOV) {
10801     APInt KZ2(KnownZero.getBitWidth(), 0);
10802     APInt KO2(KnownOne.getBitWidth(), 0);
10803     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10804     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10805 
10806     KnownZero &= KZ2;
10807     KnownOne &= KO2;
10808     return;
10809   }
10810   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10811 }
10812 
10813 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10814   // If we have a CMOV, OR and AND combination such as:
10815   //   if (x & CN)
10816   //     y |= CM;
10817   //
10818   // And:
10819   //   * CN is a single bit;
10820   //   * All bits covered by CM are known zero in y
10821   //
10822   // Then we can convert this into a sequence of BFI instructions. This will
10823   // always be a win if CM is a single bit, will always be no worse than the
10824   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10825   // three bits (due to the extra IT instruction).
10826 
10827   SDValue Op0 = CMOV->getOperand(0);
10828   SDValue Op1 = CMOV->getOperand(1);
10829   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10830   auto CC = CCNode->getAPIntValue().getLimitedValue();
10831   SDValue CmpZ = CMOV->getOperand(4);
10832 
10833   // The compare must be against zero.
10834   if (!isNullConstant(CmpZ->getOperand(1)))
10835     return SDValue();
10836 
10837   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10838   SDValue And = CmpZ->getOperand(0);
10839   if (And->getOpcode() != ISD::AND)
10840     return SDValue();
10841   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10842   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10843     return SDValue();
10844   SDValue X = And->getOperand(0);
10845 
10846   if (CC == ARMCC::EQ) {
10847     // We're performing an "equal to zero" compare. Swap the operands so we
10848     // canonicalize on a "not equal to zero" compare.
10849     std::swap(Op0, Op1);
10850   } else {
10851     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10852   }
10853 
10854   if (Op1->getOpcode() != ISD::OR)
10855     return SDValue();
10856 
10857   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10858   if (!OrC)
10859     return SDValue();
10860   SDValue Y = Op1->getOperand(0);
10861 
10862   if (Op0 != Y)
10863     return SDValue();
10864 
10865   // Now, is it profitable to continue?
10866   APInt OrCI = OrC->getAPIntValue();
10867   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10868   if (OrCI.countPopulation() > Heuristic)
10869     return SDValue();
10870 
10871   // Lastly, can we determine that the bits defined by OrCI
10872   // are zero in Y?
10873   APInt KnownZero, KnownOne;
10874   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10875   if ((OrCI & KnownZero) != OrCI)
10876     return SDValue();
10877 
10878   // OK, we can do the combine.
10879   SDValue V = Y;
10880   SDLoc dl(X);
10881   EVT VT = X.getValueType();
10882   unsigned BitInX = AndC->getAPIntValue().logBase2();
10883 
10884   if (BitInX != 0) {
10885     // We must shift X first.
10886     X = DAG.getNode(ISD::SRL, dl, VT, X,
10887                     DAG.getConstant(BitInX, dl, VT));
10888   }
10889 
10890   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10891        BitInY < NumActiveBits; ++BitInY) {
10892     if (OrCI[BitInY] == 0)
10893       continue;
10894     APInt Mask(VT.getSizeInBits(), 0);
10895     Mask.setBit(BitInY);
10896     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10897                     // Confusingly, the operand is an *inverted* mask.
10898                     DAG.getConstant(~Mask, dl, VT));
10899   }
10900 
10901   return V;
10902 }
10903 
10904 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
10905 SDValue
10906 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
10907   SDValue Cmp = N->getOperand(4);
10908   if (Cmp.getOpcode() != ARMISD::CMPZ)
10909     // Only looking at NE cases.
10910     return SDValue();
10911 
10912   EVT VT = N->getValueType(0);
10913   SDLoc dl(N);
10914   SDValue LHS = Cmp.getOperand(0);
10915   SDValue RHS = Cmp.getOperand(1);
10916   SDValue Chain = N->getOperand(0);
10917   SDValue BB = N->getOperand(1);
10918   SDValue ARMcc = N->getOperand(2);
10919   ARMCC::CondCodes CC =
10920     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10921 
10922   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
10923   // -> (brcond Chain BB CC CPSR Cmp)
10924   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
10925       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
10926       LHS->getOperand(0)->hasOneUse()) {
10927     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
10928     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
10929     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
10930     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
10931     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
10932         (LHS01C && LHS01C->getZExtValue() == 1) &&
10933         (LHS1C && LHS1C->getZExtValue() == 1) &&
10934         (RHSC && RHSC->getZExtValue() == 0)) {
10935       return DAG.getNode(
10936           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
10937           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
10938     }
10939   }
10940 
10941   return SDValue();
10942 }
10943 
10944 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10945 SDValue
10946 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10947   SDValue Cmp = N->getOperand(4);
10948   if (Cmp.getOpcode() != ARMISD::CMPZ)
10949     // Only looking at EQ and NE cases.
10950     return SDValue();
10951 
10952   EVT VT = N->getValueType(0);
10953   SDLoc dl(N);
10954   SDValue LHS = Cmp.getOperand(0);
10955   SDValue RHS = Cmp.getOperand(1);
10956   SDValue FalseVal = N->getOperand(0);
10957   SDValue TrueVal = N->getOperand(1);
10958   SDValue ARMcc = N->getOperand(2);
10959   ARMCC::CondCodes CC =
10960     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10961 
10962   // BFI is only available on V6T2+.
10963   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10964     SDValue R = PerformCMOVToBFICombine(N, DAG);
10965     if (R)
10966       return R;
10967   }
10968 
10969   // Simplify
10970   //   mov     r1, r0
10971   //   cmp     r1, x
10972   //   mov     r0, y
10973   //   moveq   r0, x
10974   // to
10975   //   cmp     r0, x
10976   //   movne   r0, y
10977   //
10978   //   mov     r1, r0
10979   //   cmp     r1, x
10980   //   mov     r0, x
10981   //   movne   r0, y
10982   // to
10983   //   cmp     r0, x
10984   //   movne   r0, y
10985   /// FIXME: Turn this into a target neutral optimization?
10986   SDValue Res;
10987   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10988     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10989                       N->getOperand(3), Cmp);
10990   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10991     SDValue ARMcc;
10992     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10993     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10994                       N->getOperand(3), NewCmp);
10995   }
10996 
10997   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
10998   // -> (cmov F T CC CPSR Cmp)
10999   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11000     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11001     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11002     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11003     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11004         (LHS1C && LHS1C->getZExtValue() == 1) &&
11005         (RHSC && RHSC->getZExtValue() == 0)) {
11006       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11007                          LHS->getOperand(2), LHS->getOperand(3),
11008                          LHS->getOperand(4));
11009     }
11010   }
11011 
11012   if (Res.getNode()) {
11013     APInt KnownZero, KnownOne;
11014     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11015     // Capture demanded bits information that would be otherwise lost.
11016     if (KnownZero == 0xfffffffe)
11017       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11018                         DAG.getValueType(MVT::i1));
11019     else if (KnownZero == 0xffffff00)
11020       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11021                         DAG.getValueType(MVT::i8));
11022     else if (KnownZero == 0xffff0000)
11023       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11024                         DAG.getValueType(MVT::i16));
11025   }
11026 
11027   return Res;
11028 }
11029 
11030 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11031                                              DAGCombinerInfo &DCI) const {
11032   switch (N->getOpcode()) {
11033   default: break;
11034   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
11035   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11036   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11037   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11038   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11039   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11040   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11041   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11042   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11043   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11044   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11045   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11046   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11047   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11048   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11049   case ISD::FP_TO_SINT:
11050   case ISD::FP_TO_UINT:
11051     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11052   case ISD::FDIV:
11053     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11054   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11055   case ISD::SHL:
11056   case ISD::SRA:
11057   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11058   case ISD::SIGN_EXTEND:
11059   case ISD::ZERO_EXTEND:
11060   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11061   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11062   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11063   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11064   case ARMISD::VLD2DUP:
11065   case ARMISD::VLD3DUP:
11066   case ARMISD::VLD4DUP:
11067     return PerformVLDCombine(N, DCI);
11068   case ARMISD::BUILD_VECTOR:
11069     return PerformARMBUILD_VECTORCombine(N, DCI);
11070   case ISD::INTRINSIC_VOID:
11071   case ISD::INTRINSIC_W_CHAIN:
11072     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11073     case Intrinsic::arm_neon_vld1:
11074     case Intrinsic::arm_neon_vld2:
11075     case Intrinsic::arm_neon_vld3:
11076     case Intrinsic::arm_neon_vld4:
11077     case Intrinsic::arm_neon_vld2lane:
11078     case Intrinsic::arm_neon_vld3lane:
11079     case Intrinsic::arm_neon_vld4lane:
11080     case Intrinsic::arm_neon_vst1:
11081     case Intrinsic::arm_neon_vst2:
11082     case Intrinsic::arm_neon_vst3:
11083     case Intrinsic::arm_neon_vst4:
11084     case Intrinsic::arm_neon_vst2lane:
11085     case Intrinsic::arm_neon_vst3lane:
11086     case Intrinsic::arm_neon_vst4lane:
11087       return PerformVLDCombine(N, DCI);
11088     default: break;
11089     }
11090     break;
11091   }
11092   return SDValue();
11093 }
11094 
11095 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11096                                                           EVT VT) const {
11097   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11098 }
11099 
11100 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11101                                                        unsigned,
11102                                                        unsigned,
11103                                                        bool *Fast) const {
11104   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11105   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11106 
11107   switch (VT.getSimpleVT().SimpleTy) {
11108   default:
11109     return false;
11110   case MVT::i8:
11111   case MVT::i16:
11112   case MVT::i32: {
11113     // Unaligned access can use (for example) LRDB, LRDH, LDR
11114     if (AllowsUnaligned) {
11115       if (Fast)
11116         *Fast = Subtarget->hasV7Ops();
11117       return true;
11118     }
11119     return false;
11120   }
11121   case MVT::f64:
11122   case MVT::v2f64: {
11123     // For any little-endian targets with neon, we can support unaligned ld/st
11124     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
11125     // A big-endian target may also explicitly support unaligned accesses
11126     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
11127       if (Fast)
11128         *Fast = true;
11129       return true;
11130     }
11131     return false;
11132   }
11133   }
11134 }
11135 
11136 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
11137                        unsigned AlignCheck) {
11138   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
11139           (DstAlign == 0 || DstAlign % AlignCheck == 0));
11140 }
11141 
11142 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
11143                                            unsigned DstAlign, unsigned SrcAlign,
11144                                            bool IsMemset, bool ZeroMemset,
11145                                            bool MemcpyStrSrc,
11146                                            MachineFunction &MF) const {
11147   const Function *F = MF.getFunction();
11148 
11149   // See if we can use NEON instructions for this...
11150   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
11151       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11152     bool Fast;
11153     if (Size >= 16 &&
11154         (memOpAlign(SrcAlign, DstAlign, 16) ||
11155          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
11156       return MVT::v2f64;
11157     } else if (Size >= 8 &&
11158                (memOpAlign(SrcAlign, DstAlign, 8) ||
11159                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
11160                  Fast))) {
11161       return MVT::f64;
11162     }
11163   }
11164 
11165   // Lowering to i32/i16 if the size permits.
11166   if (Size >= 4)
11167     return MVT::i32;
11168   else if (Size >= 2)
11169     return MVT::i16;
11170 
11171   // Let the target-independent logic figure it out.
11172   return MVT::Other;
11173 }
11174 
11175 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11176   if (Val.getOpcode() != ISD::LOAD)
11177     return false;
11178 
11179   EVT VT1 = Val.getValueType();
11180   if (!VT1.isSimple() || !VT1.isInteger() ||
11181       !VT2.isSimple() || !VT2.isInteger())
11182     return false;
11183 
11184   switch (VT1.getSimpleVT().SimpleTy) {
11185   default: break;
11186   case MVT::i1:
11187   case MVT::i8:
11188   case MVT::i16:
11189     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
11190     return true;
11191   }
11192 
11193   return false;
11194 }
11195 
11196 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
11197   EVT VT = ExtVal.getValueType();
11198 
11199   if (!isTypeLegal(VT))
11200     return false;
11201 
11202   // Don't create a loadext if we can fold the extension into a wide/long
11203   // instruction.
11204   // If there's more than one user instruction, the loadext is desirable no
11205   // matter what.  There can be two uses by the same instruction.
11206   if (ExtVal->use_empty() ||
11207       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
11208     return true;
11209 
11210   SDNode *U = *ExtVal->use_begin();
11211   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
11212        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
11213     return false;
11214 
11215   return true;
11216 }
11217 
11218 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
11219   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11220     return false;
11221 
11222   if (!isTypeLegal(EVT::getEVT(Ty1)))
11223     return false;
11224 
11225   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
11226 
11227   // Assuming the caller doesn't have a zeroext or signext return parameter,
11228   // truncation all the way down to i1 is valid.
11229   return true;
11230 }
11231 
11232 
11233 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
11234   if (V < 0)
11235     return false;
11236 
11237   unsigned Scale = 1;
11238   switch (VT.getSimpleVT().SimpleTy) {
11239   default: return false;
11240   case MVT::i1:
11241   case MVT::i8:
11242     // Scale == 1;
11243     break;
11244   case MVT::i16:
11245     // Scale == 2;
11246     Scale = 2;
11247     break;
11248   case MVT::i32:
11249     // Scale == 4;
11250     Scale = 4;
11251     break;
11252   }
11253 
11254   if ((V & (Scale - 1)) != 0)
11255     return false;
11256   V /= Scale;
11257   return V == (V & ((1LL << 5) - 1));
11258 }
11259 
11260 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
11261                                       const ARMSubtarget *Subtarget) {
11262   bool isNeg = false;
11263   if (V < 0) {
11264     isNeg = true;
11265     V = - V;
11266   }
11267 
11268   switch (VT.getSimpleVT().SimpleTy) {
11269   default: return false;
11270   case MVT::i1:
11271   case MVT::i8:
11272   case MVT::i16:
11273   case MVT::i32:
11274     // + imm12 or - imm8
11275     if (isNeg)
11276       return V == (V & ((1LL << 8) - 1));
11277     return V == (V & ((1LL << 12) - 1));
11278   case MVT::f32:
11279   case MVT::f64:
11280     // Same as ARM mode. FIXME: NEON?
11281     if (!Subtarget->hasVFP2())
11282       return false;
11283     if ((V & 3) != 0)
11284       return false;
11285     V >>= 2;
11286     return V == (V & ((1LL << 8) - 1));
11287   }
11288 }
11289 
11290 /// isLegalAddressImmediate - Return true if the integer value can be used
11291 /// as the offset of the target addressing mode for load / store of the
11292 /// given type.
11293 static bool isLegalAddressImmediate(int64_t V, EVT VT,
11294                                     const ARMSubtarget *Subtarget) {
11295   if (V == 0)
11296     return true;
11297 
11298   if (!VT.isSimple())
11299     return false;
11300 
11301   if (Subtarget->isThumb1Only())
11302     return isLegalT1AddressImmediate(V, VT);
11303   else if (Subtarget->isThumb2())
11304     return isLegalT2AddressImmediate(V, VT, Subtarget);
11305 
11306   // ARM mode.
11307   if (V < 0)
11308     V = - V;
11309   switch (VT.getSimpleVT().SimpleTy) {
11310   default: return false;
11311   case MVT::i1:
11312   case MVT::i8:
11313   case MVT::i32:
11314     // +- imm12
11315     return V == (V & ((1LL << 12) - 1));
11316   case MVT::i16:
11317     // +- imm8
11318     return V == (V & ((1LL << 8) - 1));
11319   case MVT::f32:
11320   case MVT::f64:
11321     if (!Subtarget->hasVFP2()) // FIXME: NEON?
11322       return false;
11323     if ((V & 3) != 0)
11324       return false;
11325     V >>= 2;
11326     return V == (V & ((1LL << 8) - 1));
11327   }
11328 }
11329 
11330 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
11331                                                       EVT VT) const {
11332   int Scale = AM.Scale;
11333   if (Scale < 0)
11334     return false;
11335 
11336   switch (VT.getSimpleVT().SimpleTy) {
11337   default: return false;
11338   case MVT::i1:
11339   case MVT::i8:
11340   case MVT::i16:
11341   case MVT::i32:
11342     if (Scale == 1)
11343       return true;
11344     // r + r << imm
11345     Scale = Scale & ~1;
11346     return Scale == 2 || Scale == 4 || Scale == 8;
11347   case MVT::i64:
11348     // r + r
11349     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11350       return true;
11351     return false;
11352   case MVT::isVoid:
11353     // Note, we allow "void" uses (basically, uses that aren't loads or
11354     // stores), because arm allows folding a scale into many arithmetic
11355     // operations.  This should be made more precise and revisited later.
11356 
11357     // Allow r << imm, but the imm has to be a multiple of two.
11358     if (Scale & 1) return false;
11359     return isPowerOf2_32(Scale);
11360   }
11361 }
11362 
11363 /// isLegalAddressingMode - Return true if the addressing mode represented
11364 /// by AM is legal for this target, for a load/store of the specified type.
11365 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11366                                               const AddrMode &AM, Type *Ty,
11367                                               unsigned AS) const {
11368   EVT VT = getValueType(DL, Ty, true);
11369   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11370     return false;
11371 
11372   // Can never fold addr of global into load/store.
11373   if (AM.BaseGV)
11374     return false;
11375 
11376   switch (AM.Scale) {
11377   case 0:  // no scale reg, must be "r+i" or "r", or "i".
11378     break;
11379   case 1:
11380     if (Subtarget->isThumb1Only())
11381       return false;
11382     // FALL THROUGH.
11383   default:
11384     // ARM doesn't support any R+R*scale+imm addr modes.
11385     if (AM.BaseOffs)
11386       return false;
11387 
11388     if (!VT.isSimple())
11389       return false;
11390 
11391     if (Subtarget->isThumb2())
11392       return isLegalT2ScaledAddressingMode(AM, VT);
11393 
11394     int Scale = AM.Scale;
11395     switch (VT.getSimpleVT().SimpleTy) {
11396     default: return false;
11397     case MVT::i1:
11398     case MVT::i8:
11399     case MVT::i32:
11400       if (Scale < 0) Scale = -Scale;
11401       if (Scale == 1)
11402         return true;
11403       // r + r << imm
11404       return isPowerOf2_32(Scale & ~1);
11405     case MVT::i16:
11406     case MVT::i64:
11407       // r + r
11408       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11409         return true;
11410       return false;
11411 
11412     case MVT::isVoid:
11413       // Note, we allow "void" uses (basically, uses that aren't loads or
11414       // stores), because arm allows folding a scale into many arithmetic
11415       // operations.  This should be made more precise and revisited later.
11416 
11417       // Allow r << imm, but the imm has to be a multiple of two.
11418       if (Scale & 1) return false;
11419       return isPowerOf2_32(Scale);
11420     }
11421   }
11422   return true;
11423 }
11424 
11425 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11426 /// icmp immediate, that is the target has icmp instructions which can compare
11427 /// a register against the immediate without having to materialize the
11428 /// immediate into a register.
11429 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11430   // Thumb2 and ARM modes can use cmn for negative immediates.
11431   if (!Subtarget->isThumb())
11432     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11433   if (Subtarget->isThumb2())
11434     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11435   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11436   return Imm >= 0 && Imm <= 255;
11437 }
11438 
11439 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11440 /// *or sub* immediate, that is the target has add or sub instructions which can
11441 /// add a register with the immediate without having to materialize the
11442 /// immediate into a register.
11443 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11444   // Same encoding for add/sub, just flip the sign.
11445   int64_t AbsImm = std::abs(Imm);
11446   if (!Subtarget->isThumb())
11447     return ARM_AM::getSOImmVal(AbsImm) != -1;
11448   if (Subtarget->isThumb2())
11449     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11450   // Thumb1 only has 8-bit unsigned immediate.
11451   return AbsImm >= 0 && AbsImm <= 255;
11452 }
11453 
11454 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11455                                       bool isSEXTLoad, SDValue &Base,
11456                                       SDValue &Offset, bool &isInc,
11457                                       SelectionDAG &DAG) {
11458   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11459     return false;
11460 
11461   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11462     // AddressingMode 3
11463     Base = Ptr->getOperand(0);
11464     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11465       int RHSC = (int)RHS->getZExtValue();
11466       if (RHSC < 0 && RHSC > -256) {
11467         assert(Ptr->getOpcode() == ISD::ADD);
11468         isInc = false;
11469         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11470         return true;
11471       }
11472     }
11473     isInc = (Ptr->getOpcode() == ISD::ADD);
11474     Offset = Ptr->getOperand(1);
11475     return true;
11476   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11477     // AddressingMode 2
11478     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11479       int RHSC = (int)RHS->getZExtValue();
11480       if (RHSC < 0 && RHSC > -0x1000) {
11481         assert(Ptr->getOpcode() == ISD::ADD);
11482         isInc = false;
11483         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11484         Base = Ptr->getOperand(0);
11485         return true;
11486       }
11487     }
11488 
11489     if (Ptr->getOpcode() == ISD::ADD) {
11490       isInc = true;
11491       ARM_AM::ShiftOpc ShOpcVal=
11492         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11493       if (ShOpcVal != ARM_AM::no_shift) {
11494         Base = Ptr->getOperand(1);
11495         Offset = Ptr->getOperand(0);
11496       } else {
11497         Base = Ptr->getOperand(0);
11498         Offset = Ptr->getOperand(1);
11499       }
11500       return true;
11501     }
11502 
11503     isInc = (Ptr->getOpcode() == ISD::ADD);
11504     Base = Ptr->getOperand(0);
11505     Offset = Ptr->getOperand(1);
11506     return true;
11507   }
11508 
11509   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11510   return false;
11511 }
11512 
11513 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11514                                      bool isSEXTLoad, SDValue &Base,
11515                                      SDValue &Offset, bool &isInc,
11516                                      SelectionDAG &DAG) {
11517   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11518     return false;
11519 
11520   Base = Ptr->getOperand(0);
11521   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11522     int RHSC = (int)RHS->getZExtValue();
11523     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11524       assert(Ptr->getOpcode() == ISD::ADD);
11525       isInc = false;
11526       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11527       return true;
11528     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11529       isInc = Ptr->getOpcode() == ISD::ADD;
11530       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11531       return true;
11532     }
11533   }
11534 
11535   return false;
11536 }
11537 
11538 /// getPreIndexedAddressParts - returns true by value, base pointer and
11539 /// offset pointer and addressing mode by reference if the node's address
11540 /// can be legally represented as pre-indexed load / store address.
11541 bool
11542 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11543                                              SDValue &Offset,
11544                                              ISD::MemIndexedMode &AM,
11545                                              SelectionDAG &DAG) const {
11546   if (Subtarget->isThumb1Only())
11547     return false;
11548 
11549   EVT VT;
11550   SDValue Ptr;
11551   bool isSEXTLoad = false;
11552   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11553     Ptr = LD->getBasePtr();
11554     VT  = LD->getMemoryVT();
11555     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11556   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11557     Ptr = ST->getBasePtr();
11558     VT  = ST->getMemoryVT();
11559   } else
11560     return false;
11561 
11562   bool isInc;
11563   bool isLegal = false;
11564   if (Subtarget->isThumb2())
11565     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11566                                        Offset, isInc, DAG);
11567   else
11568     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11569                                         Offset, isInc, DAG);
11570   if (!isLegal)
11571     return false;
11572 
11573   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11574   return true;
11575 }
11576 
11577 /// getPostIndexedAddressParts - returns true by value, base pointer and
11578 /// offset pointer and addressing mode by reference if this node can be
11579 /// combined with a load / store to form a post-indexed load / store.
11580 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11581                                                    SDValue &Base,
11582                                                    SDValue &Offset,
11583                                                    ISD::MemIndexedMode &AM,
11584                                                    SelectionDAG &DAG) const {
11585   EVT VT;
11586   SDValue Ptr;
11587   bool isSEXTLoad = false, isNonExt;
11588   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11589     VT  = LD->getMemoryVT();
11590     Ptr = LD->getBasePtr();
11591     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11592     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
11593   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11594     VT  = ST->getMemoryVT();
11595     Ptr = ST->getBasePtr();
11596     isNonExt = !ST->isTruncatingStore();
11597   } else
11598     return false;
11599 
11600   if (Subtarget->isThumb1Only()) {
11601     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
11602     // must be non-extending/truncating, i32, with an offset of 4.
11603     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
11604     if (Op->getOpcode() != ISD::ADD || !isNonExt)
11605       return false;
11606     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11607     if (!RHS || RHS->getZExtValue() != 4)
11608       return false;
11609 
11610     Offset = Op->getOperand(1);
11611     Base = Op->getOperand(0);
11612     AM = ISD::POST_INC;
11613     return true;
11614   }
11615 
11616   bool isInc;
11617   bool isLegal = false;
11618   if (Subtarget->isThumb2())
11619     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11620                                        isInc, DAG);
11621   else
11622     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11623                                         isInc, DAG);
11624   if (!isLegal)
11625     return false;
11626 
11627   if (Ptr != Base) {
11628     // Swap base ptr and offset to catch more post-index load / store when
11629     // it's legal. In Thumb2 mode, offset must be an immediate.
11630     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11631         !Subtarget->isThumb2())
11632       std::swap(Base, Offset);
11633 
11634     // Post-indexed load / store update the base pointer.
11635     if (Ptr != Base)
11636       return false;
11637   }
11638 
11639   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11640   return true;
11641 }
11642 
11643 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11644                                                       APInt &KnownZero,
11645                                                       APInt &KnownOne,
11646                                                       const SelectionDAG &DAG,
11647                                                       unsigned Depth) const {
11648   unsigned BitWidth = KnownOne.getBitWidth();
11649   KnownZero = KnownOne = APInt(BitWidth, 0);
11650   switch (Op.getOpcode()) {
11651   default: break;
11652   case ARMISD::ADDC:
11653   case ARMISD::ADDE:
11654   case ARMISD::SUBC:
11655   case ARMISD::SUBE:
11656     // These nodes' second result is a boolean
11657     if (Op.getResNo() == 0)
11658       break;
11659     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11660     break;
11661   case ARMISD::CMOV: {
11662     // Bits are known zero/one if known on the LHS and RHS.
11663     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11664     if (KnownZero == 0 && KnownOne == 0) return;
11665 
11666     APInt KnownZeroRHS, KnownOneRHS;
11667     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11668     KnownZero &= KnownZeroRHS;
11669     KnownOne  &= KnownOneRHS;
11670     return;
11671   }
11672   case ISD::INTRINSIC_W_CHAIN: {
11673     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11674     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11675     switch (IntID) {
11676     default: return;
11677     case Intrinsic::arm_ldaex:
11678     case Intrinsic::arm_ldrex: {
11679       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11680       unsigned MemBits = VT.getScalarType().getSizeInBits();
11681       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11682       return;
11683     }
11684     }
11685   }
11686   }
11687 }
11688 
11689 //===----------------------------------------------------------------------===//
11690 //                           ARM Inline Assembly Support
11691 //===----------------------------------------------------------------------===//
11692 
11693 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11694   // Looking for "rev" which is V6+.
11695   if (!Subtarget->hasV6Ops())
11696     return false;
11697 
11698   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11699   std::string AsmStr = IA->getAsmString();
11700   SmallVector<StringRef, 4> AsmPieces;
11701   SplitString(AsmStr, AsmPieces, ";\n");
11702 
11703   switch (AsmPieces.size()) {
11704   default: return false;
11705   case 1:
11706     AsmStr = AsmPieces[0];
11707     AsmPieces.clear();
11708     SplitString(AsmStr, AsmPieces, " \t,");
11709 
11710     // rev $0, $1
11711     if (AsmPieces.size() == 3 &&
11712         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11713         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11714       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11715       if (Ty && Ty->getBitWidth() == 32)
11716         return IntrinsicLowering::LowerToByteSwap(CI);
11717     }
11718     break;
11719   }
11720 
11721   return false;
11722 }
11723 
11724 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
11725   // At this point, we have to lower this constraint to something else, so we
11726   // lower it to an "r" or "w". However, by doing this we will force the result
11727   // to be in register, while the X constraint is much more permissive.
11728   //
11729   // Although we are correct (we are free to emit anything, without
11730   // constraints), we might break use cases that would expect us to be more
11731   // efficient and emit something else.
11732   if (!Subtarget->hasVFP2())
11733     return "r";
11734   if (ConstraintVT.isFloatingPoint())
11735     return "w";
11736   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
11737      (ConstraintVT.getSizeInBits() == 64 ||
11738       ConstraintVT.getSizeInBits() == 128))
11739     return "w";
11740 
11741   return "r";
11742 }
11743 
11744 /// getConstraintType - Given a constraint letter, return the type of
11745 /// constraint it is for this target.
11746 ARMTargetLowering::ConstraintType
11747 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11748   if (Constraint.size() == 1) {
11749     switch (Constraint[0]) {
11750     default:  break;
11751     case 'l': return C_RegisterClass;
11752     case 'w': return C_RegisterClass;
11753     case 'h': return C_RegisterClass;
11754     case 'x': return C_RegisterClass;
11755     case 't': return C_RegisterClass;
11756     case 'j': return C_Other; // Constant for movw.
11757       // An address with a single base register. Due to the way we
11758       // currently handle addresses it is the same as an 'r' memory constraint.
11759     case 'Q': return C_Memory;
11760     }
11761   } else if (Constraint.size() == 2) {
11762     switch (Constraint[0]) {
11763     default: break;
11764     // All 'U+' constraints are addresses.
11765     case 'U': return C_Memory;
11766     }
11767   }
11768   return TargetLowering::getConstraintType(Constraint);
11769 }
11770 
11771 /// Examine constraint type and operand type and determine a weight value.
11772 /// This object must already have been set up with the operand type
11773 /// and the current alternative constraint selected.
11774 TargetLowering::ConstraintWeight
11775 ARMTargetLowering::getSingleConstraintMatchWeight(
11776     AsmOperandInfo &info, const char *constraint) const {
11777   ConstraintWeight weight = CW_Invalid;
11778   Value *CallOperandVal = info.CallOperandVal;
11779     // If we don't have a value, we can't do a match,
11780     // but allow it at the lowest weight.
11781   if (!CallOperandVal)
11782     return CW_Default;
11783   Type *type = CallOperandVal->getType();
11784   // Look at the constraint type.
11785   switch (*constraint) {
11786   default:
11787     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11788     break;
11789   case 'l':
11790     if (type->isIntegerTy()) {
11791       if (Subtarget->isThumb())
11792         weight = CW_SpecificReg;
11793       else
11794         weight = CW_Register;
11795     }
11796     break;
11797   case 'w':
11798     if (type->isFloatingPointTy())
11799       weight = CW_Register;
11800     break;
11801   }
11802   return weight;
11803 }
11804 
11805 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11806 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11807     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11808   if (Constraint.size() == 1) {
11809     // GCC ARM Constraint Letters
11810     switch (Constraint[0]) {
11811     case 'l': // Low regs or general regs.
11812       if (Subtarget->isThumb())
11813         return RCPair(0U, &ARM::tGPRRegClass);
11814       return RCPair(0U, &ARM::GPRRegClass);
11815     case 'h': // High regs or no regs.
11816       if (Subtarget->isThumb())
11817         return RCPair(0U, &ARM::hGPRRegClass);
11818       break;
11819     case 'r':
11820       if (Subtarget->isThumb1Only())
11821         return RCPair(0U, &ARM::tGPRRegClass);
11822       return RCPair(0U, &ARM::GPRRegClass);
11823     case 'w':
11824       if (VT == MVT::Other)
11825         break;
11826       if (VT == MVT::f32)
11827         return RCPair(0U, &ARM::SPRRegClass);
11828       if (VT.getSizeInBits() == 64)
11829         return RCPair(0U, &ARM::DPRRegClass);
11830       if (VT.getSizeInBits() == 128)
11831         return RCPair(0U, &ARM::QPRRegClass);
11832       break;
11833     case 'x':
11834       if (VT == MVT::Other)
11835         break;
11836       if (VT == MVT::f32)
11837         return RCPair(0U, &ARM::SPR_8RegClass);
11838       if (VT.getSizeInBits() == 64)
11839         return RCPair(0U, &ARM::DPR_8RegClass);
11840       if (VT.getSizeInBits() == 128)
11841         return RCPair(0U, &ARM::QPR_8RegClass);
11842       break;
11843     case 't':
11844       if (VT == MVT::f32)
11845         return RCPair(0U, &ARM::SPRRegClass);
11846       break;
11847     }
11848   }
11849   if (StringRef("{cc}").equals_lower(Constraint))
11850     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11851 
11852   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11853 }
11854 
11855 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11856 /// vector.  If it is invalid, don't add anything to Ops.
11857 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11858                                                      std::string &Constraint,
11859                                                      std::vector<SDValue>&Ops,
11860                                                      SelectionDAG &DAG) const {
11861   SDValue Result;
11862 
11863   // Currently only support length 1 constraints.
11864   if (Constraint.length() != 1) return;
11865 
11866   char ConstraintLetter = Constraint[0];
11867   switch (ConstraintLetter) {
11868   default: break;
11869   case 'j':
11870   case 'I': case 'J': case 'K': case 'L':
11871   case 'M': case 'N': case 'O':
11872     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11873     if (!C)
11874       return;
11875 
11876     int64_t CVal64 = C->getSExtValue();
11877     int CVal = (int) CVal64;
11878     // None of these constraints allow values larger than 32 bits.  Check
11879     // that the value fits in an int.
11880     if (CVal != CVal64)
11881       return;
11882 
11883     switch (ConstraintLetter) {
11884       case 'j':
11885         // Constant suitable for movw, must be between 0 and
11886         // 65535.
11887         if (Subtarget->hasV6T2Ops())
11888           if (CVal >= 0 && CVal <= 65535)
11889             break;
11890         return;
11891       case 'I':
11892         if (Subtarget->isThumb1Only()) {
11893           // This must be a constant between 0 and 255, for ADD
11894           // immediates.
11895           if (CVal >= 0 && CVal <= 255)
11896             break;
11897         } else if (Subtarget->isThumb2()) {
11898           // A constant that can be used as an immediate value in a
11899           // data-processing instruction.
11900           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11901             break;
11902         } else {
11903           // A constant that can be used as an immediate value in a
11904           // data-processing instruction.
11905           if (ARM_AM::getSOImmVal(CVal) != -1)
11906             break;
11907         }
11908         return;
11909 
11910       case 'J':
11911         if (Subtarget->isThumb1Only()) {
11912           // This must be a constant between -255 and -1, for negated ADD
11913           // immediates. This can be used in GCC with an "n" modifier that
11914           // prints the negated value, for use with SUB instructions. It is
11915           // not useful otherwise but is implemented for compatibility.
11916           if (CVal >= -255 && CVal <= -1)
11917             break;
11918         } else {
11919           // This must be a constant between -4095 and 4095. It is not clear
11920           // what this constraint is intended for. Implemented for
11921           // compatibility with GCC.
11922           if (CVal >= -4095 && CVal <= 4095)
11923             break;
11924         }
11925         return;
11926 
11927       case 'K':
11928         if (Subtarget->isThumb1Only()) {
11929           // A 32-bit value where only one byte has a nonzero value. Exclude
11930           // zero to match GCC. This constraint is used by GCC internally for
11931           // constants that can be loaded with a move/shift combination.
11932           // It is not useful otherwise but is implemented for compatibility.
11933           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11934             break;
11935         } else if (Subtarget->isThumb2()) {
11936           // A constant whose bitwise inverse can be used as an immediate
11937           // value in a data-processing instruction. This can be used in GCC
11938           // with a "B" modifier that prints the inverted value, for use with
11939           // BIC and MVN instructions. It is not useful otherwise but is
11940           // implemented for compatibility.
11941           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11942             break;
11943         } else {
11944           // A constant whose bitwise inverse can be used as an immediate
11945           // value in a data-processing instruction. This can be used in GCC
11946           // with a "B" modifier that prints the inverted value, for use with
11947           // BIC and MVN instructions. It is not useful otherwise but is
11948           // implemented for compatibility.
11949           if (ARM_AM::getSOImmVal(~CVal) != -1)
11950             break;
11951         }
11952         return;
11953 
11954       case 'L':
11955         if (Subtarget->isThumb1Only()) {
11956           // This must be a constant between -7 and 7,
11957           // for 3-operand ADD/SUB immediate instructions.
11958           if (CVal >= -7 && CVal < 7)
11959             break;
11960         } else if (Subtarget->isThumb2()) {
11961           // A constant whose negation can be used as an immediate value in a
11962           // data-processing instruction. This can be used in GCC with an "n"
11963           // modifier that prints the negated value, for use with SUB
11964           // instructions. It is not useful otherwise but is implemented for
11965           // compatibility.
11966           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11967             break;
11968         } else {
11969           // A constant whose negation can be used as an immediate value in a
11970           // data-processing instruction. This can be used in GCC with an "n"
11971           // modifier that prints the negated value, for use with SUB
11972           // instructions. It is not useful otherwise but is implemented for
11973           // compatibility.
11974           if (ARM_AM::getSOImmVal(-CVal) != -1)
11975             break;
11976         }
11977         return;
11978 
11979       case 'M':
11980         if (Subtarget->isThumb1Only()) {
11981           // This must be a multiple of 4 between 0 and 1020, for
11982           // ADD sp + immediate.
11983           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11984             break;
11985         } else {
11986           // A power of two or a constant between 0 and 32.  This is used in
11987           // GCC for the shift amount on shifted register operands, but it is
11988           // useful in general for any shift amounts.
11989           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11990             break;
11991         }
11992         return;
11993 
11994       case 'N':
11995         if (Subtarget->isThumb()) {  // FIXME thumb2
11996           // This must be a constant between 0 and 31, for shift amounts.
11997           if (CVal >= 0 && CVal <= 31)
11998             break;
11999         }
12000         return;
12001 
12002       case 'O':
12003         if (Subtarget->isThumb()) {  // FIXME thumb2
12004           // This must be a multiple of 4 between -508 and 508, for
12005           // ADD/SUB sp = sp + immediate.
12006           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12007             break;
12008         }
12009         return;
12010     }
12011     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12012     break;
12013   }
12014 
12015   if (Result.getNode()) {
12016     Ops.push_back(Result);
12017     return;
12018   }
12019   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12020 }
12021 
12022 static RTLIB::Libcall getDivRemLibcall(
12023     const SDNode *N, MVT::SimpleValueType SVT) {
12024   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12025           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12026          "Unhandled Opcode in getDivRemLibcall");
12027   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12028                   N->getOpcode() == ISD::SREM;
12029   RTLIB::Libcall LC;
12030   switch (SVT) {
12031   default: llvm_unreachable("Unexpected request for libcall!");
12032   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
12033   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12034   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12035   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12036   }
12037   return LC;
12038 }
12039 
12040 static TargetLowering::ArgListTy getDivRemArgList(
12041     const SDNode *N, LLVMContext *Context) {
12042   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12043           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12044          "Unhandled Opcode in getDivRemArgList");
12045   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12046                   N->getOpcode() == ISD::SREM;
12047   TargetLowering::ArgListTy Args;
12048   TargetLowering::ArgListEntry Entry;
12049   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12050     EVT ArgVT = N->getOperand(i).getValueType();
12051     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12052     Entry.Node = N->getOperand(i);
12053     Entry.Ty = ArgTy;
12054     Entry.isSExt = isSigned;
12055     Entry.isZExt = !isSigned;
12056     Args.push_back(Entry);
12057   }
12058   return Args;
12059 }
12060 
12061 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12062   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12063           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) &&
12064          "Register-based DivRem lowering only");
12065   unsigned Opcode = Op->getOpcode();
12066   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12067          "Invalid opcode for Div/Rem lowering");
12068   bool isSigned = (Opcode == ISD::SDIVREM);
12069   EVT VT = Op->getValueType(0);
12070   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12071 
12072   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12073                                        VT.getSimpleVT().SimpleTy);
12074   SDValue InChain = DAG.getEntryNode();
12075 
12076   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12077                                                     DAG.getContext());
12078 
12079   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12080                                          getPointerTy(DAG.getDataLayout()));
12081 
12082   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12083 
12084   SDLoc dl(Op);
12085   TargetLowering::CallLoweringInfo CLI(DAG);
12086   CLI.setDebugLoc(dl).setChain(InChain)
12087     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
12088     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
12089 
12090   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
12091   return CallInfo.first;
12092 }
12093 
12094 // Lowers REM using divmod helpers
12095 // see RTABI section 4.2/4.3
12096 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
12097   // Build return types (div and rem)
12098   std::vector<Type*> RetTyParams;
12099   Type *RetTyElement;
12100 
12101   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
12102   default: llvm_unreachable("Unexpected request for libcall!");
12103   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
12104   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
12105   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
12106   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
12107   }
12108 
12109   RetTyParams.push_back(RetTyElement);
12110   RetTyParams.push_back(RetTyElement);
12111   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
12112   Type *RetTy = StructType::get(*DAG.getContext(), ret);
12113 
12114   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
12115                                                              SimpleTy);
12116   SDValue InChain = DAG.getEntryNode();
12117   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
12118   bool isSigned = N->getOpcode() == ISD::SREM;
12119   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12120                                          getPointerTy(DAG.getDataLayout()));
12121 
12122   // Lower call
12123   CallLoweringInfo CLI(DAG);
12124   CLI.setChain(InChain)
12125      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
12126      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
12127   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12128 
12129   // Return second (rem) result operand (first contains div)
12130   SDNode *ResNode = CallResult.first.getNode();
12131   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
12132   return ResNode->getOperand(1);
12133 }
12134 
12135 SDValue
12136 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
12137   assert(Subtarget->isTargetWindows() && "unsupported target platform");
12138   SDLoc DL(Op);
12139 
12140   // Get the inputs.
12141   SDValue Chain = Op.getOperand(0);
12142   SDValue Size  = Op.getOperand(1);
12143 
12144   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
12145                               DAG.getConstant(2, DL, MVT::i32));
12146 
12147   SDValue Flag;
12148   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
12149   Flag = Chain.getValue(1);
12150 
12151   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12152   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
12153 
12154   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
12155   Chain = NewSP.getValue(1);
12156 
12157   SDValue Ops[2] = { NewSP, Chain };
12158   return DAG.getMergeValues(Ops, DL);
12159 }
12160 
12161 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12162   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
12163          "Unexpected type for custom-lowering FP_EXTEND");
12164 
12165   RTLIB::Libcall LC;
12166   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
12167 
12168   SDValue SrcVal = Op.getOperand(0);
12169   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12170                      SDLoc(Op)).first;
12171 }
12172 
12173 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12174   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
12175          Subtarget->isFPOnlySP() &&
12176          "Unexpected type for custom-lowering FP_ROUND");
12177 
12178   RTLIB::Libcall LC;
12179   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
12180 
12181   SDValue SrcVal = Op.getOperand(0);
12182   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12183                      SDLoc(Op)).first;
12184 }
12185 
12186 bool
12187 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12188   // The ARM target isn't yet aware of offsets.
12189   return false;
12190 }
12191 
12192 bool ARM::isBitFieldInvertedMask(unsigned v) {
12193   if (v == 0xffffffff)
12194     return false;
12195 
12196   // there can be 1's on either or both "outsides", all the "inside"
12197   // bits must be 0's
12198   return isShiftedMask_32(~v);
12199 }
12200 
12201 /// isFPImmLegal - Returns true if the target can instruction select the
12202 /// specified FP immediate natively. If false, the legalizer will
12203 /// materialize the FP immediate as a load from a constant pool.
12204 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12205   if (!Subtarget->hasVFP3())
12206     return false;
12207   if (VT == MVT::f32)
12208     return ARM_AM::getFP32Imm(Imm) != -1;
12209   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
12210     return ARM_AM::getFP64Imm(Imm) != -1;
12211   return false;
12212 }
12213 
12214 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
12215 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
12216 /// specified in the intrinsic calls.
12217 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12218                                            const CallInst &I,
12219                                            unsigned Intrinsic) const {
12220   switch (Intrinsic) {
12221   case Intrinsic::arm_neon_vld1:
12222   case Intrinsic::arm_neon_vld2:
12223   case Intrinsic::arm_neon_vld3:
12224   case Intrinsic::arm_neon_vld4:
12225   case Intrinsic::arm_neon_vld2lane:
12226   case Intrinsic::arm_neon_vld3lane:
12227   case Intrinsic::arm_neon_vld4lane: {
12228     Info.opc = ISD::INTRINSIC_W_CHAIN;
12229     // Conservatively set memVT to the entire set of vectors loaded.
12230     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12231     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
12232     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12233     Info.ptrVal = I.getArgOperand(0);
12234     Info.offset = 0;
12235     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12236     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12237     Info.vol = false; // volatile loads with NEON intrinsics not supported
12238     Info.readMem = true;
12239     Info.writeMem = false;
12240     return true;
12241   }
12242   case Intrinsic::arm_neon_vst1:
12243   case Intrinsic::arm_neon_vst2:
12244   case Intrinsic::arm_neon_vst3:
12245   case Intrinsic::arm_neon_vst4:
12246   case Intrinsic::arm_neon_vst2lane:
12247   case Intrinsic::arm_neon_vst3lane:
12248   case Intrinsic::arm_neon_vst4lane: {
12249     Info.opc = ISD::INTRINSIC_VOID;
12250     // Conservatively set memVT to the entire set of vectors stored.
12251     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12252     unsigned NumElts = 0;
12253     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
12254       Type *ArgTy = I.getArgOperand(ArgI)->getType();
12255       if (!ArgTy->isVectorTy())
12256         break;
12257       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
12258     }
12259     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12260     Info.ptrVal = I.getArgOperand(0);
12261     Info.offset = 0;
12262     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12263     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12264     Info.vol = false; // volatile stores with NEON intrinsics not supported
12265     Info.readMem = false;
12266     Info.writeMem = true;
12267     return true;
12268   }
12269   case Intrinsic::arm_ldaex:
12270   case Intrinsic::arm_ldrex: {
12271     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12272     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
12273     Info.opc = ISD::INTRINSIC_W_CHAIN;
12274     Info.memVT = MVT::getVT(PtrTy->getElementType());
12275     Info.ptrVal = I.getArgOperand(0);
12276     Info.offset = 0;
12277     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12278     Info.vol = true;
12279     Info.readMem = true;
12280     Info.writeMem = false;
12281     return true;
12282   }
12283   case Intrinsic::arm_stlex:
12284   case Intrinsic::arm_strex: {
12285     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12286     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
12287     Info.opc = ISD::INTRINSIC_W_CHAIN;
12288     Info.memVT = MVT::getVT(PtrTy->getElementType());
12289     Info.ptrVal = I.getArgOperand(1);
12290     Info.offset = 0;
12291     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12292     Info.vol = true;
12293     Info.readMem = false;
12294     Info.writeMem = true;
12295     return true;
12296   }
12297   case Intrinsic::arm_stlexd:
12298   case Intrinsic::arm_strexd: {
12299     Info.opc = ISD::INTRINSIC_W_CHAIN;
12300     Info.memVT = MVT::i64;
12301     Info.ptrVal = I.getArgOperand(2);
12302     Info.offset = 0;
12303     Info.align = 8;
12304     Info.vol = true;
12305     Info.readMem = false;
12306     Info.writeMem = true;
12307     return true;
12308   }
12309   case Intrinsic::arm_ldaexd:
12310   case Intrinsic::arm_ldrexd: {
12311     Info.opc = ISD::INTRINSIC_W_CHAIN;
12312     Info.memVT = MVT::i64;
12313     Info.ptrVal = I.getArgOperand(0);
12314     Info.offset = 0;
12315     Info.align = 8;
12316     Info.vol = true;
12317     Info.readMem = true;
12318     Info.writeMem = false;
12319     return true;
12320   }
12321   default:
12322     break;
12323   }
12324 
12325   return false;
12326 }
12327 
12328 /// \brief Returns true if it is beneficial to convert a load of a constant
12329 /// to just the constant itself.
12330 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12331                                                           Type *Ty) const {
12332   assert(Ty->isIntegerTy());
12333 
12334   unsigned Bits = Ty->getPrimitiveSizeInBits();
12335   if (Bits == 0 || Bits > 32)
12336     return false;
12337   return true;
12338 }
12339 
12340 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
12341                                         ARM_MB::MemBOpt Domain) const {
12342   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12343 
12344   // First, if the target has no DMB, see what fallback we can use.
12345   if (!Subtarget->hasDataBarrier()) {
12346     // Some ARMv6 cpus can support data barriers with an mcr instruction.
12347     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
12348     // here.
12349     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
12350       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
12351       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
12352                         Builder.getInt32(0), Builder.getInt32(7),
12353                         Builder.getInt32(10), Builder.getInt32(5)};
12354       return Builder.CreateCall(MCR, args);
12355     } else {
12356       // Instead of using barriers, atomic accesses on these subtargets use
12357       // libcalls.
12358       llvm_unreachable("makeDMB on a target so old that it has no barriers");
12359     }
12360   } else {
12361     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
12362     // Only a full system barrier exists in the M-class architectures.
12363     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
12364     Constant *CDomain = Builder.getInt32(Domain);
12365     return Builder.CreateCall(DMB, CDomain);
12366   }
12367 }
12368 
12369 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
12370 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
12371                                          AtomicOrdering Ord, bool IsStore,
12372                                          bool IsLoad) const {
12373   switch (Ord) {
12374   case AtomicOrdering::NotAtomic:
12375   case AtomicOrdering::Unordered:
12376     llvm_unreachable("Invalid fence: unordered/non-atomic");
12377   case AtomicOrdering::Monotonic:
12378   case AtomicOrdering::Acquire:
12379     return nullptr; // Nothing to do
12380   case AtomicOrdering::SequentiallyConsistent:
12381     if (!IsStore)
12382       return nullptr; // Nothing to do
12383     /*FALLTHROUGH*/
12384   case AtomicOrdering::Release:
12385   case AtomicOrdering::AcquireRelease:
12386     if (Subtarget->preferISHSTBarriers())
12387       return makeDMB(Builder, ARM_MB::ISHST);
12388     // FIXME: add a comment with a link to documentation justifying this.
12389     else
12390       return makeDMB(Builder, ARM_MB::ISH);
12391   }
12392   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12393 }
12394 
12395 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12396                                           AtomicOrdering Ord, bool IsStore,
12397                                           bool IsLoad) const {
12398   switch (Ord) {
12399   case AtomicOrdering::NotAtomic:
12400   case AtomicOrdering::Unordered:
12401     llvm_unreachable("Invalid fence: unordered/not-atomic");
12402   case AtomicOrdering::Monotonic:
12403   case AtomicOrdering::Release:
12404     return nullptr; // Nothing to do
12405   case AtomicOrdering::Acquire:
12406   case AtomicOrdering::AcquireRelease:
12407   case AtomicOrdering::SequentiallyConsistent:
12408     return makeDMB(Builder, ARM_MB::ISH);
12409   }
12410   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12411 }
12412 
12413 // Loads and stores less than 64-bits are already atomic; ones above that
12414 // are doomed anyway, so defer to the default libcall and blame the OS when
12415 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12416 // anything for those.
12417 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12418   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12419   return (Size == 64) && !Subtarget->isMClass();
12420 }
12421 
12422 // Loads and stores less than 64-bits are already atomic; ones above that
12423 // are doomed anyway, so defer to the default libcall and blame the OS when
12424 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12425 // anything for those.
12426 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12427 // guarantee, see DDI0406C ARM architecture reference manual,
12428 // sections A8.8.72-74 LDRD)
12429 TargetLowering::AtomicExpansionKind
12430 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12431   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12432   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12433                                                   : AtomicExpansionKind::None;
12434 }
12435 
12436 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12437 // and up to 64 bits on the non-M profiles
12438 TargetLowering::AtomicExpansionKind
12439 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12440   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12441   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12442              ? AtomicExpansionKind::LLSC
12443              : AtomicExpansionKind::None;
12444 }
12445 
12446 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12447     AtomicCmpXchgInst *AI) const {
12448   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12449   // implement cmpxchg without spilling. If the address being exchanged is also
12450   // on the stack and close enough to the spill slot, this can lead to a
12451   // situation where the monitor always gets cleared and the atomic operation
12452   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12453   return getTargetMachine().getOptLevel() != 0;
12454 }
12455 
12456 bool ARMTargetLowering::shouldInsertFencesForAtomic(
12457     const Instruction *I) const {
12458   return InsertFencesForAtomic;
12459 }
12460 
12461 // This has so far only been implemented for MachO.
12462 bool ARMTargetLowering::useLoadStackGuardNode() const {
12463   return Subtarget->isTargetMachO();
12464 }
12465 
12466 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12467                                                   unsigned &Cost) const {
12468   // If we do not have NEON, vector types are not natively supported.
12469   if (!Subtarget->hasNEON())
12470     return false;
12471 
12472   // Floating point values and vector values map to the same register file.
12473   // Therefore, although we could do a store extract of a vector type, this is
12474   // better to leave at float as we have more freedom in the addressing mode for
12475   // those.
12476   if (VectorTy->isFPOrFPVectorTy())
12477     return false;
12478 
12479   // If the index is unknown at compile time, this is very expensive to lower
12480   // and it is not possible to combine the store with the extract.
12481   if (!isa<ConstantInt>(Idx))
12482     return false;
12483 
12484   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12485   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12486   // We can do a store + vector extract on any vector that fits perfectly in a D
12487   // or Q register.
12488   if (BitWidth == 64 || BitWidth == 128) {
12489     Cost = 0;
12490     return true;
12491   }
12492   return false;
12493 }
12494 
12495 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12496   return Subtarget->hasV6T2Ops();
12497 }
12498 
12499 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12500   return Subtarget->hasV6T2Ops();
12501 }
12502 
12503 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12504                                          AtomicOrdering Ord) const {
12505   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12506   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12507   bool IsAcquire = isAcquireOrStronger(Ord);
12508 
12509   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12510   // intrinsic must return {i32, i32} and we have to recombine them into a
12511   // single i64 here.
12512   if (ValTy->getPrimitiveSizeInBits() == 64) {
12513     Intrinsic::ID Int =
12514         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12515     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12516 
12517     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12518     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12519 
12520     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12521     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12522     if (!Subtarget->isLittle())
12523       std::swap (Lo, Hi);
12524     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12525     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12526     return Builder.CreateOr(
12527         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12528   }
12529 
12530   Type *Tys[] = { Addr->getType() };
12531   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12532   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12533 
12534   return Builder.CreateTruncOrBitCast(
12535       Builder.CreateCall(Ldrex, Addr),
12536       cast<PointerType>(Addr->getType())->getElementType());
12537 }
12538 
12539 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12540     IRBuilder<> &Builder) const {
12541   if (!Subtarget->hasV7Ops())
12542     return;
12543   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12544   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12545 }
12546 
12547 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12548                                                Value *Addr,
12549                                                AtomicOrdering Ord) const {
12550   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12551   bool IsRelease = isReleaseOrStronger(Ord);
12552 
12553   // Since the intrinsics must have legal type, the i64 intrinsics take two
12554   // parameters: "i32, i32". We must marshal Val into the appropriate form
12555   // before the call.
12556   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12557     Intrinsic::ID Int =
12558         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12559     Function *Strex = Intrinsic::getDeclaration(M, Int);
12560     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12561 
12562     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12563     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12564     if (!Subtarget->isLittle())
12565       std::swap (Lo, Hi);
12566     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12567     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12568   }
12569 
12570   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12571   Type *Tys[] = { Addr->getType() };
12572   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12573 
12574   return Builder.CreateCall(
12575       Strex, {Builder.CreateZExtOrBitCast(
12576                   Val, Strex->getFunctionType()->getParamType(0)),
12577               Addr});
12578 }
12579 
12580 /// \brief Lower an interleaved load into a vldN intrinsic.
12581 ///
12582 /// E.g. Lower an interleaved load (Factor = 2):
12583 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12584 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12585 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12586 ///
12587 ///      Into:
12588 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12589 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12590 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12591 bool ARMTargetLowering::lowerInterleavedLoad(
12592     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12593     ArrayRef<unsigned> Indices, unsigned Factor) const {
12594   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12595          "Invalid interleave factor");
12596   assert(!Shuffles.empty() && "Empty shufflevector input");
12597   assert(Shuffles.size() == Indices.size() &&
12598          "Unmatched number of shufflevectors and indices");
12599 
12600   VectorType *VecTy = Shuffles[0]->getType();
12601   Type *EltTy = VecTy->getVectorElementType();
12602 
12603   const DataLayout &DL = LI->getModule()->getDataLayout();
12604   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12605   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12606 
12607   // Skip if we do not have NEON and skip illegal vector types and vector types
12608   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12609   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12610     return false;
12611 
12612   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12613   // load integer vectors first and then convert to pointer vectors.
12614   if (EltTy->isPointerTy())
12615     VecTy =
12616         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12617 
12618   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12619                                             Intrinsic::arm_neon_vld3,
12620                                             Intrinsic::arm_neon_vld4};
12621 
12622   IRBuilder<> Builder(LI);
12623   SmallVector<Value *, 2> Ops;
12624 
12625   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12626   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12627   Ops.push_back(Builder.getInt32(LI->getAlignment()));
12628 
12629   Type *Tys[] = { VecTy, Int8Ptr };
12630   Function *VldnFunc =
12631       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12632   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12633 
12634   // Replace uses of each shufflevector with the corresponding vector loaded
12635   // by ldN.
12636   for (unsigned i = 0; i < Shuffles.size(); i++) {
12637     ShuffleVectorInst *SV = Shuffles[i];
12638     unsigned Index = Indices[i];
12639 
12640     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12641 
12642     // Convert the integer vector to pointer vector if the element is pointer.
12643     if (EltTy->isPointerTy())
12644       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12645 
12646     SV->replaceAllUsesWith(SubVec);
12647   }
12648 
12649   return true;
12650 }
12651 
12652 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12653 ///
12654 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12655 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12656                                    unsigned NumElts) {
12657   SmallVector<Constant *, 16> Mask;
12658   for (unsigned i = 0; i < NumElts; i++)
12659     Mask.push_back(Builder.getInt32(Start + i));
12660 
12661   return ConstantVector::get(Mask);
12662 }
12663 
12664 /// \brief Lower an interleaved store into a vstN intrinsic.
12665 ///
12666 /// E.g. Lower an interleaved store (Factor = 3):
12667 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12668 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12669 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12670 ///
12671 ///      Into:
12672 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12673 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12674 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12675 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12676 ///
12677 /// Note that the new shufflevectors will be removed and we'll only generate one
12678 /// vst3 instruction in CodeGen.
12679 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12680                                               ShuffleVectorInst *SVI,
12681                                               unsigned Factor) const {
12682   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12683          "Invalid interleave factor");
12684 
12685   VectorType *VecTy = SVI->getType();
12686   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12687          "Invalid interleaved store");
12688 
12689   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12690   Type *EltTy = VecTy->getVectorElementType();
12691   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12692 
12693   const DataLayout &DL = SI->getModule()->getDataLayout();
12694   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12695   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12696 
12697   // Skip if we do not have NEON and skip illegal vector types and vector types
12698   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12699   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12700       EltIs64Bits)
12701     return false;
12702 
12703   Value *Op0 = SVI->getOperand(0);
12704   Value *Op1 = SVI->getOperand(1);
12705   IRBuilder<> Builder(SI);
12706 
12707   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12708   // vectors to integer vectors.
12709   if (EltTy->isPointerTy()) {
12710     Type *IntTy = DL.getIntPtrType(EltTy);
12711 
12712     // Convert to the corresponding integer vector.
12713     Type *IntVecTy =
12714         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12715     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12716     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12717 
12718     SubVecTy = VectorType::get(IntTy, NumSubElts);
12719   }
12720 
12721   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12722                                              Intrinsic::arm_neon_vst3,
12723                                              Intrinsic::arm_neon_vst4};
12724   SmallVector<Value *, 6> Ops;
12725 
12726   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12727   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12728 
12729   Type *Tys[] = { Int8Ptr, SubVecTy };
12730   Function *VstNFunc = Intrinsic::getDeclaration(
12731       SI->getModule(), StoreInts[Factor - 2], Tys);
12732 
12733   // Split the shufflevector operands into sub vectors for the new vstN call.
12734   for (unsigned i = 0; i < Factor; i++)
12735     Ops.push_back(Builder.CreateShuffleVector(
12736         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12737 
12738   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12739   Builder.CreateCall(VstNFunc, Ops);
12740   return true;
12741 }
12742 
12743 enum HABaseType {
12744   HA_UNKNOWN = 0,
12745   HA_FLOAT,
12746   HA_DOUBLE,
12747   HA_VECT64,
12748   HA_VECT128
12749 };
12750 
12751 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12752                                    uint64_t &Members) {
12753   if (auto *ST = dyn_cast<StructType>(Ty)) {
12754     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12755       uint64_t SubMembers = 0;
12756       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12757         return false;
12758       Members += SubMembers;
12759     }
12760   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12761     uint64_t SubMembers = 0;
12762     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12763       return false;
12764     Members += SubMembers * AT->getNumElements();
12765   } else if (Ty->isFloatTy()) {
12766     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12767       return false;
12768     Members = 1;
12769     Base = HA_FLOAT;
12770   } else if (Ty->isDoubleTy()) {
12771     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12772       return false;
12773     Members = 1;
12774     Base = HA_DOUBLE;
12775   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12776     Members = 1;
12777     switch (Base) {
12778     case HA_FLOAT:
12779     case HA_DOUBLE:
12780       return false;
12781     case HA_VECT64:
12782       return VT->getBitWidth() == 64;
12783     case HA_VECT128:
12784       return VT->getBitWidth() == 128;
12785     case HA_UNKNOWN:
12786       switch (VT->getBitWidth()) {
12787       case 64:
12788         Base = HA_VECT64;
12789         return true;
12790       case 128:
12791         Base = HA_VECT128;
12792         return true;
12793       default:
12794         return false;
12795       }
12796     }
12797   }
12798 
12799   return (Members > 0 && Members <= 4);
12800 }
12801 
12802 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12803 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12804 /// passing according to AAPCS rules.
12805 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12806     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12807   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12808       CallingConv::ARM_AAPCS_VFP)
12809     return false;
12810 
12811   HABaseType Base = HA_UNKNOWN;
12812   uint64_t Members = 0;
12813   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12814   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12815 
12816   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12817   return IsHA || IsIntArray;
12818 }
12819 
12820 unsigned ARMTargetLowering::getExceptionPointerRegister(
12821     const Constant *PersonalityFn) const {
12822   // Platforms which do not use SjLj EH may return values in these registers
12823   // via the personality function.
12824   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12825 }
12826 
12827 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12828     const Constant *PersonalityFn) const {
12829   // Platforms which do not use SjLj EH may return values in these registers
12830   // via the personality function.
12831   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12832 }
12833 
12834 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12835   // Update IsSplitCSR in ARMFunctionInfo.
12836   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12837   AFI->setIsSplitCSR(true);
12838 }
12839 
12840 void ARMTargetLowering::insertCopiesSplitCSR(
12841     MachineBasicBlock *Entry,
12842     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12843   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12844   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12845   if (!IStart)
12846     return;
12847 
12848   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12849   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12850   MachineBasicBlock::iterator MBBI = Entry->begin();
12851   for (const MCPhysReg *I = IStart; *I; ++I) {
12852     const TargetRegisterClass *RC = nullptr;
12853     if (ARM::GPRRegClass.contains(*I))
12854       RC = &ARM::GPRRegClass;
12855     else if (ARM::DPRRegClass.contains(*I))
12856       RC = &ARM::DPRRegClass;
12857     else
12858       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12859 
12860     unsigned NewVR = MRI->createVirtualRegister(RC);
12861     // Create copy from CSR to a virtual register.
12862     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12863     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12864     // nounwind. If we want to generalize this later, we may need to emit
12865     // CFI pseudo-instructions.
12866     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12867                Attribute::NoUnwind) &&
12868            "Function should be nounwind in insertCopiesSplitCSR!");
12869     Entry->addLiveIn(*I);
12870     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12871         .addReg(*I);
12872 
12873     // Insert the copy-back instructions right before the terminator.
12874     for (auto *Exit : Exits)
12875       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12876               TII->get(TargetOpcode::COPY), *I)
12877           .addReg(NewVR);
12878   }
12879 }
12880