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->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       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
394       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
395       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
396       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
397     };
398 
399     for (const auto &LC : LibraryCalls) {
400       setLibcallName(LC.Op, LC.Name);
401       setLibcallCallingConv(LC.Op, LC.CC);
402     }
403   }
404 
405   // Use divmod compiler-rt calls for iOS 5.0 and later.
406   if (Subtarget->isTargetWatchOS() ||
407       (Subtarget->isTargetIOS() &&
408        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
409     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
410     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
411   }
412 
413   // The half <-> float conversion functions are always soft-float, but are
414   // needed for some targets which use a hard-float calling convention by
415   // default.
416   if (Subtarget->isAAPCS_ABI()) {
417     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
418     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
420   } else {
421     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
422     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
423     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
424   }
425 
426   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
427   // a __gnu_ prefix (which is the default).
428   if (Subtarget->isTargetAEABI()) {
429     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
430     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
431     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
432   }
433 
434   if (Subtarget->isThumb1Only())
435     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436   else
437     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
439       !Subtarget->isThumb1Only()) {
440     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442   }
443 
444   for (MVT VT : MVT::vector_valuetypes()) {
445     for (MVT InnerVT : MVT::vector_valuetypes()) {
446       setTruncStoreAction(VT, InnerVT, Expand);
447       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
448       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
449       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
450     }
451 
452     setOperationAction(ISD::MULHS, VT, Expand);
453     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454     setOperationAction(ISD::MULHU, VT, Expand);
455     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
456 
457     setOperationAction(ISD::BSWAP, VT, Expand);
458   }
459 
460   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
461   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
462 
463   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
464   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
465 
466   if (Subtarget->hasNEON()) {
467     addDRTypeForNEON(MVT::v2f32);
468     addDRTypeForNEON(MVT::v8i8);
469     addDRTypeForNEON(MVT::v4i16);
470     addDRTypeForNEON(MVT::v2i32);
471     addDRTypeForNEON(MVT::v1i64);
472 
473     addQRTypeForNEON(MVT::v4f32);
474     addQRTypeForNEON(MVT::v2f64);
475     addQRTypeForNEON(MVT::v16i8);
476     addQRTypeForNEON(MVT::v8i16);
477     addQRTypeForNEON(MVT::v4i32);
478     addQRTypeForNEON(MVT::v2i64);
479 
480     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
481     // neither Neon nor VFP support any arithmetic operations on it.
482     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
483     // supported for v4f32.
484     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
485     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
486     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
487     // FIXME: Code duplication: FDIV and FREM are expanded always, see
488     // ARMTargetLowering::addTypeForNEON method for details.
489     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
490     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
491     // FIXME: Create unittest.
492     // In another words, find a way when "copysign" appears in DAG with vector
493     // operands.
494     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
495     // FIXME: Code duplication: SETCC has custom operation action, see
496     // ARMTargetLowering::addTypeForNEON method for details.
497     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
498     // FIXME: Create unittest for FNEG and for FABS.
499     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
501     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
511     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
512     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
513     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
514     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
515     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
516     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
517     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
518 
519     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
520     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
521     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
522     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
523     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
524     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
525     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
526     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
527     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
528     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
529     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
530     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
531     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
532     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
533     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
534 
535     // Mark v2f32 intrinsics.
536     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
537     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
538     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
539     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
540     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
541     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
542     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
543     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
544     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
545     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
546     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
547     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
548     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
549     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
550     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
551 
552     // Neon does not support some operations on v1i64 and v2i64 types.
553     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
554     // Custom handling for some quad-vector types to detect VMULL.
555     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
556     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
557     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
558     // Custom handling for some vector types to avoid expensive expansions
559     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
560     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
561     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
562     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
563     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
564     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
565     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
566     // a destination type that is wider than the source, and nor does
567     // it have a FP_TO_[SU]INT instruction with a narrower destination than
568     // source.
569     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
570     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
571     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
572     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
573 
574     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
575     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
576 
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584 
585     // NEON does not have single instruction CTTZ for vectors.
586     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
587     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
588     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
589     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
590 
591     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
592     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
593     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
594     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
595 
596     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
597     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
598     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
599     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
600 
601     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
602     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
603     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
604     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
605 
606     // NEON only has FMA instructions as of VFP4.
607     if (!Subtarget->hasVFP4()) {
608       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
609       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
610     }
611 
612     setTargetDAGCombine(ISD::INTRINSIC_VOID);
613     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
614     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
615     setTargetDAGCombine(ISD::SHL);
616     setTargetDAGCombine(ISD::SRL);
617     setTargetDAGCombine(ISD::SRA);
618     setTargetDAGCombine(ISD::SIGN_EXTEND);
619     setTargetDAGCombine(ISD::ZERO_EXTEND);
620     setTargetDAGCombine(ISD::ANY_EXTEND);
621     setTargetDAGCombine(ISD::BUILD_VECTOR);
622     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
623     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
624     setTargetDAGCombine(ISD::STORE);
625     setTargetDAGCombine(ISD::FP_TO_SINT);
626     setTargetDAGCombine(ISD::FP_TO_UINT);
627     setTargetDAGCombine(ISD::FDIV);
628     setTargetDAGCombine(ISD::LOAD);
629 
630     // It is legal to extload from v4i8 to v4i16 or v4i32.
631     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
632                    MVT::v2i32}) {
633       for (MVT VT : MVT::integer_vector_valuetypes()) {
634         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
635         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
636         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
637       }
638     }
639   }
640 
641   // ARM and Thumb2 support UMLAL/SMLAL.
642   if (!Subtarget->isThumb1Only())
643     setTargetDAGCombine(ISD::ADDC);
644 
645   if (Subtarget->isFPOnlySP()) {
646     // When targeting a floating-point unit with only single-precision
647     // operations, f64 is legal for the few double-precision instructions which
648     // are present However, no double-precision operations other than moves,
649     // loads and stores are provided by the hardware.
650     setOperationAction(ISD::FADD,       MVT::f64, Expand);
651     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
652     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
653     setOperationAction(ISD::FMA,        MVT::f64, Expand);
654     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
655     setOperationAction(ISD::FREM,       MVT::f64, Expand);
656     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
657     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
658     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
659     setOperationAction(ISD::FABS,       MVT::f64, Expand);
660     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
661     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
662     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
663     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
664     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
665     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
666     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
667     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
668     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
669     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
670     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
671     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
672     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
673     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
674     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
675     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
676     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
677     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
678     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
679     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
680     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
681     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
682     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
683   }
684 
685   computeRegisterProperties(Subtarget->getRegisterInfo());
686 
687   // ARM does not have floating-point extending loads.
688   for (MVT VT : MVT::fp_valuetypes()) {
689     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
690     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
691   }
692 
693   // ... or truncating stores
694   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
695   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
696   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
697 
698   // ARM does not have i1 sign extending load.
699   for (MVT VT : MVT::integer_valuetypes())
700     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
701 
702   // ARM supports all 4 flavors of integer indexed load / store.
703   if (!Subtarget->isThumb1Only()) {
704     for (unsigned im = (unsigned)ISD::PRE_INC;
705          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
706       setIndexedLoadAction(im,  MVT::i1,  Legal);
707       setIndexedLoadAction(im,  MVT::i8,  Legal);
708       setIndexedLoadAction(im,  MVT::i16, Legal);
709       setIndexedLoadAction(im,  MVT::i32, Legal);
710       setIndexedStoreAction(im, MVT::i1,  Legal);
711       setIndexedStoreAction(im, MVT::i8,  Legal);
712       setIndexedStoreAction(im, MVT::i16, Legal);
713       setIndexedStoreAction(im, MVT::i32, Legal);
714     }
715   }
716 
717   setOperationAction(ISD::SADDO, MVT::i32, Custom);
718   setOperationAction(ISD::UADDO, MVT::i32, Custom);
719   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
720   setOperationAction(ISD::USUBO, MVT::i32, Custom);
721 
722   // i64 operation support.
723   setOperationAction(ISD::MUL,     MVT::i64, Expand);
724   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
725   if (Subtarget->isThumb1Only()) {
726     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
727     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
728   }
729   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
730       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
731     setOperationAction(ISD::MULHS, MVT::i32, Expand);
732 
733   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
734   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
735   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
736   setOperationAction(ISD::SRL,       MVT::i64, Custom);
737   setOperationAction(ISD::SRA,       MVT::i64, Custom);
738 
739   if (!Subtarget->isThumb1Only()) {
740     // FIXME: We should do this for Thumb1 as well.
741     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
742     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
743     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
744     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
745   }
746 
747   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
748     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
749 
750   // ARM does not have ROTL.
751   setOperationAction(ISD::ROTL, MVT::i32, Expand);
752   for (MVT VT : MVT::vector_valuetypes()) {
753     setOperationAction(ISD::ROTL, VT, Expand);
754     setOperationAction(ISD::ROTR, VT, Expand);
755   }
756   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
757   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
758   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
759     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
760 
761   // These just redirect to CTTZ and CTLZ on ARM.
762   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
763   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
764 
765   // @llvm.readcyclecounter requires the Performance Monitors extension.
766   // Default to the 0 expansion on unsupported platforms.
767   // FIXME: Technically there are older ARM CPUs that have
768   // implementation-specific ways of obtaining this information.
769   if (Subtarget->hasPerfMon())
770     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
771 
772   // Only ARMv6 has BSWAP.
773   if (!Subtarget->hasV6Ops())
774     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
775 
776   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
777                                         : Subtarget->hasDivideInARMMode();
778   if (!hasDivide) {
779     // These are expanded into libcalls if the cpu doesn't have HW divider.
780     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
781     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
782   }
783 
784   setOperationAction(ISD::SREM,  MVT::i32, Expand);
785   setOperationAction(ISD::UREM,  MVT::i32, Expand);
786   // Register based DivRem for AEABI (RTABI 4.2)
787   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
788       Subtarget->isTargetGNUAEABI()) {
789     setOperationAction(ISD::SREM, MVT::i64, Custom);
790     setOperationAction(ISD::UREM, MVT::i64, Custom);
791 
792     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
793     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
794     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
795     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
796     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
797     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
798     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
799     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
800 
801     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
802     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
803     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
804     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
805     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
806     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
807     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
808     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
809 
810     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
811     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
812     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
813     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
814   } else {
815     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
816     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
817   }
818 
819   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
820   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
821   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
822   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
823 
824   setOperationAction(ISD::TRAP, MVT::Other, Legal);
825 
826   // Use the default implementation.
827   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
828   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
829   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
830   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
831   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
832   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
833 
834   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
835     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
836   else
837     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
838 
839   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
840   // the default expansion. If we are targeting a single threaded system,
841   // then set them all for expand so we can lower them later into their
842   // non-atomic form.
843   if (TM.Options.ThreadModel == ThreadModel::Single)
844     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
845   else if (Subtarget->hasAnyDataBarrier() && (!Subtarget->isThumb() ||
846                                               Subtarget->hasV8MBaselineOps())) {
847     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
848     // to ldrex/strex loops already.
849     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
850 
851     // On v8, we have particularly efficient implementations of atomic fences
852     // if they can be combined with nearby atomic loads and stores.
853     if (!Subtarget->hasV8Ops()) {
854       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
855       setInsertFencesForAtomic(true);
856     }
857   } else {
858     // If there's anything we can use as a barrier, go through custom lowering
859     // for ATOMIC_FENCE.
860     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
861                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
862 
863     // Set them all for expansion, which will force libcalls.
864     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
865     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
866     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
867     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
868     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
869     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
870     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
871     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
872     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
873     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
874     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
875     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
876     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
877     // Unordered/Monotonic case.
878     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
879     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
880   }
881 
882   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
883 
884   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
885   if (!Subtarget->hasV6Ops()) {
886     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
887     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
888   }
889   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
890 
891   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892       !Subtarget->isThumb1Only()) {
893     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
894     // iff target supports vfp2.
895     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
896     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
897   }
898 
899   // We want to custom lower some of our intrinsics.
900   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
901   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
902   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
903   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
904   if (Subtarget->useSjLjEH())
905     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
906 
907   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
908   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
909   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
910   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
911   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
912   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
913   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
914   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
915   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
916 
917   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
918   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
919   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
920   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
921   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
922 
923   // We don't support sin/cos/fmod/copysign/pow
924   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
925   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
926   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
927   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
928   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
929   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
930   setOperationAction(ISD::FREM,      MVT::f64, Expand);
931   setOperationAction(ISD::FREM,      MVT::f32, Expand);
932   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
933       !Subtarget->isThumb1Only()) {
934     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
935     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
936   }
937   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
938   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
939 
940   if (!Subtarget->hasVFP4()) {
941     setOperationAction(ISD::FMA, MVT::f64, Expand);
942     setOperationAction(ISD::FMA, MVT::f32, Expand);
943   }
944 
945   // Various VFP goodness
946   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
947     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
948     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
949       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
950       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
951     }
952 
953     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
954     if (!Subtarget->hasFP16()) {
955       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
956       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
957     }
958   }
959 
960   // Combine sin / cos into one node or libcall if possible.
961   if (Subtarget->hasSinCos()) {
962     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
963     setLibcallName(RTLIB::SINCOS_F64, "sincos");
964     if (Subtarget->isTargetWatchABI()) {
965       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
966       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
967     }
968     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
969       // For iOS, we don't want to the normal expansion of a libcall to
970       // sincos. We want to issue a libcall to __sincos_stret.
971       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
972       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
973     }
974   }
975 
976   // FP-ARMv8 implements a lot of rounding-like FP operations.
977   if (Subtarget->hasFPARMv8()) {
978     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
979     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
980     setOperationAction(ISD::FROUND, MVT::f32, Legal);
981     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
982     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
983     setOperationAction(ISD::FRINT, MVT::f32, Legal);
984     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
985     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
986     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
987     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
988     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
989     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
990 
991     if (!Subtarget->isFPOnlySP()) {
992       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
993       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
994       setOperationAction(ISD::FROUND, MVT::f64, Legal);
995       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
996       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
997       setOperationAction(ISD::FRINT, MVT::f64, Legal);
998       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
999       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1000     }
1001   }
1002 
1003   if (Subtarget->hasNEON()) {
1004     // vmin and vmax aren't available in a scalar form, so we use
1005     // a NEON instruction with an undef lane instead.
1006     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1007     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1008     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1009     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1010     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1011     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1012   }
1013 
1014   // We have target-specific dag combine patterns for the following nodes:
1015   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1016   setTargetDAGCombine(ISD::ADD);
1017   setTargetDAGCombine(ISD::SUB);
1018   setTargetDAGCombine(ISD::MUL);
1019   setTargetDAGCombine(ISD::AND);
1020   setTargetDAGCombine(ISD::OR);
1021   setTargetDAGCombine(ISD::XOR);
1022 
1023   if (Subtarget->hasV6Ops())
1024     setTargetDAGCombine(ISD::SRL);
1025 
1026   setStackPointerRegisterToSaveRestore(ARM::SP);
1027 
1028   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1029       !Subtarget->hasVFP2())
1030     setSchedulingPreference(Sched::RegPressure);
1031   else
1032     setSchedulingPreference(Sched::Hybrid);
1033 
1034   //// temporary - rewrite interface to use type
1035   MaxStoresPerMemset = 8;
1036   MaxStoresPerMemsetOptSize = 4;
1037   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1038   MaxStoresPerMemcpyOptSize = 2;
1039   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1040   MaxStoresPerMemmoveOptSize = 2;
1041 
1042   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1043   // are at least 4 bytes aligned.
1044   setMinStackArgumentAlignment(4);
1045 
1046   // Prefer likely predicted branches to selects on out-of-order cores.
1047   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1048 
1049   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1050 }
1051 
1052 bool ARMTargetLowering::useSoftFloat() const {
1053   return Subtarget->useSoftFloat();
1054 }
1055 
1056 // FIXME: It might make sense to define the representative register class as the
1057 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1058 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1059 // SPR's representative would be DPR_VFP2. This should work well if register
1060 // pressure tracking were modified such that a register use would increment the
1061 // pressure of the register class's representative and all of it's super
1062 // classes' representatives transitively. We have not implemented this because
1063 // of the difficulty prior to coalescing of modeling operand register classes
1064 // due to the common occurrence of cross class copies and subregister insertions
1065 // and extractions.
1066 std::pair<const TargetRegisterClass *, uint8_t>
1067 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1068                                            MVT VT) const {
1069   const TargetRegisterClass *RRC = nullptr;
1070   uint8_t Cost = 1;
1071   switch (VT.SimpleTy) {
1072   default:
1073     return TargetLowering::findRepresentativeClass(TRI, VT);
1074   // Use DPR as representative register class for all floating point
1075   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1076   // the cost is 1 for both f32 and f64.
1077   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1078   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1079     RRC = &ARM::DPRRegClass;
1080     // When NEON is used for SP, only half of the register file is available
1081     // because operations that define both SP and DP results will be constrained
1082     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1083     // coalescing by double-counting the SP regs. See the FIXME above.
1084     if (Subtarget->useNEONForSinglePrecisionFP())
1085       Cost = 2;
1086     break;
1087   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1088   case MVT::v4f32: case MVT::v2f64:
1089     RRC = &ARM::DPRRegClass;
1090     Cost = 2;
1091     break;
1092   case MVT::v4i64:
1093     RRC = &ARM::DPRRegClass;
1094     Cost = 4;
1095     break;
1096   case MVT::v8i64:
1097     RRC = &ARM::DPRRegClass;
1098     Cost = 8;
1099     break;
1100   }
1101   return std::make_pair(RRC, Cost);
1102 }
1103 
1104 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1105   switch ((ARMISD::NodeType)Opcode) {
1106   case ARMISD::FIRST_NUMBER:  break;
1107   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1108   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1109   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1110   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1111   case ARMISD::CALL:          return "ARMISD::CALL";
1112   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1113   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1114   case ARMISD::tCALL:         return "ARMISD::tCALL";
1115   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1116   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1117   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1118   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1119   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1120   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1121   case ARMISD::CMP:           return "ARMISD::CMP";
1122   case ARMISD::CMN:           return "ARMISD::CMN";
1123   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1124   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1125   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1126   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1127   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1128 
1129   case ARMISD::CMOV:          return "ARMISD::CMOV";
1130 
1131   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1132   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1133   case ARMISD::RRX:           return "ARMISD::RRX";
1134 
1135   case ARMISD::ADDC:          return "ARMISD::ADDC";
1136   case ARMISD::ADDE:          return "ARMISD::ADDE";
1137   case ARMISD::SUBC:          return "ARMISD::SUBC";
1138   case ARMISD::SUBE:          return "ARMISD::SUBE";
1139 
1140   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1141   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1142 
1143   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1144   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1145   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1146 
1147   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1148 
1149   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1150 
1151   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1152 
1153   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1154 
1155   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1156 
1157   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1158   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1159 
1160   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1161   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1162   case ARMISD::VCGE:          return "ARMISD::VCGE";
1163   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1164   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1165   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1166   case ARMISD::VCGT:          return "ARMISD::VCGT";
1167   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1168   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1169   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1170   case ARMISD::VTST:          return "ARMISD::VTST";
1171 
1172   case ARMISD::VSHL:          return "ARMISD::VSHL";
1173   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1174   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1175   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1176   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1177   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1178   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1179   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1180   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1181   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1182   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1183   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1184   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1185   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1186   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1187   case ARMISD::VSLI:          return "ARMISD::VSLI";
1188   case ARMISD::VSRI:          return "ARMISD::VSRI";
1189   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1190   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1191   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1192   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1193   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1194   case ARMISD::VDUP:          return "ARMISD::VDUP";
1195   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1196   case ARMISD::VEXT:          return "ARMISD::VEXT";
1197   case ARMISD::VREV64:        return "ARMISD::VREV64";
1198   case ARMISD::VREV32:        return "ARMISD::VREV32";
1199   case ARMISD::VREV16:        return "ARMISD::VREV16";
1200   case ARMISD::VZIP:          return "ARMISD::VZIP";
1201   case ARMISD::VUZP:          return "ARMISD::VUZP";
1202   case ARMISD::VTRN:          return "ARMISD::VTRN";
1203   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1204   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1205   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1206   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1207   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1208   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1209   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1210   case ARMISD::BFI:           return "ARMISD::BFI";
1211   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1212   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1213   case ARMISD::VBSL:          return "ARMISD::VBSL";
1214   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1215   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1216   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1217   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1218   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1219   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1220   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1221   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1222   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1223   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1224   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1225   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1226   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1227   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1228   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1229   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1230   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1231   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1232   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1233   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1234   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1235   }
1236   return nullptr;
1237 }
1238 
1239 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1240                                           EVT VT) const {
1241   if (!VT.isVector())
1242     return getPointerTy(DL);
1243   return VT.changeVectorElementTypeToInteger();
1244 }
1245 
1246 /// getRegClassFor - Return the register class that should be used for the
1247 /// specified value type.
1248 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1249   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1250   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1251   // load / store 4 to 8 consecutive D registers.
1252   if (Subtarget->hasNEON()) {
1253     if (VT == MVT::v4i64)
1254       return &ARM::QQPRRegClass;
1255     if (VT == MVT::v8i64)
1256       return &ARM::QQQQPRRegClass;
1257   }
1258   return TargetLowering::getRegClassFor(VT);
1259 }
1260 
1261 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1262 // source/dest is aligned and the copy size is large enough. We therefore want
1263 // to align such objects passed to memory intrinsics.
1264 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1265                                                unsigned &PrefAlign) const {
1266   if (!isa<MemIntrinsic>(CI))
1267     return false;
1268   MinSize = 8;
1269   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1270   // cycle faster than 4-byte aligned LDM.
1271   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1272   return true;
1273 }
1274 
1275 // Create a fast isel object.
1276 FastISel *
1277 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1278                                   const TargetLibraryInfo *libInfo) const {
1279   return ARM::createFastISel(funcInfo, libInfo);
1280 }
1281 
1282 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1283   unsigned NumVals = N->getNumValues();
1284   if (!NumVals)
1285     return Sched::RegPressure;
1286 
1287   for (unsigned i = 0; i != NumVals; ++i) {
1288     EVT VT = N->getValueType(i);
1289     if (VT == MVT::Glue || VT == MVT::Other)
1290       continue;
1291     if (VT.isFloatingPoint() || VT.isVector())
1292       return Sched::ILP;
1293   }
1294 
1295   if (!N->isMachineOpcode())
1296     return Sched::RegPressure;
1297 
1298   // Load are scheduled for latency even if there instruction itinerary
1299   // is not available.
1300   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1301   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1302 
1303   if (MCID.getNumDefs() == 0)
1304     return Sched::RegPressure;
1305   if (!Itins->isEmpty() &&
1306       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1307     return Sched::ILP;
1308 
1309   return Sched::RegPressure;
1310 }
1311 
1312 //===----------------------------------------------------------------------===//
1313 // Lowering Code
1314 //===----------------------------------------------------------------------===//
1315 
1316 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1317 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1318   switch (CC) {
1319   default: llvm_unreachable("Unknown condition code!");
1320   case ISD::SETNE:  return ARMCC::NE;
1321   case ISD::SETEQ:  return ARMCC::EQ;
1322   case ISD::SETGT:  return ARMCC::GT;
1323   case ISD::SETGE:  return ARMCC::GE;
1324   case ISD::SETLT:  return ARMCC::LT;
1325   case ISD::SETLE:  return ARMCC::LE;
1326   case ISD::SETUGT: return ARMCC::HI;
1327   case ISD::SETUGE: return ARMCC::HS;
1328   case ISD::SETULT: return ARMCC::LO;
1329   case ISD::SETULE: return ARMCC::LS;
1330   }
1331 }
1332 
1333 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1334 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1335                         ARMCC::CondCodes &CondCode2) {
1336   CondCode2 = ARMCC::AL;
1337   switch (CC) {
1338   default: llvm_unreachable("Unknown FP condition!");
1339   case ISD::SETEQ:
1340   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1341   case ISD::SETGT:
1342   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1343   case ISD::SETGE:
1344   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1345   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1346   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1347   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1348   case ISD::SETO:   CondCode = ARMCC::VC; break;
1349   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1350   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1351   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1352   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1353   case ISD::SETLT:
1354   case ISD::SETULT: CondCode = ARMCC::LT; break;
1355   case ISD::SETLE:
1356   case ISD::SETULE: CondCode = ARMCC::LE; break;
1357   case ISD::SETNE:
1358   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1359   }
1360 }
1361 
1362 //===----------------------------------------------------------------------===//
1363 //                      Calling Convention Implementation
1364 //===----------------------------------------------------------------------===//
1365 
1366 #include "ARMGenCallingConv.inc"
1367 
1368 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1369 /// account presence of floating point hardware and calling convention
1370 /// limitations, such as support for variadic functions.
1371 CallingConv::ID
1372 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1373                                            bool isVarArg) const {
1374   switch (CC) {
1375   default:
1376     llvm_unreachable("Unsupported calling convention");
1377   case CallingConv::ARM_AAPCS:
1378   case CallingConv::ARM_APCS:
1379   case CallingConv::GHC:
1380     return CC;
1381   case CallingConv::PreserveMost:
1382     return CallingConv::PreserveMost;
1383   case CallingConv::ARM_AAPCS_VFP:
1384     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1385   case CallingConv::C:
1386     if (!Subtarget->isAAPCS_ABI())
1387       return CallingConv::ARM_APCS;
1388     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1389              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1390              !isVarArg)
1391       return CallingConv::ARM_AAPCS_VFP;
1392     else
1393       return CallingConv::ARM_AAPCS;
1394   case CallingConv::Fast:
1395   case CallingConv::CXX_FAST_TLS:
1396     if (!Subtarget->isAAPCS_ABI()) {
1397       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1398         return CallingConv::Fast;
1399       return CallingConv::ARM_APCS;
1400     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1401       return CallingConv::ARM_AAPCS_VFP;
1402     else
1403       return CallingConv::ARM_AAPCS;
1404   }
1405 }
1406 
1407 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1408 /// CallingConvention.
1409 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1410                                                  bool Return,
1411                                                  bool isVarArg) const {
1412   switch (getEffectiveCallingConv(CC, isVarArg)) {
1413   default:
1414     llvm_unreachable("Unsupported calling convention");
1415   case CallingConv::ARM_APCS:
1416     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1417   case CallingConv::ARM_AAPCS:
1418     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1419   case CallingConv::ARM_AAPCS_VFP:
1420     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1421   case CallingConv::Fast:
1422     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1423   case CallingConv::GHC:
1424     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1425   case CallingConv::PreserveMost:
1426     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1427   }
1428 }
1429 
1430 /// LowerCallResult - Lower the result values of a call into the
1431 /// appropriate copies out of appropriate physical registers.
1432 SDValue
1433 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1434                                    CallingConv::ID CallConv, bool isVarArg,
1435                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1436                                    SDLoc dl, SelectionDAG &DAG,
1437                                    SmallVectorImpl<SDValue> &InVals,
1438                                    bool isThisReturn, SDValue ThisVal) const {
1439 
1440   // Assign locations to each value returned by this call.
1441   SmallVector<CCValAssign, 16> RVLocs;
1442   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1443                     *DAG.getContext(), Call);
1444   CCInfo.AnalyzeCallResult(Ins,
1445                            CCAssignFnForNode(CallConv, /* Return*/ true,
1446                                              isVarArg));
1447 
1448   // Copy all of the result registers out of their specified physreg.
1449   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1450     CCValAssign VA = RVLocs[i];
1451 
1452     // Pass 'this' value directly from the argument to return value, to avoid
1453     // reg unit interference
1454     if (i == 0 && isThisReturn) {
1455       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1456              "unexpected return calling convention register assignment");
1457       InVals.push_back(ThisVal);
1458       continue;
1459     }
1460 
1461     SDValue Val;
1462     if (VA.needsCustom()) {
1463       // Handle f64 or half of a v2f64.
1464       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1465                                       InFlag);
1466       Chain = Lo.getValue(1);
1467       InFlag = Lo.getValue(2);
1468       VA = RVLocs[++i]; // skip ahead to next loc
1469       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1470                                       InFlag);
1471       Chain = Hi.getValue(1);
1472       InFlag = Hi.getValue(2);
1473       if (!Subtarget->isLittle())
1474         std::swap (Lo, Hi);
1475       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1476 
1477       if (VA.getLocVT() == MVT::v2f64) {
1478         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1479         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1480                           DAG.getConstant(0, dl, MVT::i32));
1481 
1482         VA = RVLocs[++i]; // skip ahead to next loc
1483         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1484         Chain = Lo.getValue(1);
1485         InFlag = Lo.getValue(2);
1486         VA = RVLocs[++i]; // skip ahead to next loc
1487         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1488         Chain = Hi.getValue(1);
1489         InFlag = Hi.getValue(2);
1490         if (!Subtarget->isLittle())
1491           std::swap (Lo, Hi);
1492         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1493         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1494                           DAG.getConstant(1, dl, MVT::i32));
1495       }
1496     } else {
1497       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1498                                InFlag);
1499       Chain = Val.getValue(1);
1500       InFlag = Val.getValue(2);
1501     }
1502 
1503     switch (VA.getLocInfo()) {
1504     default: llvm_unreachable("Unknown loc info!");
1505     case CCValAssign::Full: break;
1506     case CCValAssign::BCvt:
1507       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1508       break;
1509     }
1510 
1511     InVals.push_back(Val);
1512   }
1513 
1514   return Chain;
1515 }
1516 
1517 /// LowerMemOpCallTo - Store the argument to the stack.
1518 SDValue
1519 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1520                                     SDValue StackPtr, SDValue Arg,
1521                                     SDLoc dl, SelectionDAG &DAG,
1522                                     const CCValAssign &VA,
1523                                     ISD::ArgFlagsTy Flags) const {
1524   unsigned LocMemOffset = VA.getLocMemOffset();
1525   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1526   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1527                        StackPtr, PtrOff);
1528   return DAG.getStore(
1529       Chain, dl, Arg, PtrOff,
1530       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1531       false, false, 0);
1532 }
1533 
1534 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1535                                          SDValue Chain, SDValue &Arg,
1536                                          RegsToPassVector &RegsToPass,
1537                                          CCValAssign &VA, CCValAssign &NextVA,
1538                                          SDValue &StackPtr,
1539                                          SmallVectorImpl<SDValue> &MemOpChains,
1540                                          ISD::ArgFlagsTy Flags) const {
1541 
1542   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1543                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1544   unsigned id = Subtarget->isLittle() ? 0 : 1;
1545   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1546 
1547   if (NextVA.isRegLoc())
1548     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1549   else {
1550     assert(NextVA.isMemLoc());
1551     if (!StackPtr.getNode())
1552       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1553                                     getPointerTy(DAG.getDataLayout()));
1554 
1555     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1556                                            dl, DAG, NextVA,
1557                                            Flags));
1558   }
1559 }
1560 
1561 /// LowerCall - Lowering a call into a callseq_start <-
1562 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1563 /// nodes.
1564 SDValue
1565 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1566                              SmallVectorImpl<SDValue> &InVals) const {
1567   SelectionDAG &DAG                     = CLI.DAG;
1568   SDLoc &dl                             = CLI.DL;
1569   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1570   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1571   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1572   SDValue Chain                         = CLI.Chain;
1573   SDValue Callee                        = CLI.Callee;
1574   bool &isTailCall                      = CLI.IsTailCall;
1575   CallingConv::ID CallConv              = CLI.CallConv;
1576   bool doesNotRet                       = CLI.DoesNotReturn;
1577   bool isVarArg                         = CLI.IsVarArg;
1578 
1579   MachineFunction &MF = DAG.getMachineFunction();
1580   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1581   bool isThisReturn   = false;
1582   bool isSibCall      = false;
1583   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1584 
1585   // Disable tail calls if they're not supported.
1586   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1587     isTailCall = false;
1588 
1589   if (isTailCall) {
1590     // Check if it's really possible to do a tail call.
1591     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1592                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1593                                                    Outs, OutVals, Ins, DAG);
1594     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1595       report_fatal_error("failed to perform tail call elimination on a call "
1596                          "site marked musttail");
1597     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1598     // detected sibcalls.
1599     if (isTailCall) {
1600       ++NumTailCalls;
1601       isSibCall = true;
1602     }
1603   }
1604 
1605   // Analyze operands of the call, assigning locations to each operand.
1606   SmallVector<CCValAssign, 16> ArgLocs;
1607   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1608                     *DAG.getContext(), Call);
1609   CCInfo.AnalyzeCallOperands(Outs,
1610                              CCAssignFnForNode(CallConv, /* Return*/ false,
1611                                                isVarArg));
1612 
1613   // Get a count of how many bytes are to be pushed on the stack.
1614   unsigned NumBytes = CCInfo.getNextStackOffset();
1615 
1616   // For tail calls, memory operands are available in our caller's stack.
1617   if (isSibCall)
1618     NumBytes = 0;
1619 
1620   // Adjust the stack pointer for the new arguments...
1621   // These operations are automatically eliminated by the prolog/epilog pass
1622   if (!isSibCall)
1623     Chain = DAG.getCALLSEQ_START(Chain,
1624                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1625 
1626   SDValue StackPtr =
1627       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1628 
1629   RegsToPassVector RegsToPass;
1630   SmallVector<SDValue, 8> MemOpChains;
1631 
1632   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1633   // of tail call optimization, arguments are handled later.
1634   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1635        i != e;
1636        ++i, ++realArgIdx) {
1637     CCValAssign &VA = ArgLocs[i];
1638     SDValue Arg = OutVals[realArgIdx];
1639     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1640     bool isByVal = Flags.isByVal();
1641 
1642     // Promote the value if needed.
1643     switch (VA.getLocInfo()) {
1644     default: llvm_unreachable("Unknown loc info!");
1645     case CCValAssign::Full: break;
1646     case CCValAssign::SExt:
1647       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1648       break;
1649     case CCValAssign::ZExt:
1650       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1651       break;
1652     case CCValAssign::AExt:
1653       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1654       break;
1655     case CCValAssign::BCvt:
1656       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1657       break;
1658     }
1659 
1660     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1661     if (VA.needsCustom()) {
1662       if (VA.getLocVT() == MVT::v2f64) {
1663         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1664                                   DAG.getConstant(0, dl, MVT::i32));
1665         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1666                                   DAG.getConstant(1, dl, MVT::i32));
1667 
1668         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1669                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1670 
1671         VA = ArgLocs[++i]; // skip ahead to next loc
1672         if (VA.isRegLoc()) {
1673           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1674                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1675         } else {
1676           assert(VA.isMemLoc());
1677 
1678           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1679                                                  dl, DAG, VA, Flags));
1680         }
1681       } else {
1682         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1683                          StackPtr, MemOpChains, Flags);
1684       }
1685     } else if (VA.isRegLoc()) {
1686       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1687         assert(VA.getLocVT() == MVT::i32 &&
1688                "unexpected calling convention register assignment");
1689         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1690                "unexpected use of 'returned'");
1691         isThisReturn = true;
1692       }
1693       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1694     } else if (isByVal) {
1695       assert(VA.isMemLoc());
1696       unsigned offset = 0;
1697 
1698       // True if this byval aggregate will be split between registers
1699       // and memory.
1700       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1701       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1702 
1703       if (CurByValIdx < ByValArgsCount) {
1704 
1705         unsigned RegBegin, RegEnd;
1706         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1707 
1708         EVT PtrVT =
1709             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1710         unsigned int i, j;
1711         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1712           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1713           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1714           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1715                                      MachinePointerInfo(),
1716                                      false, false, false,
1717                                      DAG.InferPtrAlignment(AddArg));
1718           MemOpChains.push_back(Load.getValue(1));
1719           RegsToPass.push_back(std::make_pair(j, Load));
1720         }
1721 
1722         // If parameter size outsides register area, "offset" value
1723         // helps us to calculate stack slot for remained part properly.
1724         offset = RegEnd - RegBegin;
1725 
1726         CCInfo.nextInRegsParam();
1727       }
1728 
1729       if (Flags.getByValSize() > 4*offset) {
1730         auto PtrVT = getPointerTy(DAG.getDataLayout());
1731         unsigned LocMemOffset = VA.getLocMemOffset();
1732         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1733         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1734         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1735         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1736         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1737                                            MVT::i32);
1738         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1739                                             MVT::i32);
1740 
1741         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1742         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1743         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1744                                           Ops));
1745       }
1746     } else if (!isSibCall) {
1747       assert(VA.isMemLoc());
1748 
1749       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1750                                              dl, DAG, VA, Flags));
1751     }
1752   }
1753 
1754   if (!MemOpChains.empty())
1755     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1756 
1757   // Build a sequence of copy-to-reg nodes chained together with token chain
1758   // and flag operands which copy the outgoing args into the appropriate regs.
1759   SDValue InFlag;
1760   // Tail call byval lowering might overwrite argument registers so in case of
1761   // tail call optimization the copies to registers are lowered later.
1762   if (!isTailCall)
1763     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1764       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1765                                RegsToPass[i].second, InFlag);
1766       InFlag = Chain.getValue(1);
1767     }
1768 
1769   // For tail calls lower the arguments to the 'real' stack slot.
1770   if (isTailCall) {
1771     // Force all the incoming stack arguments to be loaded from the stack
1772     // before any new outgoing arguments are stored to the stack, because the
1773     // outgoing stack slots may alias the incoming argument stack slots, and
1774     // the alias isn't otherwise explicit. This is slightly more conservative
1775     // than necessary, because it means that each store effectively depends
1776     // on every argument instead of just those arguments it would clobber.
1777 
1778     // Do not flag preceding copytoreg stuff together with the following stuff.
1779     InFlag = SDValue();
1780     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1781       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1782                                RegsToPass[i].second, InFlag);
1783       InFlag = Chain.getValue(1);
1784     }
1785     InFlag = SDValue();
1786   }
1787 
1788   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1789   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1790   // node so that legalize doesn't hack it.
1791   bool isDirect = false;
1792   bool isARMFunc = false;
1793   bool isLocalARMFunc = false;
1794   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1795   auto PtrVt = getPointerTy(DAG.getDataLayout());
1796 
1797   if (Subtarget->genLongCalls()) {
1798     assert((Subtarget->isTargetWindows() ||
1799             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1800            "long-calls with non-static relocation model!");
1801     // Handle a global address or an external symbol. If it's not one of
1802     // those, the target's already in a register, so we don't need to do
1803     // anything extra.
1804     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1805       const GlobalValue *GV = G->getGlobal();
1806       // Create a constant pool entry for the callee address
1807       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1808       ARMConstantPoolValue *CPV =
1809         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1810 
1811       // Get the address of the callee into a register
1812       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1813       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1814       Callee = DAG.getLoad(
1815           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1816           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1817           false, false, 0);
1818     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1819       const char *Sym = S->getSymbol();
1820 
1821       // Create a constant pool entry for the callee address
1822       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1823       ARMConstantPoolValue *CPV =
1824         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1825                                       ARMPCLabelIndex, 0);
1826       // Get the address of the callee into a register
1827       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1828       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1829       Callee = DAG.getLoad(
1830           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1831           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1832           false, false, 0);
1833     }
1834   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1835     const GlobalValue *GV = G->getGlobal();
1836     isDirect = true;
1837     bool isDef = GV->isStrongDefinitionForLinker();
1838     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1839                    getTargetMachine().getRelocationModel() != Reloc::Static;
1840     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1841     // ARM call to a local ARM function is predicable.
1842     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1843     // tBX takes a register source operand.
1844     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1845       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1846       Callee = DAG.getNode(
1847           ARMISD::WrapperPIC, dl, PtrVt,
1848           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1849       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1850                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1851                            false, false, true, 0);
1852     } else if (Subtarget->isTargetCOFF()) {
1853       assert(Subtarget->isTargetWindows() &&
1854              "Windows is the only supported COFF target");
1855       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1856                                  ? ARMII::MO_DLLIMPORT
1857                                  : ARMII::MO_NO_FLAG;
1858       Callee =
1859           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1860       if (GV->hasDLLImportStorageClass())
1861         Callee =
1862             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1863                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1864                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1865                         false, false, false, 0);
1866     } else {
1867       // On ELF targets for PIC code, direct calls should go through the PLT
1868       unsigned OpFlags = 0;
1869       if (Subtarget->isTargetELF() &&
1870           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1871         OpFlags = ARMII::MO_PLT;
1872       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1873     }
1874   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1875     isDirect = true;
1876     bool isStub = Subtarget->isTargetMachO() &&
1877                   getTargetMachine().getRelocationModel() != Reloc::Static;
1878     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1879     // tBX takes a register source operand.
1880     const char *Sym = S->getSymbol();
1881     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1882       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1883       ARMConstantPoolValue *CPV =
1884         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1885                                       ARMPCLabelIndex, 4);
1886       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1887       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1888       Callee = DAG.getLoad(
1889           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1890           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1891           false, false, 0);
1892       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1893       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1894     } else {
1895       unsigned OpFlags = 0;
1896       // On ELF targets for PIC code, direct calls should go through the PLT
1897       if (Subtarget->isTargetELF() &&
1898                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1899         OpFlags = ARMII::MO_PLT;
1900       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1901     }
1902   }
1903 
1904   // FIXME: handle tail calls differently.
1905   unsigned CallOpc;
1906   if (Subtarget->isThumb()) {
1907     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1908       CallOpc = ARMISD::CALL_NOLINK;
1909     else
1910       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1911   } else {
1912     if (!isDirect && !Subtarget->hasV5TOps())
1913       CallOpc = ARMISD::CALL_NOLINK;
1914     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1915              // Emit regular call when code size is the priority
1916              !MF.getFunction()->optForMinSize())
1917       // "mov lr, pc; b _foo" to avoid confusing the RSP
1918       CallOpc = ARMISD::CALL_NOLINK;
1919     else
1920       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1921   }
1922 
1923   std::vector<SDValue> Ops;
1924   Ops.push_back(Chain);
1925   Ops.push_back(Callee);
1926 
1927   // Add argument registers to the end of the list so that they are known live
1928   // into the call.
1929   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1930     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1931                                   RegsToPass[i].second.getValueType()));
1932 
1933   // Add a register mask operand representing the call-preserved registers.
1934   if (!isTailCall) {
1935     const uint32_t *Mask;
1936     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1937     if (isThisReturn) {
1938       // For 'this' returns, use the R0-preserving mask if applicable
1939       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1940       if (!Mask) {
1941         // Set isThisReturn to false if the calling convention is not one that
1942         // allows 'returned' to be modeled in this way, so LowerCallResult does
1943         // not try to pass 'this' straight through
1944         isThisReturn = false;
1945         Mask = ARI->getCallPreservedMask(MF, CallConv);
1946       }
1947     } else
1948       Mask = ARI->getCallPreservedMask(MF, CallConv);
1949 
1950     assert(Mask && "Missing call preserved mask for calling convention");
1951     Ops.push_back(DAG.getRegisterMask(Mask));
1952   }
1953 
1954   if (InFlag.getNode())
1955     Ops.push_back(InFlag);
1956 
1957   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1958   if (isTailCall) {
1959     MF.getFrameInfo()->setHasTailCall();
1960     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1961   }
1962 
1963   // Returns a chain and a flag for retval copy to use.
1964   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1965   InFlag = Chain.getValue(1);
1966 
1967   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1968                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1969   if (!Ins.empty())
1970     InFlag = Chain.getValue(1);
1971 
1972   // Handle result values, copying them out of physregs into vregs that we
1973   // return.
1974   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1975                          InVals, isThisReturn,
1976                          isThisReturn ? OutVals[0] : SDValue());
1977 }
1978 
1979 /// HandleByVal - Every parameter *after* a byval parameter is passed
1980 /// on the stack.  Remember the next parameter register to allocate,
1981 /// and then confiscate the rest of the parameter registers to insure
1982 /// this.
1983 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1984                                     unsigned Align) const {
1985   assert((State->getCallOrPrologue() == Prologue ||
1986           State->getCallOrPrologue() == Call) &&
1987          "unhandled ParmContext");
1988 
1989   // Byval (as with any stack) slots are always at least 4 byte aligned.
1990   Align = std::max(Align, 4U);
1991 
1992   unsigned Reg = State->AllocateReg(GPRArgRegs);
1993   if (!Reg)
1994     return;
1995 
1996   unsigned AlignInRegs = Align / 4;
1997   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1998   for (unsigned i = 0; i < Waste; ++i)
1999     Reg = State->AllocateReg(GPRArgRegs);
2000 
2001   if (!Reg)
2002     return;
2003 
2004   unsigned Excess = 4 * (ARM::R4 - Reg);
2005 
2006   // Special case when NSAA != SP and parameter size greater than size of
2007   // all remained GPR regs. In that case we can't split parameter, we must
2008   // send it to stack. We also must set NCRN to R4, so waste all
2009   // remained registers.
2010   const unsigned NSAAOffset = State->getNextStackOffset();
2011   if (NSAAOffset != 0 && Size > Excess) {
2012     while (State->AllocateReg(GPRArgRegs))
2013       ;
2014     return;
2015   }
2016 
2017   // First register for byval parameter is the first register that wasn't
2018   // allocated before this method call, so it would be "reg".
2019   // If parameter is small enough to be saved in range [reg, r4), then
2020   // the end (first after last) register would be reg + param-size-in-regs,
2021   // else parameter would be splitted between registers and stack,
2022   // end register would be r4 in this case.
2023   unsigned ByValRegBegin = Reg;
2024   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2025   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2026   // Note, first register is allocated in the beginning of function already,
2027   // allocate remained amount of registers we need.
2028   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2029     State->AllocateReg(GPRArgRegs);
2030   // A byval parameter that is split between registers and memory needs its
2031   // size truncated here.
2032   // In the case where the entire structure fits in registers, we set the
2033   // size in memory to zero.
2034   Size = std::max<int>(Size - Excess, 0);
2035 }
2036 
2037 /// MatchingStackOffset - Return true if the given stack call argument is
2038 /// already available in the same position (relatively) of the caller's
2039 /// incoming argument stack.
2040 static
2041 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2042                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2043                          const TargetInstrInfo *TII) {
2044   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2045   int FI = INT_MAX;
2046   if (Arg.getOpcode() == ISD::CopyFromReg) {
2047     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2048     if (!TargetRegisterInfo::isVirtualRegister(VR))
2049       return false;
2050     MachineInstr *Def = MRI->getVRegDef(VR);
2051     if (!Def)
2052       return false;
2053     if (!Flags.isByVal()) {
2054       if (!TII->isLoadFromStackSlot(Def, FI))
2055         return false;
2056     } else {
2057       return false;
2058     }
2059   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2060     if (Flags.isByVal())
2061       // ByVal argument is passed in as a pointer but it's now being
2062       // dereferenced. e.g.
2063       // define @foo(%struct.X* %A) {
2064       //   tail call @bar(%struct.X* byval %A)
2065       // }
2066       return false;
2067     SDValue Ptr = Ld->getBasePtr();
2068     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2069     if (!FINode)
2070       return false;
2071     FI = FINode->getIndex();
2072   } else
2073     return false;
2074 
2075   assert(FI != INT_MAX);
2076   if (!MFI->isFixedObjectIndex(FI))
2077     return false;
2078   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2079 }
2080 
2081 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2082 /// for tail call optimization. Targets which want to do tail call
2083 /// optimization should implement this function.
2084 bool
2085 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2086                                                      CallingConv::ID CalleeCC,
2087                                                      bool isVarArg,
2088                                                      bool isCalleeStructRet,
2089                                                      bool isCallerStructRet,
2090                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2091                                     const SmallVectorImpl<SDValue> &OutVals,
2092                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2093                                                      SelectionDAG& DAG) const {
2094   const Function *CallerF = DAG.getMachineFunction().getFunction();
2095   CallingConv::ID CallerCC = CallerF->getCallingConv();
2096   bool CCMatch = CallerCC == CalleeCC;
2097 
2098   assert(Subtarget->supportsTailCall());
2099 
2100   // Look for obvious safe cases to perform tail call optimization that do not
2101   // require ABI changes. This is what gcc calls sibcall.
2102 
2103   // Do not sibcall optimize vararg calls unless the call site is not passing
2104   // any arguments.
2105   if (isVarArg && !Outs.empty())
2106     return false;
2107 
2108   // Exception-handling functions need a special set of instructions to indicate
2109   // a return to the hardware. Tail-calling another function would probably
2110   // break this.
2111   if (CallerF->hasFnAttribute("interrupt"))
2112     return false;
2113 
2114   // Also avoid sibcall optimization if either caller or callee uses struct
2115   // return semantics.
2116   if (isCalleeStructRet || isCallerStructRet)
2117     return false;
2118 
2119   // Externally-defined functions with weak linkage should not be
2120   // tail-called on ARM when the OS does not support dynamic
2121   // pre-emption of symbols, as the AAELF spec requires normal calls
2122   // to undefined weak functions to be replaced with a NOP or jump to the
2123   // next instruction. The behaviour of branch instructions in this
2124   // situation (as used for tail calls) is implementation-defined, so we
2125   // cannot rely on the linker replacing the tail call with a return.
2126   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2127     const GlobalValue *GV = G->getGlobal();
2128     const Triple &TT = getTargetMachine().getTargetTriple();
2129     if (GV->hasExternalWeakLinkage() &&
2130         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2131       return false;
2132   }
2133 
2134   // If the calling conventions do not match, then we'd better make sure the
2135   // results are returned in the same way as what the caller expects.
2136   if (!CCMatch) {
2137     SmallVector<CCValAssign, 16> RVLocs1;
2138     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2139                        *DAG.getContext(), Call);
2140     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2141 
2142     SmallVector<CCValAssign, 16> RVLocs2;
2143     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2144                        *DAG.getContext(), Call);
2145     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2146 
2147     if (RVLocs1.size() != RVLocs2.size())
2148       return false;
2149     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2150       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2151         return false;
2152       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2153         return false;
2154       if (RVLocs1[i].isRegLoc()) {
2155         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2156           return false;
2157       } else {
2158         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2159           return false;
2160       }
2161     }
2162   }
2163 
2164   // If Caller's vararg or byval argument has been split between registers and
2165   // stack, do not perform tail call, since part of the argument is in caller's
2166   // local frame.
2167   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2168                                       getInfo<ARMFunctionInfo>();
2169   if (AFI_Caller->getArgRegsSaveSize())
2170     return false;
2171 
2172   // If the callee takes no arguments then go on to check the results of the
2173   // call.
2174   if (!Outs.empty()) {
2175     // Check if stack adjustment is needed. For now, do not do this if any
2176     // argument is passed on the stack.
2177     SmallVector<CCValAssign, 16> ArgLocs;
2178     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2179                       *DAG.getContext(), Call);
2180     CCInfo.AnalyzeCallOperands(Outs,
2181                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2182     if (CCInfo.getNextStackOffset()) {
2183       MachineFunction &MF = DAG.getMachineFunction();
2184 
2185       // Check if the arguments are already laid out in the right way as
2186       // the caller's fixed stack objects.
2187       MachineFrameInfo *MFI = MF.getFrameInfo();
2188       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2189       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2190       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2191            i != e;
2192            ++i, ++realArgIdx) {
2193         CCValAssign &VA = ArgLocs[i];
2194         EVT RegVT = VA.getLocVT();
2195         SDValue Arg = OutVals[realArgIdx];
2196         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2197         if (VA.getLocInfo() == CCValAssign::Indirect)
2198           return false;
2199         if (VA.needsCustom()) {
2200           // f64 and vector types are split into multiple registers or
2201           // register/stack-slot combinations.  The types will not match
2202           // the registers; give up on memory f64 refs until we figure
2203           // out what to do about this.
2204           if (!VA.isRegLoc())
2205             return false;
2206           if (!ArgLocs[++i].isRegLoc())
2207             return false;
2208           if (RegVT == MVT::v2f64) {
2209             if (!ArgLocs[++i].isRegLoc())
2210               return false;
2211             if (!ArgLocs[++i].isRegLoc())
2212               return false;
2213           }
2214         } else if (!VA.isRegLoc()) {
2215           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2216                                    MFI, MRI, TII))
2217             return false;
2218         }
2219       }
2220     }
2221   }
2222 
2223   return true;
2224 }
2225 
2226 bool
2227 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2228                                   MachineFunction &MF, bool isVarArg,
2229                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2230                                   LLVMContext &Context) const {
2231   SmallVector<CCValAssign, 16> RVLocs;
2232   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2233   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2234                                                     isVarArg));
2235 }
2236 
2237 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2238                                     SDLoc DL, SelectionDAG &DAG) {
2239   const MachineFunction &MF = DAG.getMachineFunction();
2240   const Function *F = MF.getFunction();
2241 
2242   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2243 
2244   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2245   // version of the "preferred return address". These offsets affect the return
2246   // instruction if this is a return from PL1 without hypervisor extensions.
2247   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2248   //    SWI:     0      "subs pc, lr, #0"
2249   //    ABORT:   +4     "subs pc, lr, #4"
2250   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2251   // UNDEF varies depending on where the exception came from ARM or Thumb
2252   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2253 
2254   int64_t LROffset;
2255   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2256       IntKind == "ABORT")
2257     LROffset = 4;
2258   else if (IntKind == "SWI" || IntKind == "UNDEF")
2259     LROffset = 0;
2260   else
2261     report_fatal_error("Unsupported interrupt attribute. If present, value "
2262                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2263 
2264   RetOps.insert(RetOps.begin() + 1,
2265                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2266 
2267   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2268 }
2269 
2270 SDValue
2271 ARMTargetLowering::LowerReturn(SDValue Chain,
2272                                CallingConv::ID CallConv, bool isVarArg,
2273                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2274                                const SmallVectorImpl<SDValue> &OutVals,
2275                                SDLoc dl, SelectionDAG &DAG) const {
2276 
2277   // CCValAssign - represent the assignment of the return value to a location.
2278   SmallVector<CCValAssign, 16> RVLocs;
2279 
2280   // CCState - Info about the registers and stack slots.
2281   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2282                     *DAG.getContext(), Call);
2283 
2284   // Analyze outgoing return values.
2285   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2286                                                isVarArg));
2287 
2288   SDValue Flag;
2289   SmallVector<SDValue, 4> RetOps;
2290   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2291   bool isLittleEndian = Subtarget->isLittle();
2292 
2293   MachineFunction &MF = DAG.getMachineFunction();
2294   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2295   AFI->setReturnRegsCount(RVLocs.size());
2296 
2297   // Copy the result values into the output registers.
2298   for (unsigned i = 0, realRVLocIdx = 0;
2299        i != RVLocs.size();
2300        ++i, ++realRVLocIdx) {
2301     CCValAssign &VA = RVLocs[i];
2302     assert(VA.isRegLoc() && "Can only return in registers!");
2303 
2304     SDValue Arg = OutVals[realRVLocIdx];
2305 
2306     switch (VA.getLocInfo()) {
2307     default: llvm_unreachable("Unknown loc info!");
2308     case CCValAssign::Full: break;
2309     case CCValAssign::BCvt:
2310       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2311       break;
2312     }
2313 
2314     if (VA.needsCustom()) {
2315       if (VA.getLocVT() == MVT::v2f64) {
2316         // Extract the first half and return it in two registers.
2317         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2318                                    DAG.getConstant(0, dl, MVT::i32));
2319         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2320                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2321 
2322         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2323                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2324                                  Flag);
2325         Flag = Chain.getValue(1);
2326         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2327         VA = RVLocs[++i]; // skip ahead to next loc
2328         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2329                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2330                                  Flag);
2331         Flag = Chain.getValue(1);
2332         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2333         VA = RVLocs[++i]; // skip ahead to next loc
2334 
2335         // Extract the 2nd half and fall through to handle it as an f64 value.
2336         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2337                           DAG.getConstant(1, dl, MVT::i32));
2338       }
2339       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2340       // available.
2341       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2342                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2343       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2344                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2345                                Flag);
2346       Flag = Chain.getValue(1);
2347       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2348       VA = RVLocs[++i]; // skip ahead to next loc
2349       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2350                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2351                                Flag);
2352     } else
2353       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2354 
2355     // Guarantee that all emitted copies are
2356     // stuck together, avoiding something bad.
2357     Flag = Chain.getValue(1);
2358     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2359   }
2360   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2361   const MCPhysReg *I =
2362       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2363   if (I) {
2364     for (; *I; ++I) {
2365       if (ARM::GPRRegClass.contains(*I))
2366         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2367       else if (ARM::DPRRegClass.contains(*I))
2368         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2369       else
2370         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2371     }
2372   }
2373 
2374   // Update chain and glue.
2375   RetOps[0] = Chain;
2376   if (Flag.getNode())
2377     RetOps.push_back(Flag);
2378 
2379   // CPUs which aren't M-class use a special sequence to return from
2380   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2381   // though we use "subs pc, lr, #N").
2382   //
2383   // M-class CPUs actually use a normal return sequence with a special
2384   // (hardware-provided) value in LR, so the normal code path works.
2385   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2386       !Subtarget->isMClass()) {
2387     if (Subtarget->isThumb1Only())
2388       report_fatal_error("interrupt attribute is not supported in Thumb1");
2389     return LowerInterruptReturn(RetOps, dl, DAG);
2390   }
2391 
2392   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2393 }
2394 
2395 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2396   if (N->getNumValues() != 1)
2397     return false;
2398   if (!N->hasNUsesOfValue(1, 0))
2399     return false;
2400 
2401   SDValue TCChain = Chain;
2402   SDNode *Copy = *N->use_begin();
2403   if (Copy->getOpcode() == ISD::CopyToReg) {
2404     // If the copy has a glue operand, we conservatively assume it isn't safe to
2405     // perform a tail call.
2406     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2407       return false;
2408     TCChain = Copy->getOperand(0);
2409   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2410     SDNode *VMov = Copy;
2411     // f64 returned in a pair of GPRs.
2412     SmallPtrSet<SDNode*, 2> Copies;
2413     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2414          UI != UE; ++UI) {
2415       if (UI->getOpcode() != ISD::CopyToReg)
2416         return false;
2417       Copies.insert(*UI);
2418     }
2419     if (Copies.size() > 2)
2420       return false;
2421 
2422     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2423          UI != UE; ++UI) {
2424       SDValue UseChain = UI->getOperand(0);
2425       if (Copies.count(UseChain.getNode()))
2426         // Second CopyToReg
2427         Copy = *UI;
2428       else {
2429         // We are at the top of this chain.
2430         // If the copy has a glue operand, we conservatively assume it
2431         // isn't safe to perform a tail call.
2432         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2433           return false;
2434         // First CopyToReg
2435         TCChain = UseChain;
2436       }
2437     }
2438   } else if (Copy->getOpcode() == ISD::BITCAST) {
2439     // f32 returned in a single GPR.
2440     if (!Copy->hasOneUse())
2441       return false;
2442     Copy = *Copy->use_begin();
2443     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2444       return false;
2445     // If the copy has a glue operand, we conservatively assume it isn't safe to
2446     // perform a tail call.
2447     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2448       return false;
2449     TCChain = Copy->getOperand(0);
2450   } else {
2451     return false;
2452   }
2453 
2454   bool HasRet = false;
2455   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2456        UI != UE; ++UI) {
2457     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2458         UI->getOpcode() != ARMISD::INTRET_FLAG)
2459       return false;
2460     HasRet = true;
2461   }
2462 
2463   if (!HasRet)
2464     return false;
2465 
2466   Chain = TCChain;
2467   return true;
2468 }
2469 
2470 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2471   if (!Subtarget->supportsTailCall())
2472     return false;
2473 
2474   auto Attr =
2475       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2476   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2477     return false;
2478 
2479   return true;
2480 }
2481 
2482 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2483 // and pass the lower and high parts through.
2484 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2485   SDLoc DL(Op);
2486   SDValue WriteValue = Op->getOperand(2);
2487 
2488   // This function is only supposed to be called for i64 type argument.
2489   assert(WriteValue.getValueType() == MVT::i64
2490           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2491 
2492   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2493                            DAG.getConstant(0, DL, MVT::i32));
2494   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2495                            DAG.getConstant(1, DL, MVT::i32));
2496   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2497   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2498 }
2499 
2500 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2501 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2502 // one of the above mentioned nodes. It has to be wrapped because otherwise
2503 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2504 // be used to form addressing mode. These wrapped nodes will be selected
2505 // into MOVi.
2506 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2507   EVT PtrVT = Op.getValueType();
2508   // FIXME there is no actual debug info here
2509   SDLoc dl(Op);
2510   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2511   SDValue Res;
2512   if (CP->isMachineConstantPoolEntry())
2513     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2514                                     CP->getAlignment());
2515   else
2516     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2517                                     CP->getAlignment());
2518   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2519 }
2520 
2521 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2522   return MachineJumpTableInfo::EK_Inline;
2523 }
2524 
2525 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2526                                              SelectionDAG &DAG) const {
2527   MachineFunction &MF = DAG.getMachineFunction();
2528   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2529   unsigned ARMPCLabelIndex = 0;
2530   SDLoc DL(Op);
2531   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2532   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2533   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2534   SDValue CPAddr;
2535   if (RelocM == Reloc::Static) {
2536     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2537   } else {
2538     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2539     ARMPCLabelIndex = AFI->createPICLabelUId();
2540     ARMConstantPoolValue *CPV =
2541       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2542                                       ARMCP::CPBlockAddress, PCAdj);
2543     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2544   }
2545   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2546   SDValue Result =
2547       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2548                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2549                   false, false, false, 0);
2550   if (RelocM == Reloc::Static)
2551     return Result;
2552   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2553   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2554 }
2555 
2556 /// \brief Convert a TLS address reference into the correct sequence of loads
2557 /// and calls to compute the variable's address for Darwin, and return an
2558 /// SDValue containing the final node.
2559 
2560 /// Darwin only has one TLS scheme which must be capable of dealing with the
2561 /// fully general situation, in the worst case. This means:
2562 ///     + "extern __thread" declaration.
2563 ///     + Defined in a possibly unknown dynamic library.
2564 ///
2565 /// The general system is that each __thread variable has a [3 x i32] descriptor
2566 /// which contains information used by the runtime to calculate the address. The
2567 /// only part of this the compiler needs to know about is the first word, which
2568 /// contains a function pointer that must be called with the address of the
2569 /// entire descriptor in "r0".
2570 ///
2571 /// Since this descriptor may be in a different unit, in general access must
2572 /// proceed along the usual ARM rules. A common sequence to produce is:
2573 ///
2574 ///     movw rT1, :lower16:_var$non_lazy_ptr
2575 ///     movt rT1, :upper16:_var$non_lazy_ptr
2576 ///     ldr r0, [rT1]
2577 ///     ldr rT2, [r0]
2578 ///     blx rT2
2579 ///     [...address now in r0...]
2580 SDValue
2581 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2582                                                SelectionDAG &DAG) const {
2583   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2584   SDLoc DL(Op);
2585 
2586   // First step is to get the address of the actua global symbol. This is where
2587   // the TLS descriptor lives.
2588   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2589 
2590   // The first entry in the descriptor is a function pointer that we must call
2591   // to obtain the address of the variable.
2592   SDValue Chain = DAG.getEntryNode();
2593   SDValue FuncTLVGet =
2594       DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2595                   MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2596                   false, true, true, 4);
2597   Chain = FuncTLVGet.getValue(1);
2598 
2599   MachineFunction &F = DAG.getMachineFunction();
2600   MachineFrameInfo *MFI = F.getFrameInfo();
2601   MFI->setAdjustsStack(true);
2602 
2603   // TLS calls preserve all registers except those that absolutely must be
2604   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2605   // silly).
2606   auto TRI =
2607       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2608   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2609   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2610 
2611   // Finally, we can make the call. This is just a degenerate version of a
2612   // normal AArch64 call node: r0 takes the address of the descriptor, and
2613   // returns the address of the variable in this thread.
2614   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2615   Chain =
2616       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2617                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2618                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2619   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2620 }
2621 
2622 SDValue
2623 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2624                                                 SelectionDAG &DAG) const {
2625   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
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                          false, false, false, 0);
2650 
2651   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2652   // offset into the TLSArray.
2653 
2654   // Load the TLS index from the C runtime
2655   SDValue TLSIndex =
2656       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2657   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2658   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo(),
2659                          false, false, false, 0);
2660 
2661   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2662                               DAG.getConstant(2, DL, MVT::i32));
2663   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2664                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2665                             MachinePointerInfo(), false, false, false, 0);
2666 
2667   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS,
2668                      LowerGlobalAddressWindows(Op, DAG));
2669 }
2670 
2671 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2672 SDValue
2673 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2674                                                  SelectionDAG &DAG) const {
2675   SDLoc dl(GA);
2676   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2677   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2678   MachineFunction &MF = DAG.getMachineFunction();
2679   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2680   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2681   ARMConstantPoolValue *CPV =
2682     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2683                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2684   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2685   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2686   Argument =
2687       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2688                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2689                   false, false, false, 0);
2690   SDValue Chain = Argument.getValue(1);
2691 
2692   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2693   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2694 
2695   // call __tls_get_addr.
2696   ArgListTy Args;
2697   ArgListEntry Entry;
2698   Entry.Node = Argument;
2699   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2700   Args.push_back(Entry);
2701 
2702   // FIXME: is there useful debug info available here?
2703   TargetLowering::CallLoweringInfo CLI(DAG);
2704   CLI.setDebugLoc(dl).setChain(Chain)
2705     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2706                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2707                0);
2708 
2709   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2710   return CallResult.first;
2711 }
2712 
2713 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2714 // "local exec" model.
2715 SDValue
2716 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2717                                         SelectionDAG &DAG,
2718                                         TLSModel::Model model) const {
2719   const GlobalValue *GV = GA->getGlobal();
2720   SDLoc dl(GA);
2721   SDValue Offset;
2722   SDValue Chain = DAG.getEntryNode();
2723   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2724   // Get the Thread Pointer
2725   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2726 
2727   if (model == TLSModel::InitialExec) {
2728     MachineFunction &MF = DAG.getMachineFunction();
2729     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2730     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2731     // Initial exec model.
2732     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2733     ARMConstantPoolValue *CPV =
2734       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2735                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2736                                       true);
2737     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2738     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2739     Offset = DAG.getLoad(
2740         PtrVT, dl, Chain, Offset,
2741         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2742         false, false, 0);
2743     Chain = Offset.getValue(1);
2744 
2745     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2746     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2747 
2748     Offset = DAG.getLoad(
2749         PtrVT, dl, Chain, Offset,
2750         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2751         false, false, 0);
2752   } else {
2753     // local exec model
2754     assert(model == TLSModel::LocalExec);
2755     ARMConstantPoolValue *CPV =
2756       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2757     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2758     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2759     Offset = DAG.getLoad(
2760         PtrVT, dl, Chain, Offset,
2761         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2762         false, false, 0);
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   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2803     bool UseGOT_PREL =
2804         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
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()), false,
2821         false, false, 0);
2822     SDValue Chain = Result.getValue(1);
2823     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2824     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2825     if (UseGOT_PREL)
2826       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2827                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2828                            false, false, false, 0);
2829     return Result;
2830   }
2831 
2832   // If we have T2 ops, we can materialize the address directly via movt/movw
2833   // pair. This is always cheaper.
2834   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2835     ++NumMovwMovt;
2836     // FIXME: Once remat is capable of dealing with instructions with register
2837     // operands, expand this into two nodes.
2838     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2839                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2840   } else {
2841     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2842     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2843     return DAG.getLoad(
2844         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2845         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2846         false, false, 0);
2847   }
2848 }
2849 
2850 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2851                                                     SelectionDAG &DAG) const {
2852   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2853   SDLoc dl(Op);
2854   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2855   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2856 
2857   if (Subtarget->useMovt(DAG.getMachineFunction()))
2858     ++NumMovwMovt;
2859 
2860   // FIXME: Once remat is capable of dealing with instructions with register
2861   // operands, expand this into multiple nodes
2862   unsigned Wrapper =
2863       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2864 
2865   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2866   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2867 
2868   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2869     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2870                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2871                          false, false, false, 0);
2872   return Result;
2873 }
2874 
2875 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2876                                                      SelectionDAG &DAG) const {
2877   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2878   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2879          "Windows on ARM expects to use movw/movt");
2880 
2881   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2882   const ARMII::TOF TargetFlags =
2883     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2884   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2885   SDValue Result;
2886   SDLoc DL(Op);
2887 
2888   ++NumMovwMovt;
2889 
2890   // FIXME: Once remat is capable of dealing with instructions with register
2891   // operands, expand this into two nodes.
2892   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2893                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2894                                                   TargetFlags));
2895   if (GV->hasDLLImportStorageClass())
2896     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2897                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2898                          false, false, false, 0);
2899   return Result;
2900 }
2901 
2902 SDValue
2903 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2904   SDLoc dl(Op);
2905   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2906   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2907                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2908                      Op.getOperand(1), Val);
2909 }
2910 
2911 SDValue
2912 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2913   SDLoc dl(Op);
2914   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2915                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2916 }
2917 
2918 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2919                                                       SelectionDAG &DAG) const {
2920   SDLoc dl(Op);
2921   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2922                      Op.getOperand(0));
2923 }
2924 
2925 SDValue
2926 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2927                                           const ARMSubtarget *Subtarget) const {
2928   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2929   SDLoc dl(Op);
2930   switch (IntNo) {
2931   default: return SDValue();    // Don't custom lower most intrinsics.
2932   case Intrinsic::arm_rbit: {
2933     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2934            "RBIT intrinsic must have i32 type!");
2935     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2936   }
2937   case Intrinsic::arm_thread_pointer: {
2938     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2939     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2940   }
2941   case Intrinsic::eh_sjlj_lsda: {
2942     MachineFunction &MF = DAG.getMachineFunction();
2943     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2944     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2945     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2946     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2947     SDValue CPAddr;
2948     unsigned PCAdj = (RelocM != Reloc::PIC_)
2949       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2950     ARMConstantPoolValue *CPV =
2951       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2952                                       ARMCP::CPLSDA, PCAdj);
2953     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2954     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2955     SDValue Result = DAG.getLoad(
2956         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2957         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2958         false, false, 0);
2959 
2960     if (RelocM == Reloc::PIC_) {
2961       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2962       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2963     }
2964     return Result;
2965   }
2966   case Intrinsic::arm_neon_vmulls:
2967   case Intrinsic::arm_neon_vmullu: {
2968     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2969       ? ARMISD::VMULLs : ARMISD::VMULLu;
2970     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2971                        Op.getOperand(1), Op.getOperand(2));
2972   }
2973   case Intrinsic::arm_neon_vminnm:
2974   case Intrinsic::arm_neon_vmaxnm: {
2975     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2976       ? ISD::FMINNUM : ISD::FMAXNUM;
2977     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2978                        Op.getOperand(1), Op.getOperand(2));
2979   }
2980   case Intrinsic::arm_neon_vminu:
2981   case Intrinsic::arm_neon_vmaxu: {
2982     if (Op.getValueType().isFloatingPoint())
2983       return SDValue();
2984     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2985       ? ISD::UMIN : ISD::UMAX;
2986     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2987                          Op.getOperand(1), Op.getOperand(2));
2988   }
2989   case Intrinsic::arm_neon_vmins:
2990   case Intrinsic::arm_neon_vmaxs: {
2991     // v{min,max}s is overloaded between signed integers and floats.
2992     if (!Op.getValueType().isFloatingPoint()) {
2993       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2994         ? ISD::SMIN : ISD::SMAX;
2995       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2996                          Op.getOperand(1), Op.getOperand(2));
2997     }
2998     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2999       ? ISD::FMINNAN : ISD::FMAXNAN;
3000     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3001                        Op.getOperand(1), Op.getOperand(2));
3002   }
3003   }
3004 }
3005 
3006 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3007                                  const ARMSubtarget *Subtarget) {
3008   // FIXME: handle "fence singlethread" more efficiently.
3009   SDLoc dl(Op);
3010   if (!Subtarget->hasDataBarrier()) {
3011     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3012     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3013     // here.
3014     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3015            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3016     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3017                        DAG.getConstant(0, dl, MVT::i32));
3018   }
3019 
3020   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3021   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3022   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3023   if (Subtarget->isMClass()) {
3024     // Only a full system barrier exists in the M-class architectures.
3025     Domain = ARM_MB::SY;
3026   } else if (Subtarget->isSwift() && Ord == Release) {
3027     // Swift happens to implement ISHST barriers in a way that's compatible with
3028     // Release semantics but weaker than ISH so we'd be fools not to use
3029     // it. Beware: other processors probably don't!
3030     Domain = ARM_MB::ISHST;
3031   }
3032 
3033   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3034                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3035                      DAG.getConstant(Domain, dl, MVT::i32));
3036 }
3037 
3038 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3039                              const ARMSubtarget *Subtarget) {
3040   // ARM pre v5TE and Thumb1 does not have preload instructions.
3041   if (!(Subtarget->isThumb2() ||
3042         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3043     // Just preserve the chain.
3044     return Op.getOperand(0);
3045 
3046   SDLoc dl(Op);
3047   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3048   if (!isRead &&
3049       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3050     // ARMv7 with MP extension has PLDW.
3051     return Op.getOperand(0);
3052 
3053   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3054   if (Subtarget->isThumb()) {
3055     // Invert the bits.
3056     isRead = ~isRead & 1;
3057     isData = ~isData & 1;
3058   }
3059 
3060   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3061                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3062                      DAG.getConstant(isData, dl, MVT::i32));
3063 }
3064 
3065 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3066   MachineFunction &MF = DAG.getMachineFunction();
3067   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3068 
3069   // vastart just stores the address of the VarArgsFrameIndex slot into the
3070   // memory location argument.
3071   SDLoc dl(Op);
3072   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3073   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3074   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3075   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3076                       MachinePointerInfo(SV), false, false, 0);
3077 }
3078 
3079 SDValue
3080 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
3081                                         SDValue &Root, SelectionDAG &DAG,
3082                                         SDLoc dl) const {
3083   MachineFunction &MF = DAG.getMachineFunction();
3084   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3085 
3086   const TargetRegisterClass *RC;
3087   if (AFI->isThumb1OnlyFunction())
3088     RC = &ARM::tGPRRegClass;
3089   else
3090     RC = &ARM::GPRRegClass;
3091 
3092   // Transform the arguments stored in physical registers into virtual ones.
3093   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3094   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3095 
3096   SDValue ArgValue2;
3097   if (NextVA.isMemLoc()) {
3098     MachineFrameInfo *MFI = MF.getFrameInfo();
3099     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3100 
3101     // Create load node to retrieve arguments from the stack.
3102     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3103     ArgValue2 = DAG.getLoad(
3104         MVT::i32, dl, Root, FIN,
3105         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3106         false, false, 0);
3107   } else {
3108     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3109     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3110   }
3111   if (!Subtarget->isLittle())
3112     std::swap (ArgValue, ArgValue2);
3113   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3114 }
3115 
3116 // The remaining GPRs hold either the beginning of variable-argument
3117 // data, or the beginning of an aggregate passed by value (usually
3118 // byval).  Either way, we allocate stack slots adjacent to the data
3119 // provided by our caller, and store the unallocated registers there.
3120 // If this is a variadic function, the va_list pointer will begin with
3121 // these values; otherwise, this reassembles a (byval) structure that
3122 // was split between registers and memory.
3123 // Return: The frame index registers were stored into.
3124 int
3125 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3126                                   SDLoc dl, SDValue &Chain,
3127                                   const Value *OrigArg,
3128                                   unsigned InRegsParamRecordIdx,
3129                                   int ArgOffset,
3130                                   unsigned ArgSize) const {
3131   // Currently, two use-cases possible:
3132   // Case #1. Non-var-args function, and we meet first byval parameter.
3133   //          Setup first unallocated register as first byval register;
3134   //          eat all remained registers
3135   //          (these two actions are performed by HandleByVal method).
3136   //          Then, here, we initialize stack frame with
3137   //          "store-reg" instructions.
3138   // Case #2. Var-args function, that doesn't contain byval parameters.
3139   //          The same: eat all remained unallocated registers,
3140   //          initialize stack frame.
3141 
3142   MachineFunction &MF = DAG.getMachineFunction();
3143   MachineFrameInfo *MFI = MF.getFrameInfo();
3144   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3145   unsigned RBegin, REnd;
3146   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3147     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3148   } else {
3149     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3150     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3151     REnd = ARM::R4;
3152   }
3153 
3154   if (REnd != RBegin)
3155     ArgOffset = -4 * (ARM::R4 - RBegin);
3156 
3157   auto PtrVT = getPointerTy(DAG.getDataLayout());
3158   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3159   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3160 
3161   SmallVector<SDValue, 4> MemOps;
3162   const TargetRegisterClass *RC =
3163       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3164 
3165   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3166     unsigned VReg = MF.addLiveIn(Reg, RC);
3167     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3168     SDValue Store =
3169         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3170                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3171     MemOps.push_back(Store);
3172     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3173   }
3174 
3175   if (!MemOps.empty())
3176     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3177   return FrameIndex;
3178 }
3179 
3180 // Setup stack frame, the va_list pointer will start from.
3181 void
3182 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3183                                         SDLoc dl, SDValue &Chain,
3184                                         unsigned ArgOffset,
3185                                         unsigned TotalArgRegsSaveSize,
3186                                         bool ForceMutable) const {
3187   MachineFunction &MF = DAG.getMachineFunction();
3188   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3189 
3190   // Try to store any remaining integer argument regs
3191   // to their spots on the stack so that they may be loaded by deferencing
3192   // the result of va_next.
3193   // If there is no regs to be stored, just point address after last
3194   // argument passed via stack.
3195   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3196                                   CCInfo.getInRegsParamsCount(),
3197                                   CCInfo.getNextStackOffset(), 4);
3198   AFI->setVarArgsFrameIndex(FrameIndex);
3199 }
3200 
3201 SDValue
3202 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3203                                         CallingConv::ID CallConv, bool isVarArg,
3204                                         const SmallVectorImpl<ISD::InputArg>
3205                                           &Ins,
3206                                         SDLoc dl, SelectionDAG &DAG,
3207                                         SmallVectorImpl<SDValue> &InVals)
3208                                           const {
3209   MachineFunction &MF = DAG.getMachineFunction();
3210   MachineFrameInfo *MFI = MF.getFrameInfo();
3211 
3212   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3213 
3214   // Assign locations to all of the incoming arguments.
3215   SmallVector<CCValAssign, 16> ArgLocs;
3216   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3217                     *DAG.getContext(), Prologue);
3218   CCInfo.AnalyzeFormalArguments(Ins,
3219                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3220                                                   isVarArg));
3221 
3222   SmallVector<SDValue, 16> ArgValues;
3223   SDValue ArgValue;
3224   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3225   unsigned CurArgIdx = 0;
3226 
3227   // Initially ArgRegsSaveSize is zero.
3228   // Then we increase this value each time we meet byval parameter.
3229   // We also increase this value in case of varargs function.
3230   AFI->setArgRegsSaveSize(0);
3231 
3232   // Calculate the amount of stack space that we need to allocate to store
3233   // byval and variadic arguments that are passed in registers.
3234   // We need to know this before we allocate the first byval or variadic
3235   // argument, as they will be allocated a stack slot below the CFA (Canonical
3236   // Frame Address, the stack pointer at entry to the function).
3237   unsigned ArgRegBegin = ARM::R4;
3238   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3239     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3240       break;
3241 
3242     CCValAssign &VA = ArgLocs[i];
3243     unsigned Index = VA.getValNo();
3244     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3245     if (!Flags.isByVal())
3246       continue;
3247 
3248     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3249     unsigned RBegin, REnd;
3250     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3251     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3252 
3253     CCInfo.nextInRegsParam();
3254   }
3255   CCInfo.rewindByValRegsInfo();
3256 
3257   int lastInsIndex = -1;
3258   if (isVarArg && MFI->hasVAStart()) {
3259     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3260     if (RegIdx != array_lengthof(GPRArgRegs))
3261       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3262   }
3263 
3264   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3265   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3266   auto PtrVT = getPointerTy(DAG.getDataLayout());
3267 
3268   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3269     CCValAssign &VA = ArgLocs[i];
3270     if (Ins[VA.getValNo()].isOrigArg()) {
3271       std::advance(CurOrigArg,
3272                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3273       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3274     }
3275     // Arguments stored in registers.
3276     if (VA.isRegLoc()) {
3277       EVT RegVT = VA.getLocVT();
3278 
3279       if (VA.needsCustom()) {
3280         // f64 and vector types are split up into multiple registers or
3281         // combinations of registers and stack slots.
3282         if (VA.getLocVT() == MVT::v2f64) {
3283           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3284                                                    Chain, DAG, dl);
3285           VA = ArgLocs[++i]; // skip ahead to next loc
3286           SDValue ArgValue2;
3287           if (VA.isMemLoc()) {
3288             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3289             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3290             ArgValue2 = DAG.getLoad(
3291                 MVT::f64, dl, Chain, FIN,
3292                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3293                 false, false, false, 0);
3294           } else {
3295             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3296                                              Chain, DAG, dl);
3297           }
3298           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3299           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3300                                  ArgValue, ArgValue1,
3301                                  DAG.getIntPtrConstant(0, dl));
3302           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3303                                  ArgValue, ArgValue2,
3304                                  DAG.getIntPtrConstant(1, dl));
3305         } else
3306           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3307 
3308       } else {
3309         const TargetRegisterClass *RC;
3310 
3311         if (RegVT == MVT::f32)
3312           RC = &ARM::SPRRegClass;
3313         else if (RegVT == MVT::f64)
3314           RC = &ARM::DPRRegClass;
3315         else if (RegVT == MVT::v2f64)
3316           RC = &ARM::QPRRegClass;
3317         else if (RegVT == MVT::i32)
3318           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3319                                            : &ARM::GPRRegClass;
3320         else
3321           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3322 
3323         // Transform the arguments in physical registers into virtual ones.
3324         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3325         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3326       }
3327 
3328       // If this is an 8 or 16-bit value, it is really passed promoted
3329       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3330       // truncate to the right size.
3331       switch (VA.getLocInfo()) {
3332       default: llvm_unreachable("Unknown loc info!");
3333       case CCValAssign::Full: break;
3334       case CCValAssign::BCvt:
3335         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3336         break;
3337       case CCValAssign::SExt:
3338         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3339                                DAG.getValueType(VA.getValVT()));
3340         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3341         break;
3342       case CCValAssign::ZExt:
3343         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3344                                DAG.getValueType(VA.getValVT()));
3345         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3346         break;
3347       }
3348 
3349       InVals.push_back(ArgValue);
3350 
3351     } else { // VA.isRegLoc()
3352 
3353       // sanity check
3354       assert(VA.isMemLoc());
3355       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3356 
3357       int index = VA.getValNo();
3358 
3359       // Some Ins[] entries become multiple ArgLoc[] entries.
3360       // Process them only once.
3361       if (index != lastInsIndex)
3362         {
3363           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3364           // FIXME: For now, all byval parameter objects are marked mutable.
3365           // This can be changed with more analysis.
3366           // In case of tail call optimization mark all arguments mutable.
3367           // Since they could be overwritten by lowering of arguments in case of
3368           // a tail call.
3369           if (Flags.isByVal()) {
3370             assert(Ins[index].isOrigArg() &&
3371                    "Byval arguments cannot be implicit");
3372             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3373 
3374             int FrameIndex = StoreByValRegs(
3375                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3376                 VA.getLocMemOffset(), Flags.getByValSize());
3377             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3378             CCInfo.nextInRegsParam();
3379           } else {
3380             unsigned FIOffset = VA.getLocMemOffset();
3381             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3382                                             FIOffset, true);
3383 
3384             // Create load nodes to retrieve arguments from the stack.
3385             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3386             InVals.push_back(DAG.getLoad(
3387                 VA.getValVT(), dl, Chain, FIN,
3388                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3389                 false, false, false, 0));
3390           }
3391           lastInsIndex = index;
3392         }
3393     }
3394   }
3395 
3396   // varargs
3397   if (isVarArg && MFI->hasVAStart())
3398     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3399                          CCInfo.getNextStackOffset(),
3400                          TotalArgRegsSaveSize);
3401 
3402   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3403 
3404   return Chain;
3405 }
3406 
3407 /// isFloatingPointZero - Return true if this is +0.0.
3408 static bool isFloatingPointZero(SDValue Op) {
3409   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3410     return CFP->getValueAPF().isPosZero();
3411   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3412     // Maybe this has already been legalized into the constant pool?
3413     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3414       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3415       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3416         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3417           return CFP->getValueAPF().isPosZero();
3418     }
3419   } else if (Op->getOpcode() == ISD::BITCAST &&
3420              Op->getValueType(0) == MVT::f64) {
3421     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3422     // created by LowerConstantFP().
3423     SDValue BitcastOp = Op->getOperand(0);
3424     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3425         isNullConstant(BitcastOp->getOperand(0)))
3426       return true;
3427   }
3428   return false;
3429 }
3430 
3431 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3432 /// the given operands.
3433 SDValue
3434 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3435                              SDValue &ARMcc, SelectionDAG &DAG,
3436                              SDLoc dl) const {
3437   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3438     unsigned C = RHSC->getZExtValue();
3439     if (!isLegalICmpImmediate(C)) {
3440       // Constant does not fit, try adjusting it by one?
3441       switch (CC) {
3442       default: break;
3443       case ISD::SETLT:
3444       case ISD::SETGE:
3445         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3446           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3447           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3448         }
3449         break;
3450       case ISD::SETULT:
3451       case ISD::SETUGE:
3452         if (C != 0 && isLegalICmpImmediate(C-1)) {
3453           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3454           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3455         }
3456         break;
3457       case ISD::SETLE:
3458       case ISD::SETGT:
3459         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3460           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3461           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3462         }
3463         break;
3464       case ISD::SETULE:
3465       case ISD::SETUGT:
3466         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3467           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3468           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3469         }
3470         break;
3471       }
3472     }
3473   }
3474 
3475   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3476   ARMISD::NodeType CompareType;
3477   switch (CondCode) {
3478   default:
3479     CompareType = ARMISD::CMP;
3480     break;
3481   case ARMCC::EQ:
3482   case ARMCC::NE:
3483     // Uses only Z Flag
3484     CompareType = ARMISD::CMPZ;
3485     break;
3486   }
3487   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3488   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3489 }
3490 
3491 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3492 SDValue
3493 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3494                              SDLoc dl) const {
3495   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3496   SDValue Cmp;
3497   if (!isFloatingPointZero(RHS))
3498     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3499   else
3500     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3501   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3502 }
3503 
3504 /// duplicateCmp - Glue values can have only one use, so this function
3505 /// duplicates a comparison node.
3506 SDValue
3507 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3508   unsigned Opc = Cmp.getOpcode();
3509   SDLoc DL(Cmp);
3510   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3511     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3512 
3513   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3514   Cmp = Cmp.getOperand(0);
3515   Opc = Cmp.getOpcode();
3516   if (Opc == ARMISD::CMPFP)
3517     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3518   else {
3519     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3520     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3521   }
3522   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3523 }
3524 
3525 std::pair<SDValue, SDValue>
3526 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3527                                  SDValue &ARMcc) const {
3528   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3529 
3530   SDValue Value, OverflowCmp;
3531   SDValue LHS = Op.getOperand(0);
3532   SDValue RHS = Op.getOperand(1);
3533   SDLoc dl(Op);
3534 
3535   // FIXME: We are currently always generating CMPs because we don't support
3536   // generating CMN through the backend. This is not as good as the natural
3537   // CMP case because it causes a register dependency and cannot be folded
3538   // later.
3539 
3540   switch (Op.getOpcode()) {
3541   default:
3542     llvm_unreachable("Unknown overflow instruction!");
3543   case ISD::SADDO:
3544     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3545     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3546     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3547     break;
3548   case ISD::UADDO:
3549     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3550     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3551     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3552     break;
3553   case ISD::SSUBO:
3554     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3555     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3556     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3557     break;
3558   case ISD::USUBO:
3559     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3560     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3561     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3562     break;
3563   } // switch (...)
3564 
3565   return std::make_pair(Value, OverflowCmp);
3566 }
3567 
3568 
3569 SDValue
3570 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3571   // Let legalize expand this if it isn't a legal type yet.
3572   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3573     return SDValue();
3574 
3575   SDValue Value, OverflowCmp;
3576   SDValue ARMcc;
3577   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3578   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3579   SDLoc dl(Op);
3580   // We use 0 and 1 as false and true values.
3581   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3582   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3583   EVT VT = Op.getValueType();
3584 
3585   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3586                                  ARMcc, CCR, OverflowCmp);
3587 
3588   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3589   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3590 }
3591 
3592 
3593 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3594   SDValue Cond = Op.getOperand(0);
3595   SDValue SelectTrue = Op.getOperand(1);
3596   SDValue SelectFalse = Op.getOperand(2);
3597   SDLoc dl(Op);
3598   unsigned Opc = Cond.getOpcode();
3599 
3600   if (Cond.getResNo() == 1 &&
3601       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3602        Opc == ISD::USUBO)) {
3603     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3604       return SDValue();
3605 
3606     SDValue Value, OverflowCmp;
3607     SDValue ARMcc;
3608     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3609     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3610     EVT VT = Op.getValueType();
3611 
3612     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3613                    OverflowCmp, DAG);
3614   }
3615 
3616   // Convert:
3617   //
3618   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3619   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3620   //
3621   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3622     const ConstantSDNode *CMOVTrue =
3623       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3624     const ConstantSDNode *CMOVFalse =
3625       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3626 
3627     if (CMOVTrue && CMOVFalse) {
3628       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3629       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3630 
3631       SDValue True;
3632       SDValue False;
3633       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3634         True = SelectTrue;
3635         False = SelectFalse;
3636       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3637         True = SelectFalse;
3638         False = SelectTrue;
3639       }
3640 
3641       if (True.getNode() && False.getNode()) {
3642         EVT VT = Op.getValueType();
3643         SDValue ARMcc = Cond.getOperand(2);
3644         SDValue CCR = Cond.getOperand(3);
3645         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3646         assert(True.getValueType() == VT);
3647         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3648       }
3649     }
3650   }
3651 
3652   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3653   // undefined bits before doing a full-word comparison with zero.
3654   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3655                      DAG.getConstant(1, dl, Cond.getValueType()));
3656 
3657   return DAG.getSelectCC(dl, Cond,
3658                          DAG.getConstant(0, dl, Cond.getValueType()),
3659                          SelectTrue, SelectFalse, ISD::SETNE);
3660 }
3661 
3662 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3663                                  bool &swpCmpOps, bool &swpVselOps) {
3664   // Start by selecting the GE condition code for opcodes that return true for
3665   // 'equality'
3666   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3667       CC == ISD::SETULE)
3668     CondCode = ARMCC::GE;
3669 
3670   // and GT for opcodes that return false for 'equality'.
3671   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3672            CC == ISD::SETULT)
3673     CondCode = ARMCC::GT;
3674 
3675   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3676   // to swap the compare operands.
3677   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3678       CC == ISD::SETULT)
3679     swpCmpOps = true;
3680 
3681   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3682   // If we have an unordered opcode, we need to swap the operands to the VSEL
3683   // instruction (effectively negating the condition).
3684   //
3685   // This also has the effect of swapping which one of 'less' or 'greater'
3686   // returns true, so we also swap the compare operands. It also switches
3687   // whether we return true for 'equality', so we compensate by picking the
3688   // opposite condition code to our original choice.
3689   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3690       CC == ISD::SETUGT) {
3691     swpCmpOps = !swpCmpOps;
3692     swpVselOps = !swpVselOps;
3693     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3694   }
3695 
3696   // 'ordered' is 'anything but unordered', so use the VS condition code and
3697   // swap the VSEL operands.
3698   if (CC == ISD::SETO) {
3699     CondCode = ARMCC::VS;
3700     swpVselOps = true;
3701   }
3702 
3703   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3704   // code and swap the VSEL operands.
3705   if (CC == ISD::SETUNE) {
3706     CondCode = ARMCC::EQ;
3707     swpVselOps = true;
3708   }
3709 }
3710 
3711 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3712                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3713                                    SDValue Cmp, SelectionDAG &DAG) const {
3714   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3715     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3716                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3717     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3718                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3719 
3720     SDValue TrueLow = TrueVal.getValue(0);
3721     SDValue TrueHigh = TrueVal.getValue(1);
3722     SDValue FalseLow = FalseVal.getValue(0);
3723     SDValue FalseHigh = FalseVal.getValue(1);
3724 
3725     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3726                               ARMcc, CCR, Cmp);
3727     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3728                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3729 
3730     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3731   } else {
3732     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3733                        Cmp);
3734   }
3735 }
3736 
3737 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3738   EVT VT = Op.getValueType();
3739   SDValue LHS = Op.getOperand(0);
3740   SDValue RHS = Op.getOperand(1);
3741   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3742   SDValue TrueVal = Op.getOperand(2);
3743   SDValue FalseVal = Op.getOperand(3);
3744   SDLoc dl(Op);
3745 
3746   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3747     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3748                                                     dl);
3749 
3750     // If softenSetCCOperands only returned one value, we should compare it to
3751     // zero.
3752     if (!RHS.getNode()) {
3753       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3754       CC = ISD::SETNE;
3755     }
3756   }
3757 
3758   if (LHS.getValueType() == MVT::i32) {
3759     // Try to generate VSEL on ARMv8.
3760     // The VSEL instruction can't use all the usual ARM condition
3761     // codes: it only has two bits to select the condition code, so it's
3762     // constrained to use only GE, GT, VS and EQ.
3763     //
3764     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3765     // swap the operands of the previous compare instruction (effectively
3766     // inverting the compare condition, swapping 'less' and 'greater') and
3767     // sometimes need to swap the operands to the VSEL (which inverts the
3768     // condition in the sense of firing whenever the previous condition didn't)
3769     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3770                                     TrueVal.getValueType() == MVT::f64)) {
3771       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3772       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3773           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3774         CC = ISD::getSetCCInverse(CC, true);
3775         std::swap(TrueVal, FalseVal);
3776       }
3777     }
3778 
3779     SDValue ARMcc;
3780     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3781     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3782     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3783   }
3784 
3785   ARMCC::CondCodes CondCode, CondCode2;
3786   FPCCToARMCC(CC, CondCode, CondCode2);
3787 
3788   // Try to generate VMAXNM/VMINNM on ARMv8.
3789   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3790                                   TrueVal.getValueType() == MVT::f64)) {
3791     bool swpCmpOps = false;
3792     bool swpVselOps = false;
3793     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3794 
3795     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3796         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3797       if (swpCmpOps)
3798         std::swap(LHS, RHS);
3799       if (swpVselOps)
3800         std::swap(TrueVal, FalseVal);
3801     }
3802   }
3803 
3804   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3805   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3806   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3807   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3808   if (CondCode2 != ARMCC::AL) {
3809     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3810     // FIXME: Needs another CMP because flag can have but one use.
3811     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3812     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3813   }
3814   return Result;
3815 }
3816 
3817 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3818 /// to morph to an integer compare sequence.
3819 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3820                            const ARMSubtarget *Subtarget) {
3821   SDNode *N = Op.getNode();
3822   if (!N->hasOneUse())
3823     // Otherwise it requires moving the value from fp to integer registers.
3824     return false;
3825   if (!N->getNumValues())
3826     return false;
3827   EVT VT = Op.getValueType();
3828   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3829     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3830     // vmrs are very slow, e.g. cortex-a8.
3831     return false;
3832 
3833   if (isFloatingPointZero(Op)) {
3834     SeenZero = true;
3835     return true;
3836   }
3837   return ISD::isNormalLoad(N);
3838 }
3839 
3840 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3841   if (isFloatingPointZero(Op))
3842     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3843 
3844   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3845     return DAG.getLoad(MVT::i32, SDLoc(Op),
3846                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3847                        Ld->isVolatile(), Ld->isNonTemporal(),
3848                        Ld->isInvariant(), Ld->getAlignment());
3849 
3850   llvm_unreachable("Unknown VFP cmp argument!");
3851 }
3852 
3853 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3854                            SDValue &RetVal1, SDValue &RetVal2) {
3855   SDLoc dl(Op);
3856 
3857   if (isFloatingPointZero(Op)) {
3858     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3859     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3860     return;
3861   }
3862 
3863   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3864     SDValue Ptr = Ld->getBasePtr();
3865     RetVal1 = DAG.getLoad(MVT::i32, dl,
3866                           Ld->getChain(), Ptr,
3867                           Ld->getPointerInfo(),
3868                           Ld->isVolatile(), Ld->isNonTemporal(),
3869                           Ld->isInvariant(), Ld->getAlignment());
3870 
3871     EVT PtrType = Ptr.getValueType();
3872     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3873     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3874                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3875     RetVal2 = DAG.getLoad(MVT::i32, dl,
3876                           Ld->getChain(), NewPtr,
3877                           Ld->getPointerInfo().getWithOffset(4),
3878                           Ld->isVolatile(), Ld->isNonTemporal(),
3879                           Ld->isInvariant(), NewAlign);
3880     return;
3881   }
3882 
3883   llvm_unreachable("Unknown VFP cmp argument!");
3884 }
3885 
3886 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3887 /// f32 and even f64 comparisons to integer ones.
3888 SDValue
3889 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3890   SDValue Chain = Op.getOperand(0);
3891   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3892   SDValue LHS = Op.getOperand(2);
3893   SDValue RHS = Op.getOperand(3);
3894   SDValue Dest = Op.getOperand(4);
3895   SDLoc dl(Op);
3896 
3897   bool LHSSeenZero = false;
3898   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3899   bool RHSSeenZero = false;
3900   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3901   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3902     // If unsafe fp math optimization is enabled and there are no other uses of
3903     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3904     // to an integer comparison.
3905     if (CC == ISD::SETOEQ)
3906       CC = ISD::SETEQ;
3907     else if (CC == ISD::SETUNE)
3908       CC = ISD::SETNE;
3909 
3910     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3911     SDValue ARMcc;
3912     if (LHS.getValueType() == MVT::f32) {
3913       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3914                         bitcastf32Toi32(LHS, DAG), Mask);
3915       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3916                         bitcastf32Toi32(RHS, DAG), Mask);
3917       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3918       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3919       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3920                          Chain, Dest, ARMcc, CCR, Cmp);
3921     }
3922 
3923     SDValue LHS1, LHS2;
3924     SDValue RHS1, RHS2;
3925     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3926     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3927     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3928     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3929     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3930     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3931     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3932     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3933     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3934   }
3935 
3936   return SDValue();
3937 }
3938 
3939 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3940   SDValue Chain = Op.getOperand(0);
3941   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3942   SDValue LHS = Op.getOperand(2);
3943   SDValue RHS = Op.getOperand(3);
3944   SDValue Dest = Op.getOperand(4);
3945   SDLoc dl(Op);
3946 
3947   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3948     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3949                                                     dl);
3950 
3951     // If softenSetCCOperands only returned one value, we should compare it to
3952     // zero.
3953     if (!RHS.getNode()) {
3954       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3955       CC = ISD::SETNE;
3956     }
3957   }
3958 
3959   if (LHS.getValueType() == MVT::i32) {
3960     SDValue ARMcc;
3961     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3962     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3963     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3964                        Chain, Dest, ARMcc, CCR, Cmp);
3965   }
3966 
3967   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3968 
3969   if (getTargetMachine().Options.UnsafeFPMath &&
3970       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3971        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3972     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
3973       return Result;
3974   }
3975 
3976   ARMCC::CondCodes CondCode, CondCode2;
3977   FPCCToARMCC(CC, CondCode, CondCode2);
3978 
3979   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3980   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3981   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3982   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3983   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3984   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3985   if (CondCode2 != ARMCC::AL) {
3986     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3987     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3988     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3989   }
3990   return Res;
3991 }
3992 
3993 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3994   SDValue Chain = Op.getOperand(0);
3995   SDValue Table = Op.getOperand(1);
3996   SDValue Index = Op.getOperand(2);
3997   SDLoc dl(Op);
3998 
3999   EVT PTy = getPointerTy(DAG.getDataLayout());
4000   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4001   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4002   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4003   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4004   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4005   if (Subtarget->isThumb2()) {
4006     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4007     // which does another jump to the destination. This also makes it easier
4008     // to translate it to TBB / TBH later.
4009     // FIXME: This might not work if the function is extremely large.
4010     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4011                        Addr, Op.getOperand(2), JTI);
4012   }
4013   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4014     Addr =
4015         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4016                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
4017                     false, false, false, 0);
4018     Chain = Addr.getValue(1);
4019     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4020     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4021   } else {
4022     Addr =
4023         DAG.getLoad(PTy, dl, Chain, Addr,
4024                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
4025                     false, false, false, 0);
4026     Chain = Addr.getValue(1);
4027     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4028   }
4029 }
4030 
4031 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4032   EVT VT = Op.getValueType();
4033   SDLoc dl(Op);
4034 
4035   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4036     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4037       return Op;
4038     return DAG.UnrollVectorOp(Op.getNode());
4039   }
4040 
4041   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4042          "Invalid type for custom lowering!");
4043   if (VT != MVT::v4i16)
4044     return DAG.UnrollVectorOp(Op.getNode());
4045 
4046   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4047   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4048 }
4049 
4050 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4051   EVT VT = Op.getValueType();
4052   if (VT.isVector())
4053     return LowerVectorFP_TO_INT(Op, DAG);
4054   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4055     RTLIB::Libcall LC;
4056     if (Op.getOpcode() == ISD::FP_TO_SINT)
4057       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4058                               Op.getValueType());
4059     else
4060       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4061                               Op.getValueType());
4062     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4063                        /*isSigned*/ false, SDLoc(Op)).first;
4064   }
4065 
4066   return Op;
4067 }
4068 
4069 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4070   EVT VT = Op.getValueType();
4071   SDLoc dl(Op);
4072 
4073   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4074     if (VT.getVectorElementType() == MVT::f32)
4075       return Op;
4076     return DAG.UnrollVectorOp(Op.getNode());
4077   }
4078 
4079   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4080          "Invalid type for custom lowering!");
4081   if (VT != MVT::v4f32)
4082     return DAG.UnrollVectorOp(Op.getNode());
4083 
4084   unsigned CastOpc;
4085   unsigned Opc;
4086   switch (Op.getOpcode()) {
4087   default: llvm_unreachable("Invalid opcode!");
4088   case ISD::SINT_TO_FP:
4089     CastOpc = ISD::SIGN_EXTEND;
4090     Opc = ISD::SINT_TO_FP;
4091     break;
4092   case ISD::UINT_TO_FP:
4093     CastOpc = ISD::ZERO_EXTEND;
4094     Opc = ISD::UINT_TO_FP;
4095     break;
4096   }
4097 
4098   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4099   return DAG.getNode(Opc, dl, VT, Op);
4100 }
4101 
4102 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4103   EVT VT = Op.getValueType();
4104   if (VT.isVector())
4105     return LowerVectorINT_TO_FP(Op, DAG);
4106   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4107     RTLIB::Libcall LC;
4108     if (Op.getOpcode() == ISD::SINT_TO_FP)
4109       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4110                               Op.getValueType());
4111     else
4112       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4113                               Op.getValueType());
4114     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4115                        /*isSigned*/ false, SDLoc(Op)).first;
4116   }
4117 
4118   return Op;
4119 }
4120 
4121 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4122   // Implement fcopysign with a fabs and a conditional fneg.
4123   SDValue Tmp0 = Op.getOperand(0);
4124   SDValue Tmp1 = Op.getOperand(1);
4125   SDLoc dl(Op);
4126   EVT VT = Op.getValueType();
4127   EVT SrcVT = Tmp1.getValueType();
4128   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4129     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4130   bool UseNEON = !InGPR && Subtarget->hasNEON();
4131 
4132   if (UseNEON) {
4133     // Use VBSL to copy the sign bit.
4134     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4135     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4136                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4137     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4138     if (VT == MVT::f64)
4139       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4140                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4141                          DAG.getConstant(32, dl, MVT::i32));
4142     else /*if (VT == MVT::f32)*/
4143       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4144     if (SrcVT == MVT::f32) {
4145       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4146       if (VT == MVT::f64)
4147         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4148                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4149                            DAG.getConstant(32, dl, MVT::i32));
4150     } else if (VT == MVT::f32)
4151       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4152                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4153                          DAG.getConstant(32, dl, MVT::i32));
4154     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4155     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4156 
4157     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4158                                             dl, MVT::i32);
4159     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4160     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4161                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4162 
4163     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4164                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4165                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4166     if (VT == MVT::f32) {
4167       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4168       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4169                         DAG.getConstant(0, dl, MVT::i32));
4170     } else {
4171       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4172     }
4173 
4174     return Res;
4175   }
4176 
4177   // Bitcast operand 1 to i32.
4178   if (SrcVT == MVT::f64)
4179     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4180                        Tmp1).getValue(1);
4181   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4182 
4183   // Or in the signbit with integer operations.
4184   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4185   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4186   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4187   if (VT == MVT::f32) {
4188     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4189                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4190     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4191                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4192   }
4193 
4194   // f64: Or the high part with signbit and then combine two parts.
4195   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4196                      Tmp0);
4197   SDValue Lo = Tmp0.getValue(0);
4198   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4199   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4200   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4201 }
4202 
4203 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4204   MachineFunction &MF = DAG.getMachineFunction();
4205   MachineFrameInfo *MFI = MF.getFrameInfo();
4206   MFI->setReturnAddressIsTaken(true);
4207 
4208   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4209     return SDValue();
4210 
4211   EVT VT = Op.getValueType();
4212   SDLoc dl(Op);
4213   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4214   if (Depth) {
4215     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4216     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4217     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4218                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4219                        MachinePointerInfo(), false, false, false, 0);
4220   }
4221 
4222   // Return LR, which contains the return address. Mark it an implicit live-in.
4223   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4224   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4225 }
4226 
4227 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4228   const ARMBaseRegisterInfo &ARI =
4229     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4230   MachineFunction &MF = DAG.getMachineFunction();
4231   MachineFrameInfo *MFI = MF.getFrameInfo();
4232   MFI->setFrameAddressIsTaken(true);
4233 
4234   EVT VT = Op.getValueType();
4235   SDLoc dl(Op);  // FIXME probably not meaningful
4236   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4237   unsigned FrameReg = ARI.getFrameRegister(MF);
4238   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4239   while (Depth--)
4240     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4241                             MachinePointerInfo(),
4242                             false, false, false, 0);
4243   return FrameAddr;
4244 }
4245 
4246 // FIXME? Maybe this could be a TableGen attribute on some registers and
4247 // this table could be generated automatically from RegInfo.
4248 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4249                                               SelectionDAG &DAG) const {
4250   unsigned Reg = StringSwitch<unsigned>(RegName)
4251                        .Case("sp", ARM::SP)
4252                        .Default(0);
4253   if (Reg)
4254     return Reg;
4255   report_fatal_error(Twine("Invalid register name \""
4256                               + StringRef(RegName)  + "\"."));
4257 }
4258 
4259 // Result is 64 bit value so split into two 32 bit values and return as a
4260 // pair of values.
4261 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4262                                 SelectionDAG &DAG) {
4263   SDLoc DL(N);
4264 
4265   // This function is only supposed to be called for i64 type destination.
4266   assert(N->getValueType(0) == MVT::i64
4267           && "ExpandREAD_REGISTER called for non-i64 type result.");
4268 
4269   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4270                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4271                              N->getOperand(0),
4272                              N->getOperand(1));
4273 
4274   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4275                     Read.getValue(1)));
4276   Results.push_back(Read.getOperand(0));
4277 }
4278 
4279 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4280 /// When \p DstVT, the destination type of \p BC, is on the vector
4281 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4282 /// it might be possible to combine them, such that everything stays on the
4283 /// vector register bank.
4284 /// \p return The node that would replace \p BT, if the combine
4285 /// is possible.
4286 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4287                                                 SelectionDAG &DAG) {
4288   SDValue Op = BC->getOperand(0);
4289   EVT DstVT = BC->getValueType(0);
4290 
4291   // The only vector instruction that can produce a scalar (remember,
4292   // since the bitcast was about to be turned into VMOVDRR, the source
4293   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4294   // Moreover, we can do this combine only if there is one use.
4295   // Finally, if the destination type is not a vector, there is not
4296   // much point on forcing everything on the vector bank.
4297   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4298       !Op.hasOneUse())
4299     return SDValue();
4300 
4301   // If the index is not constant, we will introduce an additional
4302   // multiply that will stick.
4303   // Give up in that case.
4304   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4305   if (!Index)
4306     return SDValue();
4307   unsigned DstNumElt = DstVT.getVectorNumElements();
4308 
4309   // Compute the new index.
4310   const APInt &APIntIndex = Index->getAPIntValue();
4311   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4312   NewIndex *= APIntIndex;
4313   // Check if the new constant index fits into i32.
4314   if (NewIndex.getBitWidth() > 32)
4315     return SDValue();
4316 
4317   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4318   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4319   SDLoc dl(Op);
4320   SDValue ExtractSrc = Op.getOperand(0);
4321   EVT VecVT = EVT::getVectorVT(
4322       *DAG.getContext(), DstVT.getScalarType(),
4323       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4324   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4325   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4326                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4327 }
4328 
4329 /// ExpandBITCAST - If the target supports VFP, this function is called to
4330 /// expand a bit convert where either the source or destination type is i64 to
4331 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4332 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4333 /// vectors), since the legalizer won't know what to do with that.
4334 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4336   SDLoc dl(N);
4337   SDValue Op = N->getOperand(0);
4338 
4339   // This function is only supposed to be called for i64 types, either as the
4340   // source or destination of the bit convert.
4341   EVT SrcVT = Op.getValueType();
4342   EVT DstVT = N->getValueType(0);
4343   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4344          "ExpandBITCAST called for non-i64 type");
4345 
4346   // Turn i64->f64 into VMOVDRR.
4347   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4348     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4349     // if we can combine the bitcast with its source.
4350     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4351       return Val;
4352 
4353     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4354                              DAG.getConstant(0, dl, MVT::i32));
4355     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4356                              DAG.getConstant(1, dl, MVT::i32));
4357     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4358                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4359   }
4360 
4361   // Turn f64->i64 into VMOVRRD.
4362   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4363     SDValue Cvt;
4364     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4365         SrcVT.getVectorNumElements() > 1)
4366       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4367                         DAG.getVTList(MVT::i32, MVT::i32),
4368                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4369     else
4370       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4371                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4372     // Merge the pieces into a single i64 value.
4373     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4374   }
4375 
4376   return SDValue();
4377 }
4378 
4379 /// getZeroVector - Returns a vector of specified type with all zero elements.
4380 /// Zero vectors are used to represent vector negation and in those cases
4381 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4382 /// not support i64 elements, so sometimes the zero vectors will need to be
4383 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4384 /// zero vector.
4385 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4386   assert(VT.isVector() && "Expected a vector type");
4387   // The canonical modified immediate encoding of a zero vector is....0!
4388   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4389   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4390   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4391   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4392 }
4393 
4394 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4395 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4396 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4397                                                 SelectionDAG &DAG) const {
4398   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4399   EVT VT = Op.getValueType();
4400   unsigned VTBits = VT.getSizeInBits();
4401   SDLoc dl(Op);
4402   SDValue ShOpLo = Op.getOperand(0);
4403   SDValue ShOpHi = Op.getOperand(1);
4404   SDValue ShAmt  = Op.getOperand(2);
4405   SDValue ARMcc;
4406   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4407 
4408   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4409 
4410   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4411                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4412   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4413   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4414                                    DAG.getConstant(VTBits, dl, MVT::i32));
4415   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4416   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4417   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4418 
4419   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4420   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4421                           ISD::SETGE, ARMcc, DAG, dl);
4422   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4423   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4424                            CCR, Cmp);
4425 
4426   SDValue Ops[2] = { Lo, Hi };
4427   return DAG.getMergeValues(Ops, dl);
4428 }
4429 
4430 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4431 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4432 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4433                                                SelectionDAG &DAG) const {
4434   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4435   EVT VT = Op.getValueType();
4436   unsigned VTBits = VT.getSizeInBits();
4437   SDLoc dl(Op);
4438   SDValue ShOpLo = Op.getOperand(0);
4439   SDValue ShOpHi = Op.getOperand(1);
4440   SDValue ShAmt  = Op.getOperand(2);
4441   SDValue ARMcc;
4442 
4443   assert(Op.getOpcode() == ISD::SHL_PARTS);
4444   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4445                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4446   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4447   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4448                                    DAG.getConstant(VTBits, dl, MVT::i32));
4449   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4450   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4451 
4452   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4453   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4454   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4455                           ISD::SETGE, ARMcc, DAG, dl);
4456   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4457   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4458                            CCR, Cmp);
4459 
4460   SDValue Ops[2] = { Lo, Hi };
4461   return DAG.getMergeValues(Ops, dl);
4462 }
4463 
4464 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4465                                             SelectionDAG &DAG) const {
4466   // The rounding mode is in bits 23:22 of the FPSCR.
4467   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4468   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4469   // so that the shift + and get folded into a bitfield extract.
4470   SDLoc dl(Op);
4471   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4472                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4473                                               MVT::i32));
4474   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4475                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4476   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4477                               DAG.getConstant(22, dl, MVT::i32));
4478   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4479                      DAG.getConstant(3, dl, MVT::i32));
4480 }
4481 
4482 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4483                          const ARMSubtarget *ST) {
4484   SDLoc dl(N);
4485   EVT VT = N->getValueType(0);
4486   if (VT.isVector()) {
4487     assert(ST->hasNEON());
4488 
4489     // Compute the least significant set bit: LSB = X & -X
4490     SDValue X = N->getOperand(0);
4491     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4492     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4493 
4494     EVT ElemTy = VT.getVectorElementType();
4495 
4496     if (ElemTy == MVT::i8) {
4497       // Compute with: cttz(x) = ctpop(lsb - 1)
4498       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4499                                 DAG.getTargetConstant(1, dl, ElemTy));
4500       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4501       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4502     }
4503 
4504     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4505         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4506       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4507       unsigned NumBits = ElemTy.getSizeInBits();
4508       SDValue WidthMinus1 =
4509           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4510                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4511       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4512       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4513     }
4514 
4515     // Compute with: cttz(x) = ctpop(lsb - 1)
4516 
4517     // Since we can only compute the number of bits in a byte with vcnt.8, we
4518     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4519     // and i64.
4520 
4521     // Compute LSB - 1.
4522     SDValue Bits;
4523     if (ElemTy == MVT::i64) {
4524       // Load constant 0xffff'ffff'ffff'ffff to register.
4525       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4526                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4527       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4528     } else {
4529       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4530                                 DAG.getTargetConstant(1, dl, ElemTy));
4531       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4532     }
4533 
4534     // Count #bits with vcnt.8.
4535     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4536     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4537     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4538 
4539     // Gather the #bits with vpaddl (pairwise add.)
4540     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4541     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4542         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4543         Cnt8);
4544     if (ElemTy == MVT::i16)
4545       return Cnt16;
4546 
4547     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4548     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4549         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4550         Cnt16);
4551     if (ElemTy == MVT::i32)
4552       return Cnt32;
4553 
4554     assert(ElemTy == MVT::i64);
4555     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4556         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4557         Cnt32);
4558     return Cnt64;
4559   }
4560 
4561   if (!ST->hasV6T2Ops())
4562     return SDValue();
4563 
4564   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4565   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4566 }
4567 
4568 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4569 /// for each 16-bit element from operand, repeated.  The basic idea is to
4570 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4571 ///
4572 /// Trace for v4i16:
4573 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4574 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4575 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4576 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4577 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4578 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4579 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4580 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4581 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4582   EVT VT = N->getValueType(0);
4583   SDLoc DL(N);
4584 
4585   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4586   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4587   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4588   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4589   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4590   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4591 }
4592 
4593 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4594 /// bit-count for each 16-bit element from the operand.  We need slightly
4595 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4596 /// 64/128-bit registers.
4597 ///
4598 /// Trace for v4i16:
4599 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4600 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4601 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4602 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4603 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4604   EVT VT = N->getValueType(0);
4605   SDLoc DL(N);
4606 
4607   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4608   if (VT.is64BitVector()) {
4609     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4610     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4611                        DAG.getIntPtrConstant(0, DL));
4612   } else {
4613     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4614                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4615     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4616   }
4617 }
4618 
4619 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4620 /// bit-count for each 32-bit element from the operand.  The idea here is
4621 /// to split the vector into 16-bit elements, leverage the 16-bit count
4622 /// routine, and then combine the results.
4623 ///
4624 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4625 /// input    = [v0    v1    ] (vi: 32-bit elements)
4626 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4627 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4628 /// vrev: N0 = [k1 k0 k3 k2 ]
4629 ///            [k0 k1 k2 k3 ]
4630 ///       N1 =+[k1 k0 k3 k2 ]
4631 ///            [k0 k2 k1 k3 ]
4632 ///       N2 =+[k1 k3 k0 k2 ]
4633 ///            [k0    k2    k1    k3    ]
4634 /// Extended =+[k1    k3    k0    k2    ]
4635 ///            [k0    k2    ]
4636 /// Extracted=+[k1    k3    ]
4637 ///
4638 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4639   EVT VT = N->getValueType(0);
4640   SDLoc DL(N);
4641 
4642   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4643 
4644   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4645   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4646   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4647   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4648   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4649 
4650   if (VT.is64BitVector()) {
4651     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4652     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4653                        DAG.getIntPtrConstant(0, DL));
4654   } else {
4655     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4656                                     DAG.getIntPtrConstant(0, DL));
4657     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4658   }
4659 }
4660 
4661 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4662                           const ARMSubtarget *ST) {
4663   EVT VT = N->getValueType(0);
4664 
4665   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4666   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4667           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4668          "Unexpected type for custom ctpop lowering");
4669 
4670   if (VT.getVectorElementType() == MVT::i32)
4671     return lowerCTPOP32BitElements(N, DAG);
4672   else
4673     return lowerCTPOP16BitElements(N, DAG);
4674 }
4675 
4676 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4677                           const ARMSubtarget *ST) {
4678   EVT VT = N->getValueType(0);
4679   SDLoc dl(N);
4680 
4681   if (!VT.isVector())
4682     return SDValue();
4683 
4684   // Lower vector shifts on NEON to use VSHL.
4685   assert(ST->hasNEON() && "unexpected vector shift");
4686 
4687   // Left shifts translate directly to the vshiftu intrinsic.
4688   if (N->getOpcode() == ISD::SHL)
4689     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4690                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4691                                        MVT::i32),
4692                        N->getOperand(0), N->getOperand(1));
4693 
4694   assert((N->getOpcode() == ISD::SRA ||
4695           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4696 
4697   // NEON uses the same intrinsics for both left and right shifts.  For
4698   // right shifts, the shift amounts are negative, so negate the vector of
4699   // shift amounts.
4700   EVT ShiftVT = N->getOperand(1).getValueType();
4701   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4702                                      getZeroVector(ShiftVT, DAG, dl),
4703                                      N->getOperand(1));
4704   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4705                              Intrinsic::arm_neon_vshifts :
4706                              Intrinsic::arm_neon_vshiftu);
4707   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4708                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4709                      N->getOperand(0), NegatedCount);
4710 }
4711 
4712 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4713                                 const ARMSubtarget *ST) {
4714   EVT VT = N->getValueType(0);
4715   SDLoc dl(N);
4716 
4717   // We can get here for a node like i32 = ISD::SHL i32, i64
4718   if (VT != MVT::i64)
4719     return SDValue();
4720 
4721   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4722          "Unknown shift to lower!");
4723 
4724   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4725   if (!isOneConstant(N->getOperand(1)))
4726     return SDValue();
4727 
4728   // If we are in thumb mode, we don't have RRX.
4729   if (ST->isThumb1Only()) return SDValue();
4730 
4731   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4732   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4733                            DAG.getConstant(0, dl, MVT::i32));
4734   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4735                            DAG.getConstant(1, dl, MVT::i32));
4736 
4737   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4738   // captures the result into a carry flag.
4739   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4740   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4741 
4742   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4743   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4744 
4745   // Merge the pieces into a single i64 value.
4746  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4747 }
4748 
4749 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4750   SDValue TmpOp0, TmpOp1;
4751   bool Invert = false;
4752   bool Swap = false;
4753   unsigned Opc = 0;
4754 
4755   SDValue Op0 = Op.getOperand(0);
4756   SDValue Op1 = Op.getOperand(1);
4757   SDValue CC = Op.getOperand(2);
4758   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4759   EVT VT = Op.getValueType();
4760   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4761   SDLoc dl(Op);
4762 
4763   if (CmpVT.getVectorElementType() == MVT::i64)
4764     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4765     // but it's possible that our operands are 64-bit but our result is 32-bit.
4766     // Bail in this case.
4767     return SDValue();
4768 
4769   if (Op1.getValueType().isFloatingPoint()) {
4770     switch (SetCCOpcode) {
4771     default: llvm_unreachable("Illegal FP comparison");
4772     case ISD::SETUNE:
4773     case ISD::SETNE:  Invert = true; // Fallthrough
4774     case ISD::SETOEQ:
4775     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4776     case ISD::SETOLT:
4777     case ISD::SETLT: Swap = true; // Fallthrough
4778     case ISD::SETOGT:
4779     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4780     case ISD::SETOLE:
4781     case ISD::SETLE:  Swap = true; // Fallthrough
4782     case ISD::SETOGE:
4783     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4784     case ISD::SETUGE: Swap = true; // Fallthrough
4785     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4786     case ISD::SETUGT: Swap = true; // Fallthrough
4787     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4788     case ISD::SETUEQ: Invert = true; // Fallthrough
4789     case ISD::SETONE:
4790       // Expand this to (OLT | OGT).
4791       TmpOp0 = Op0;
4792       TmpOp1 = Op1;
4793       Opc = ISD::OR;
4794       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4795       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4796       break;
4797     case ISD::SETUO: Invert = true; // Fallthrough
4798     case ISD::SETO:
4799       // Expand this to (OLT | OGE).
4800       TmpOp0 = Op0;
4801       TmpOp1 = Op1;
4802       Opc = ISD::OR;
4803       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4804       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4805       break;
4806     }
4807   } else {
4808     // Integer comparisons.
4809     switch (SetCCOpcode) {
4810     default: llvm_unreachable("Illegal integer comparison");
4811     case ISD::SETNE:  Invert = true;
4812     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4813     case ISD::SETLT:  Swap = true;
4814     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4815     case ISD::SETLE:  Swap = true;
4816     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4817     case ISD::SETULT: Swap = true;
4818     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4819     case ISD::SETULE: Swap = true;
4820     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4821     }
4822 
4823     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4824     if (Opc == ARMISD::VCEQ) {
4825 
4826       SDValue AndOp;
4827       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4828         AndOp = Op0;
4829       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4830         AndOp = Op1;
4831 
4832       // Ignore bitconvert.
4833       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4834         AndOp = AndOp.getOperand(0);
4835 
4836       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4837         Opc = ARMISD::VTST;
4838         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4839         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4840         Invert = !Invert;
4841       }
4842     }
4843   }
4844 
4845   if (Swap)
4846     std::swap(Op0, Op1);
4847 
4848   // If one of the operands is a constant vector zero, attempt to fold the
4849   // comparison to a specialized compare-against-zero form.
4850   SDValue SingleOp;
4851   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4852     SingleOp = Op0;
4853   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4854     if (Opc == ARMISD::VCGE)
4855       Opc = ARMISD::VCLEZ;
4856     else if (Opc == ARMISD::VCGT)
4857       Opc = ARMISD::VCLTZ;
4858     SingleOp = Op1;
4859   }
4860 
4861   SDValue Result;
4862   if (SingleOp.getNode()) {
4863     switch (Opc) {
4864     case ARMISD::VCEQ:
4865       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4866     case ARMISD::VCGE:
4867       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4868     case ARMISD::VCLEZ:
4869       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4870     case ARMISD::VCGT:
4871       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4872     case ARMISD::VCLTZ:
4873       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4874     default:
4875       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4876     }
4877   } else {
4878      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4879   }
4880 
4881   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4882 
4883   if (Invert)
4884     Result = DAG.getNOT(dl, Result, VT);
4885 
4886   return Result;
4887 }
4888 
4889 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4890 /// valid vector constant for a NEON instruction with a "modified immediate"
4891 /// operand (e.g., VMOV).  If so, return the encoded value.
4892 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4893                                  unsigned SplatBitSize, SelectionDAG &DAG,
4894                                  SDLoc dl, EVT &VT, bool is128Bits,
4895                                  NEONModImmType type) {
4896   unsigned OpCmode, Imm;
4897 
4898   // SplatBitSize is set to the smallest size that splats the vector, so a
4899   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4900   // immediate instructions others than VMOV do not support the 8-bit encoding
4901   // of a zero vector, and the default encoding of zero is supposed to be the
4902   // 32-bit version.
4903   if (SplatBits == 0)
4904     SplatBitSize = 32;
4905 
4906   switch (SplatBitSize) {
4907   case 8:
4908     if (type != VMOVModImm)
4909       return SDValue();
4910     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4911     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4912     OpCmode = 0xe;
4913     Imm = SplatBits;
4914     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4915     break;
4916 
4917   case 16:
4918     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4919     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4920     if ((SplatBits & ~0xff) == 0) {
4921       // Value = 0x00nn: Op=x, Cmode=100x.
4922       OpCmode = 0x8;
4923       Imm = SplatBits;
4924       break;
4925     }
4926     if ((SplatBits & ~0xff00) == 0) {
4927       // Value = 0xnn00: Op=x, Cmode=101x.
4928       OpCmode = 0xa;
4929       Imm = SplatBits >> 8;
4930       break;
4931     }
4932     return SDValue();
4933 
4934   case 32:
4935     // NEON's 32-bit VMOV supports splat values where:
4936     // * only one byte is nonzero, or
4937     // * the least significant byte is 0xff and the second byte is nonzero, or
4938     // * the least significant 2 bytes are 0xff and the third is nonzero.
4939     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4940     if ((SplatBits & ~0xff) == 0) {
4941       // Value = 0x000000nn: Op=x, Cmode=000x.
4942       OpCmode = 0;
4943       Imm = SplatBits;
4944       break;
4945     }
4946     if ((SplatBits & ~0xff00) == 0) {
4947       // Value = 0x0000nn00: Op=x, Cmode=001x.
4948       OpCmode = 0x2;
4949       Imm = SplatBits >> 8;
4950       break;
4951     }
4952     if ((SplatBits & ~0xff0000) == 0) {
4953       // Value = 0x00nn0000: Op=x, Cmode=010x.
4954       OpCmode = 0x4;
4955       Imm = SplatBits >> 16;
4956       break;
4957     }
4958     if ((SplatBits & ~0xff000000) == 0) {
4959       // Value = 0xnn000000: Op=x, Cmode=011x.
4960       OpCmode = 0x6;
4961       Imm = SplatBits >> 24;
4962       break;
4963     }
4964 
4965     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4966     if (type == OtherModImm) return SDValue();
4967 
4968     if ((SplatBits & ~0xffff) == 0 &&
4969         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4970       // Value = 0x0000nnff: Op=x, Cmode=1100.
4971       OpCmode = 0xc;
4972       Imm = SplatBits >> 8;
4973       break;
4974     }
4975 
4976     if ((SplatBits & ~0xffffff) == 0 &&
4977         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4978       // Value = 0x00nnffff: Op=x, Cmode=1101.
4979       OpCmode = 0xd;
4980       Imm = SplatBits >> 16;
4981       break;
4982     }
4983 
4984     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4985     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4986     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4987     // and fall through here to test for a valid 64-bit splat.  But, then the
4988     // caller would also need to check and handle the change in size.
4989     return SDValue();
4990 
4991   case 64: {
4992     if (type != VMOVModImm)
4993       return SDValue();
4994     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4995     uint64_t BitMask = 0xff;
4996     uint64_t Val = 0;
4997     unsigned ImmMask = 1;
4998     Imm = 0;
4999     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5000       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5001         Val |= BitMask;
5002         Imm |= ImmMask;
5003       } else if ((SplatBits & BitMask) != 0) {
5004         return SDValue();
5005       }
5006       BitMask <<= 8;
5007       ImmMask <<= 1;
5008     }
5009 
5010     if (DAG.getDataLayout().isBigEndian())
5011       // swap higher and lower 32 bit word
5012       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5013 
5014     // Op=1, Cmode=1110.
5015     OpCmode = 0x1e;
5016     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5017     break;
5018   }
5019 
5020   default:
5021     llvm_unreachable("unexpected size for isNEONModifiedImm");
5022   }
5023 
5024   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5025   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5026 }
5027 
5028 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5029                                            const ARMSubtarget *ST) const {
5030   if (!ST->hasVFP3())
5031     return SDValue();
5032 
5033   bool IsDouble = Op.getValueType() == MVT::f64;
5034   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5035 
5036   // Use the default (constant pool) lowering for double constants when we have
5037   // an SP-only FPU
5038   if (IsDouble && Subtarget->isFPOnlySP())
5039     return SDValue();
5040 
5041   // Try splatting with a VMOV.f32...
5042   APFloat FPVal = CFP->getValueAPF();
5043   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5044 
5045   if (ImmVal != -1) {
5046     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5047       // We have code in place to select a valid ConstantFP already, no need to
5048       // do any mangling.
5049       return Op;
5050     }
5051 
5052     // It's a float and we are trying to use NEON operations where
5053     // possible. Lower it to a splat followed by an extract.
5054     SDLoc DL(Op);
5055     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5056     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5057                                       NewVal);
5058     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5059                        DAG.getConstant(0, DL, MVT::i32));
5060   }
5061 
5062   // The rest of our options are NEON only, make sure that's allowed before
5063   // proceeding..
5064   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5065     return SDValue();
5066 
5067   EVT VMovVT;
5068   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5069 
5070   // It wouldn't really be worth bothering for doubles except for one very
5071   // important value, which does happen to match: 0.0. So make sure we don't do
5072   // anything stupid.
5073   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5074     return SDValue();
5075 
5076   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5077   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5078                                      VMovVT, false, VMOVModImm);
5079   if (NewVal != SDValue()) {
5080     SDLoc DL(Op);
5081     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5082                                       NewVal);
5083     if (IsDouble)
5084       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5085 
5086     // It's a float: cast and extract a vector element.
5087     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5088                                        VecConstant);
5089     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5090                        DAG.getConstant(0, DL, MVT::i32));
5091   }
5092 
5093   // Finally, try a VMVN.i32
5094   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5095                              false, VMVNModImm);
5096   if (NewVal != SDValue()) {
5097     SDLoc DL(Op);
5098     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5099 
5100     if (IsDouble)
5101       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5102 
5103     // It's a float: cast and extract a vector element.
5104     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5105                                        VecConstant);
5106     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5107                        DAG.getConstant(0, DL, MVT::i32));
5108   }
5109 
5110   return SDValue();
5111 }
5112 
5113 // check if an VEXT instruction can handle the shuffle mask when the
5114 // vector sources of the shuffle are the same.
5115 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5116   unsigned NumElts = VT.getVectorNumElements();
5117 
5118   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5119   if (M[0] < 0)
5120     return false;
5121 
5122   Imm = M[0];
5123 
5124   // If this is a VEXT shuffle, the immediate value is the index of the first
5125   // element.  The other shuffle indices must be the successive elements after
5126   // the first one.
5127   unsigned ExpectedElt = Imm;
5128   for (unsigned i = 1; i < NumElts; ++i) {
5129     // Increment the expected index.  If it wraps around, just follow it
5130     // back to index zero and keep going.
5131     ++ExpectedElt;
5132     if (ExpectedElt == NumElts)
5133       ExpectedElt = 0;
5134 
5135     if (M[i] < 0) continue; // ignore UNDEF indices
5136     if (ExpectedElt != static_cast<unsigned>(M[i]))
5137       return false;
5138   }
5139 
5140   return true;
5141 }
5142 
5143 
5144 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5145                        bool &ReverseVEXT, unsigned &Imm) {
5146   unsigned NumElts = VT.getVectorNumElements();
5147   ReverseVEXT = false;
5148 
5149   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5150   if (M[0] < 0)
5151     return false;
5152 
5153   Imm = M[0];
5154 
5155   // If this is a VEXT shuffle, the immediate value is the index of the first
5156   // element.  The other shuffle indices must be the successive elements after
5157   // the first one.
5158   unsigned ExpectedElt = Imm;
5159   for (unsigned i = 1; i < NumElts; ++i) {
5160     // Increment the expected index.  If it wraps around, it may still be
5161     // a VEXT but the source vectors must be swapped.
5162     ExpectedElt += 1;
5163     if (ExpectedElt == NumElts * 2) {
5164       ExpectedElt = 0;
5165       ReverseVEXT = true;
5166     }
5167 
5168     if (M[i] < 0) continue; // ignore UNDEF indices
5169     if (ExpectedElt != static_cast<unsigned>(M[i]))
5170       return false;
5171   }
5172 
5173   // Adjust the index value if the source operands will be swapped.
5174   if (ReverseVEXT)
5175     Imm -= NumElts;
5176 
5177   return true;
5178 }
5179 
5180 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5181 /// instruction with the specified blocksize.  (The order of the elements
5182 /// within each block of the vector is reversed.)
5183 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5184   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5185          "Only possible block sizes for VREV are: 16, 32, 64");
5186 
5187   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5188   if (EltSz == 64)
5189     return false;
5190 
5191   unsigned NumElts = VT.getVectorNumElements();
5192   unsigned BlockElts = M[0] + 1;
5193   // If the first shuffle index is UNDEF, be optimistic.
5194   if (M[0] < 0)
5195     BlockElts = BlockSize / EltSz;
5196 
5197   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5198     return false;
5199 
5200   for (unsigned i = 0; i < NumElts; ++i) {
5201     if (M[i] < 0) continue; // ignore UNDEF indices
5202     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5203       return false;
5204   }
5205 
5206   return true;
5207 }
5208 
5209 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5210   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5211   // range, then 0 is placed into the resulting vector. So pretty much any mask
5212   // of 8 elements can work here.
5213   return VT == MVT::v8i8 && M.size() == 8;
5214 }
5215 
5216 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5217 // checking that pairs of elements in the shuffle mask represent the same index
5218 // in each vector, incrementing the expected index by 2 at each step.
5219 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5220 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5221 //  v2={e,f,g,h}
5222 // WhichResult gives the offset for each element in the mask based on which
5223 // of the two results it belongs to.
5224 //
5225 // The transpose can be represented either as:
5226 // result1 = shufflevector v1, v2, result1_shuffle_mask
5227 // result2 = shufflevector v1, v2, result2_shuffle_mask
5228 // where v1/v2 and the shuffle masks have the same number of elements
5229 // (here WhichResult (see below) indicates which result is being checked)
5230 //
5231 // or as:
5232 // results = shufflevector v1, v2, shuffle_mask
5233 // where both results are returned in one vector and the shuffle mask has twice
5234 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5235 // want to check the low half and high half of the shuffle mask as if it were
5236 // the other case
5237 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5238   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5239   if (EltSz == 64)
5240     return false;
5241 
5242   unsigned NumElts = VT.getVectorNumElements();
5243   if (M.size() != NumElts && M.size() != NumElts*2)
5244     return false;
5245 
5246   // If the mask is twice as long as the input vector then we need to check the
5247   // upper and lower parts of the mask with a matching value for WhichResult
5248   // FIXME: A mask with only even values will be rejected in case the first
5249   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5250   // M[0] is used to determine WhichResult
5251   for (unsigned i = 0; i < M.size(); i += NumElts) {
5252     if (M.size() == NumElts * 2)
5253       WhichResult = i / NumElts;
5254     else
5255       WhichResult = M[i] == 0 ? 0 : 1;
5256     for (unsigned j = 0; j < NumElts; j += 2) {
5257       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5258           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5259         return false;
5260     }
5261   }
5262 
5263   if (M.size() == NumElts*2)
5264     WhichResult = 0;
5265 
5266   return true;
5267 }
5268 
5269 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5270 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5271 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5272 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5273   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5274   if (EltSz == 64)
5275     return false;
5276 
5277   unsigned NumElts = VT.getVectorNumElements();
5278   if (M.size() != NumElts && M.size() != NumElts*2)
5279     return false;
5280 
5281   for (unsigned i = 0; i < M.size(); i += NumElts) {
5282     if (M.size() == NumElts * 2)
5283       WhichResult = i / NumElts;
5284     else
5285       WhichResult = M[i] == 0 ? 0 : 1;
5286     for (unsigned j = 0; j < NumElts; j += 2) {
5287       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5288           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5289         return false;
5290     }
5291   }
5292 
5293   if (M.size() == NumElts*2)
5294     WhichResult = 0;
5295 
5296   return true;
5297 }
5298 
5299 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5300 // that the mask elements are either all even and in steps of size 2 or all odd
5301 // and in steps of size 2.
5302 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5303 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5304 //  v2={e,f,g,h}
5305 // Requires similar checks to that of isVTRNMask with
5306 // respect the how results are returned.
5307 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5308   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5309   if (EltSz == 64)
5310     return false;
5311 
5312   unsigned NumElts = VT.getVectorNumElements();
5313   if (M.size() != NumElts && M.size() != NumElts*2)
5314     return false;
5315 
5316   for (unsigned i = 0; i < M.size(); i += NumElts) {
5317     WhichResult = M[i] == 0 ? 0 : 1;
5318     for (unsigned j = 0; j < NumElts; ++j) {
5319       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5320         return false;
5321     }
5322   }
5323 
5324   if (M.size() == NumElts*2)
5325     WhichResult = 0;
5326 
5327   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5328   if (VT.is64BitVector() && EltSz == 32)
5329     return false;
5330 
5331   return true;
5332 }
5333 
5334 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5335 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5336 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5337 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5338   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5339   if (EltSz == 64)
5340     return false;
5341 
5342   unsigned NumElts = VT.getVectorNumElements();
5343   if (M.size() != NumElts && M.size() != NumElts*2)
5344     return false;
5345 
5346   unsigned Half = NumElts / 2;
5347   for (unsigned i = 0; i < M.size(); i += NumElts) {
5348     WhichResult = M[i] == 0 ? 0 : 1;
5349     for (unsigned j = 0; j < NumElts; j += Half) {
5350       unsigned Idx = WhichResult;
5351       for (unsigned k = 0; k < Half; ++k) {
5352         int MIdx = M[i + j + k];
5353         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5354           return false;
5355         Idx += 2;
5356       }
5357     }
5358   }
5359 
5360   if (M.size() == NumElts*2)
5361     WhichResult = 0;
5362 
5363   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5364   if (VT.is64BitVector() && EltSz == 32)
5365     return false;
5366 
5367   return true;
5368 }
5369 
5370 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5371 // that pairs of elements of the shufflemask represent the same index in each
5372 // vector incrementing sequentially through the vectors.
5373 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5374 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5375 //  v2={e,f,g,h}
5376 // Requires similar checks to that of isVTRNMask with respect the how results
5377 // are returned.
5378 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5379   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5380   if (EltSz == 64)
5381     return false;
5382 
5383   unsigned NumElts = VT.getVectorNumElements();
5384   if (M.size() != NumElts && M.size() != NumElts*2)
5385     return false;
5386 
5387   for (unsigned i = 0; i < M.size(); i += NumElts) {
5388     WhichResult = M[i] == 0 ? 0 : 1;
5389     unsigned Idx = WhichResult * NumElts / 2;
5390     for (unsigned j = 0; j < NumElts; j += 2) {
5391       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5392           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5393         return false;
5394       Idx += 1;
5395     }
5396   }
5397 
5398   if (M.size() == NumElts*2)
5399     WhichResult = 0;
5400 
5401   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5402   if (VT.is64BitVector() && EltSz == 32)
5403     return false;
5404 
5405   return true;
5406 }
5407 
5408 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5409 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5410 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5411 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5412   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5413   if (EltSz == 64)
5414     return false;
5415 
5416   unsigned NumElts = VT.getVectorNumElements();
5417   if (M.size() != NumElts && M.size() != NumElts*2)
5418     return false;
5419 
5420   for (unsigned i = 0; i < M.size(); i += NumElts) {
5421     WhichResult = M[i] == 0 ? 0 : 1;
5422     unsigned Idx = WhichResult * NumElts / 2;
5423     for (unsigned j = 0; j < NumElts; j += 2) {
5424       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5425           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5426         return false;
5427       Idx += 1;
5428     }
5429   }
5430 
5431   if (M.size() == NumElts*2)
5432     WhichResult = 0;
5433 
5434   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5435   if (VT.is64BitVector() && EltSz == 32)
5436     return false;
5437 
5438   return true;
5439 }
5440 
5441 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5442 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5443 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5444                                            unsigned &WhichResult,
5445                                            bool &isV_UNDEF) {
5446   isV_UNDEF = false;
5447   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5448     return ARMISD::VTRN;
5449   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5450     return ARMISD::VUZP;
5451   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5452     return ARMISD::VZIP;
5453 
5454   isV_UNDEF = true;
5455   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5456     return ARMISD::VTRN;
5457   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5458     return ARMISD::VUZP;
5459   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5460     return ARMISD::VZIP;
5461 
5462   return 0;
5463 }
5464 
5465 /// \return true if this is a reverse operation on an vector.
5466 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5467   unsigned NumElts = VT.getVectorNumElements();
5468   // Make sure the mask has the right size.
5469   if (NumElts != M.size())
5470       return false;
5471 
5472   // Look for <15, ..., 3, -1, 1, 0>.
5473   for (unsigned i = 0; i != NumElts; ++i)
5474     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5475       return false;
5476 
5477   return true;
5478 }
5479 
5480 // If N is an integer constant that can be moved into a register in one
5481 // instruction, return an SDValue of such a constant (will become a MOV
5482 // instruction).  Otherwise return null.
5483 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5484                                      const ARMSubtarget *ST, SDLoc dl) {
5485   uint64_t Val;
5486   if (!isa<ConstantSDNode>(N))
5487     return SDValue();
5488   Val = cast<ConstantSDNode>(N)->getZExtValue();
5489 
5490   if (ST->isThumb1Only()) {
5491     if (Val <= 255 || ~Val <= 255)
5492       return DAG.getConstant(Val, dl, MVT::i32);
5493   } else {
5494     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5495       return DAG.getConstant(Val, dl, MVT::i32);
5496   }
5497   return SDValue();
5498 }
5499 
5500 // If this is a case we can't handle, return null and let the default
5501 // expansion code take care of it.
5502 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5503                                              const ARMSubtarget *ST) const {
5504   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5505   SDLoc dl(Op);
5506   EVT VT = Op.getValueType();
5507 
5508   APInt SplatBits, SplatUndef;
5509   unsigned SplatBitSize;
5510   bool HasAnyUndefs;
5511   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5512     if (SplatBitSize <= 64) {
5513       // Check if an immediate VMOV works.
5514       EVT VmovVT;
5515       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5516                                       SplatUndef.getZExtValue(), SplatBitSize,
5517                                       DAG, dl, VmovVT, VT.is128BitVector(),
5518                                       VMOVModImm);
5519       if (Val.getNode()) {
5520         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5521         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5522       }
5523 
5524       // Try an immediate VMVN.
5525       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5526       Val = isNEONModifiedImm(NegatedImm,
5527                                       SplatUndef.getZExtValue(), SplatBitSize,
5528                                       DAG, dl, VmovVT, VT.is128BitVector(),
5529                                       VMVNModImm);
5530       if (Val.getNode()) {
5531         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5532         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5533       }
5534 
5535       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5536       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5537         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5538         if (ImmVal != -1) {
5539           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5540           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5541         }
5542       }
5543     }
5544   }
5545 
5546   // Scan through the operands to see if only one value is used.
5547   //
5548   // As an optimisation, even if more than one value is used it may be more
5549   // profitable to splat with one value then change some lanes.
5550   //
5551   // Heuristically we decide to do this if the vector has a "dominant" value,
5552   // defined as splatted to more than half of the lanes.
5553   unsigned NumElts = VT.getVectorNumElements();
5554   bool isOnlyLowElement = true;
5555   bool usesOnlyOneValue = true;
5556   bool hasDominantValue = false;
5557   bool isConstant = true;
5558 
5559   // Map of the number of times a particular SDValue appears in the
5560   // element list.
5561   DenseMap<SDValue, unsigned> ValueCounts;
5562   SDValue Value;
5563   for (unsigned i = 0; i < NumElts; ++i) {
5564     SDValue V = Op.getOperand(i);
5565     if (V.isUndef())
5566       continue;
5567     if (i > 0)
5568       isOnlyLowElement = false;
5569     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5570       isConstant = false;
5571 
5572     ValueCounts.insert(std::make_pair(V, 0));
5573     unsigned &Count = ValueCounts[V];
5574 
5575     // Is this value dominant? (takes up more than half of the lanes)
5576     if (++Count > (NumElts / 2)) {
5577       hasDominantValue = true;
5578       Value = V;
5579     }
5580   }
5581   if (ValueCounts.size() != 1)
5582     usesOnlyOneValue = false;
5583   if (!Value.getNode() && ValueCounts.size() > 0)
5584     Value = ValueCounts.begin()->first;
5585 
5586   if (ValueCounts.size() == 0)
5587     return DAG.getUNDEF(VT);
5588 
5589   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5590   // Keep going if we are hitting this case.
5591   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5592     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5593 
5594   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5595 
5596   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5597   // i32 and try again.
5598   if (hasDominantValue && EltSize <= 32) {
5599     if (!isConstant) {
5600       SDValue N;
5601 
5602       // If we are VDUPing a value that comes directly from a vector, that will
5603       // cause an unnecessary move to and from a GPR, where instead we could
5604       // just use VDUPLANE. We can only do this if the lane being extracted
5605       // is at a constant index, as the VDUP from lane instructions only have
5606       // constant-index forms.
5607       ConstantSDNode *constIndex;
5608       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5609           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5610         // We need to create a new undef vector to use for the VDUPLANE if the
5611         // size of the vector from which we get the value is different than the
5612         // size of the vector that we need to create. We will insert the element
5613         // such that the register coalescer will remove unnecessary copies.
5614         if (VT != Value->getOperand(0).getValueType()) {
5615           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5616                              VT.getVectorNumElements();
5617           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5618                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5619                         Value, DAG.getConstant(index, dl, MVT::i32)),
5620                            DAG.getConstant(index, dl, MVT::i32));
5621         } else
5622           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5623                         Value->getOperand(0), Value->getOperand(1));
5624       } else
5625         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5626 
5627       if (!usesOnlyOneValue) {
5628         // The dominant value was splatted as 'N', but we now have to insert
5629         // all differing elements.
5630         for (unsigned I = 0; I < NumElts; ++I) {
5631           if (Op.getOperand(I) == Value)
5632             continue;
5633           SmallVector<SDValue, 3> Ops;
5634           Ops.push_back(N);
5635           Ops.push_back(Op.getOperand(I));
5636           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5637           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5638         }
5639       }
5640       return N;
5641     }
5642     if (VT.getVectorElementType().isFloatingPoint()) {
5643       SmallVector<SDValue, 8> Ops;
5644       for (unsigned i = 0; i < NumElts; ++i)
5645         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5646                                   Op.getOperand(i)));
5647       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5648       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5649       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5650       if (Val.getNode())
5651         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5652     }
5653     if (usesOnlyOneValue) {
5654       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5655       if (isConstant && Val.getNode())
5656         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5657     }
5658   }
5659 
5660   // If all elements are constants and the case above didn't get hit, fall back
5661   // to the default expansion, which will generate a load from the constant
5662   // pool.
5663   if (isConstant)
5664     return SDValue();
5665 
5666   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5667   if (NumElts >= 4) {
5668     SDValue shuffle = ReconstructShuffle(Op, DAG);
5669     if (shuffle != SDValue())
5670       return shuffle;
5671   }
5672 
5673   // Vectors with 32- or 64-bit elements can be built by directly assigning
5674   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5675   // will be legalized.
5676   if (EltSize >= 32) {
5677     // Do the expansion with floating-point types, since that is what the VFP
5678     // registers are defined to use, and since i64 is not legal.
5679     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5680     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5681     SmallVector<SDValue, 8> Ops;
5682     for (unsigned i = 0; i < NumElts; ++i)
5683       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5684     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5685     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5686   }
5687 
5688   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5689   // know the default expansion would otherwise fall back on something even
5690   // worse. For a vector with one or two non-undef values, that's
5691   // scalar_to_vector for the elements followed by a shuffle (provided the
5692   // shuffle is valid for the target) and materialization element by element
5693   // on the stack followed by a load for everything else.
5694   if (!isConstant && !usesOnlyOneValue) {
5695     SDValue Vec = DAG.getUNDEF(VT);
5696     for (unsigned i = 0 ; i < NumElts; ++i) {
5697       SDValue V = Op.getOperand(i);
5698       if (V.isUndef())
5699         continue;
5700       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5701       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5702     }
5703     return Vec;
5704   }
5705 
5706   return SDValue();
5707 }
5708 
5709 // Gather data to see if the operation can be modelled as a
5710 // shuffle in combination with VEXTs.
5711 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5712                                               SelectionDAG &DAG) const {
5713   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5714   SDLoc dl(Op);
5715   EVT VT = Op.getValueType();
5716   unsigned NumElts = VT.getVectorNumElements();
5717 
5718   struct ShuffleSourceInfo {
5719     SDValue Vec;
5720     unsigned MinElt;
5721     unsigned MaxElt;
5722 
5723     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5724     // be compatible with the shuffle we intend to construct. As a result
5725     // ShuffleVec will be some sliding window into the original Vec.
5726     SDValue ShuffleVec;
5727 
5728     // Code should guarantee that element i in Vec starts at element "WindowBase
5729     // + i * WindowScale in ShuffleVec".
5730     int WindowBase;
5731     int WindowScale;
5732 
5733     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5734     ShuffleSourceInfo(SDValue Vec)
5735         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5736           WindowScale(1) {}
5737   };
5738 
5739   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5740   // node.
5741   SmallVector<ShuffleSourceInfo, 2> Sources;
5742   for (unsigned i = 0; i < NumElts; ++i) {
5743     SDValue V = Op.getOperand(i);
5744     if (V.isUndef())
5745       continue;
5746     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5747       // A shuffle can only come from building a vector from various
5748       // elements of other vectors.
5749       return SDValue();
5750     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5751       // Furthermore, shuffles require a constant mask, whereas extractelts
5752       // accept variable indices.
5753       return SDValue();
5754     }
5755 
5756     // Add this element source to the list if it's not already there.
5757     SDValue SourceVec = V.getOperand(0);
5758     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5759     if (Source == Sources.end())
5760       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5761 
5762     // Update the minimum and maximum lane number seen.
5763     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5764     Source->MinElt = std::min(Source->MinElt, EltNo);
5765     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5766   }
5767 
5768   // Currently only do something sane when at most two source vectors
5769   // are involved.
5770   if (Sources.size() > 2)
5771     return SDValue();
5772 
5773   // Find out the smallest element size among result and two sources, and use
5774   // it as element size to build the shuffle_vector.
5775   EVT SmallestEltTy = VT.getVectorElementType();
5776   for (auto &Source : Sources) {
5777     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5778     if (SrcEltTy.bitsLT(SmallestEltTy))
5779       SmallestEltTy = SrcEltTy;
5780   }
5781   unsigned ResMultiplier =
5782       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5783   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5784   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5785 
5786   // If the source vector is too wide or too narrow, we may nevertheless be able
5787   // to construct a compatible shuffle either by concatenating it with UNDEF or
5788   // extracting a suitable range of elements.
5789   for (auto &Src : Sources) {
5790     EVT SrcVT = Src.ShuffleVec.getValueType();
5791 
5792     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5793       continue;
5794 
5795     // This stage of the search produces a source with the same element type as
5796     // the original, but with a total width matching the BUILD_VECTOR output.
5797     EVT EltVT = SrcVT.getVectorElementType();
5798     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5799     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5800 
5801     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5802       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5803         return SDValue();
5804       // We can pad out the smaller vector for free, so if it's part of a
5805       // shuffle...
5806       Src.ShuffleVec =
5807           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5808                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5809       continue;
5810     }
5811 
5812     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5813       return SDValue();
5814 
5815     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5816       // Span too large for a VEXT to cope
5817       return SDValue();
5818     }
5819 
5820     if (Src.MinElt >= NumSrcElts) {
5821       // The extraction can just take the second half
5822       Src.ShuffleVec =
5823           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5824                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5825       Src.WindowBase = -NumSrcElts;
5826     } else if (Src.MaxElt < NumSrcElts) {
5827       // The extraction can just take the first half
5828       Src.ShuffleVec =
5829           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5830                       DAG.getConstant(0, dl, MVT::i32));
5831     } else {
5832       // An actual VEXT is needed
5833       SDValue VEXTSrc1 =
5834           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5835                       DAG.getConstant(0, dl, MVT::i32));
5836       SDValue VEXTSrc2 =
5837           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5838                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5839 
5840       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5841                                    VEXTSrc2,
5842                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5843       Src.WindowBase = -Src.MinElt;
5844     }
5845   }
5846 
5847   // Another possible incompatibility occurs from the vector element types. We
5848   // can fix this by bitcasting the source vectors to the same type we intend
5849   // for the shuffle.
5850   for (auto &Src : Sources) {
5851     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5852     if (SrcEltTy == SmallestEltTy)
5853       continue;
5854     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5855     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5856     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5857     Src.WindowBase *= Src.WindowScale;
5858   }
5859 
5860   // Final sanity check before we try to actually produce a shuffle.
5861   DEBUG(
5862     for (auto Src : Sources)
5863       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5864   );
5865 
5866   // The stars all align, our next step is to produce the mask for the shuffle.
5867   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5868   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5869   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5870     SDValue Entry = Op.getOperand(i);
5871     if (Entry.isUndef())
5872       continue;
5873 
5874     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5875     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5876 
5877     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5878     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5879     // segment.
5880     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5881     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5882                                VT.getVectorElementType().getSizeInBits());
5883     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5884 
5885     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5886     // starting at the appropriate offset.
5887     int *LaneMask = &Mask[i * ResMultiplier];
5888 
5889     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5890     ExtractBase += NumElts * (Src - Sources.begin());
5891     for (int j = 0; j < LanesDefined; ++j)
5892       LaneMask[j] = ExtractBase + j;
5893   }
5894 
5895   // Final check before we try to produce nonsense...
5896   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5897     return SDValue();
5898 
5899   // We can't handle more than two sources. This should have already
5900   // been checked before this point.
5901   assert(Sources.size() <= 2 && "Too many sources!");
5902 
5903   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5904   for (unsigned i = 0; i < Sources.size(); ++i)
5905     ShuffleOps[i] = Sources[i].ShuffleVec;
5906 
5907   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5908                                          ShuffleOps[1], &Mask[0]);
5909   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5910 }
5911 
5912 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5913 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5914 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5915 /// are assumed to be legal.
5916 bool
5917 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5918                                       EVT VT) const {
5919   if (VT.getVectorNumElements() == 4 &&
5920       (VT.is128BitVector() || VT.is64BitVector())) {
5921     unsigned PFIndexes[4];
5922     for (unsigned i = 0; i != 4; ++i) {
5923       if (M[i] < 0)
5924         PFIndexes[i] = 8;
5925       else
5926         PFIndexes[i] = M[i];
5927     }
5928 
5929     // Compute the index in the perfect shuffle table.
5930     unsigned PFTableIndex =
5931       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5932     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5933     unsigned Cost = (PFEntry >> 30);
5934 
5935     if (Cost <= 4)
5936       return true;
5937   }
5938 
5939   bool ReverseVEXT, isV_UNDEF;
5940   unsigned Imm, WhichResult;
5941 
5942   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5943   return (EltSize >= 32 ||
5944           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5945           isVREVMask(M, VT, 64) ||
5946           isVREVMask(M, VT, 32) ||
5947           isVREVMask(M, VT, 16) ||
5948           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5949           isVTBLMask(M, VT) ||
5950           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5951           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5952 }
5953 
5954 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5955 /// the specified operations to build the shuffle.
5956 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5957                                       SDValue RHS, SelectionDAG &DAG,
5958                                       SDLoc dl) {
5959   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5960   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5961   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5962 
5963   enum {
5964     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5965     OP_VREV,
5966     OP_VDUP0,
5967     OP_VDUP1,
5968     OP_VDUP2,
5969     OP_VDUP3,
5970     OP_VEXT1,
5971     OP_VEXT2,
5972     OP_VEXT3,
5973     OP_VUZPL, // VUZP, left result
5974     OP_VUZPR, // VUZP, right result
5975     OP_VZIPL, // VZIP, left result
5976     OP_VZIPR, // VZIP, right result
5977     OP_VTRNL, // VTRN, left result
5978     OP_VTRNR  // VTRN, right result
5979   };
5980 
5981   if (OpNum == OP_COPY) {
5982     if (LHSID == (1*9+2)*9+3) return LHS;
5983     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5984     return RHS;
5985   }
5986 
5987   SDValue OpLHS, OpRHS;
5988   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5989   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5990   EVT VT = OpLHS.getValueType();
5991 
5992   switch (OpNum) {
5993   default: llvm_unreachable("Unknown shuffle opcode!");
5994   case OP_VREV:
5995     // VREV divides the vector in half and swaps within the half.
5996     if (VT.getVectorElementType() == MVT::i32 ||
5997         VT.getVectorElementType() == MVT::f32)
5998       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5999     // vrev <4 x i16> -> VREV32
6000     if (VT.getVectorElementType() == MVT::i16)
6001       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6002     // vrev <4 x i8> -> VREV16
6003     assert(VT.getVectorElementType() == MVT::i8);
6004     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6005   case OP_VDUP0:
6006   case OP_VDUP1:
6007   case OP_VDUP2:
6008   case OP_VDUP3:
6009     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6010                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6011   case OP_VEXT1:
6012   case OP_VEXT2:
6013   case OP_VEXT3:
6014     return DAG.getNode(ARMISD::VEXT, dl, VT,
6015                        OpLHS, OpRHS,
6016                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6017   case OP_VUZPL:
6018   case OP_VUZPR:
6019     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6020                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6021   case OP_VZIPL:
6022   case OP_VZIPR:
6023     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6024                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6025   case OP_VTRNL:
6026   case OP_VTRNR:
6027     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6028                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6029   }
6030 }
6031 
6032 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6033                                        ArrayRef<int> ShuffleMask,
6034                                        SelectionDAG &DAG) {
6035   // Check to see if we can use the VTBL instruction.
6036   SDValue V1 = Op.getOperand(0);
6037   SDValue V2 = Op.getOperand(1);
6038   SDLoc DL(Op);
6039 
6040   SmallVector<SDValue, 8> VTBLMask;
6041   for (ArrayRef<int>::iterator
6042          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6043     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6044 
6045   if (V2.getNode()->isUndef())
6046     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6047                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
6048 
6049   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6050                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
6051 }
6052 
6053 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6054                                                       SelectionDAG &DAG) {
6055   SDLoc DL(Op);
6056   SDValue OpLHS = Op.getOperand(0);
6057   EVT VT = OpLHS.getValueType();
6058 
6059   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6060          "Expect an v8i16/v16i8 type");
6061   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6062   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6063   // extract the first 8 bytes into the top double word and the last 8 bytes
6064   // into the bottom double word. The v8i16 case is similar.
6065   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6066   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6067                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6068 }
6069 
6070 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6071   SDValue V1 = Op.getOperand(0);
6072   SDValue V2 = Op.getOperand(1);
6073   SDLoc dl(Op);
6074   EVT VT = Op.getValueType();
6075   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6076 
6077   // Convert shuffles that are directly supported on NEON to target-specific
6078   // DAG nodes, instead of keeping them as shuffles and matching them again
6079   // during code selection.  This is more efficient and avoids the possibility
6080   // of inconsistencies between legalization and selection.
6081   // FIXME: floating-point vectors should be canonicalized to integer vectors
6082   // of the same time so that they get CSEd properly.
6083   ArrayRef<int> ShuffleMask = SVN->getMask();
6084 
6085   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6086   if (EltSize <= 32) {
6087     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
6088       int Lane = SVN->getSplatIndex();
6089       // If this is undef splat, generate it via "just" vdup, if possible.
6090       if (Lane == -1) Lane = 0;
6091 
6092       // Test if V1 is a SCALAR_TO_VECTOR.
6093       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6094         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6095       }
6096       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6097       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6098       // reaches it).
6099       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6100           !isa<ConstantSDNode>(V1.getOperand(0))) {
6101         bool IsScalarToVector = true;
6102         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6103           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
6104             IsScalarToVector = false;
6105             break;
6106           }
6107         if (IsScalarToVector)
6108           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6109       }
6110       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6111                          DAG.getConstant(Lane, dl, MVT::i32));
6112     }
6113 
6114     bool ReverseVEXT;
6115     unsigned Imm;
6116     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6117       if (ReverseVEXT)
6118         std::swap(V1, V2);
6119       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6120                          DAG.getConstant(Imm, dl, MVT::i32));
6121     }
6122 
6123     if (isVREVMask(ShuffleMask, VT, 64))
6124       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6125     if (isVREVMask(ShuffleMask, VT, 32))
6126       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6127     if (isVREVMask(ShuffleMask, VT, 16))
6128       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6129 
6130     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6131       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6132                          DAG.getConstant(Imm, dl, MVT::i32));
6133     }
6134 
6135     // Check for Neon shuffles that modify both input vectors in place.
6136     // If both results are used, i.e., if there are two shuffles with the same
6137     // source operands and with masks corresponding to both results of one of
6138     // these operations, DAG memoization will ensure that a single node is
6139     // used for both shuffles.
6140     unsigned WhichResult;
6141     bool isV_UNDEF;
6142     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6143             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6144       if (isV_UNDEF)
6145         V2 = V1;
6146       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6147           .getValue(WhichResult);
6148     }
6149 
6150     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6151     // shuffles that produce a result larger than their operands with:
6152     //   shuffle(concat(v1, undef), concat(v2, undef))
6153     // ->
6154     //   shuffle(concat(v1, v2), undef)
6155     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6156     //
6157     // This is useful in the general case, but there are special cases where
6158     // native shuffles produce larger results: the two-result ops.
6159     //
6160     // Look through the concat when lowering them:
6161     //   shuffle(concat(v1, v2), undef)
6162     // ->
6163     //   concat(VZIP(v1, v2):0, :1)
6164     //
6165     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6166       SDValue SubV1 = V1->getOperand(0);
6167       SDValue SubV2 = V1->getOperand(1);
6168       EVT SubVT = SubV1.getValueType();
6169 
6170       // We expect these to have been canonicalized to -1.
6171       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6172         return i < (int)VT.getVectorNumElements();
6173       }) && "Unexpected shuffle index into UNDEF operand!");
6174 
6175       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6176               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6177         if (isV_UNDEF)
6178           SubV2 = SubV1;
6179         assert((WhichResult == 0) &&
6180                "In-place shuffle of concat can only have one result!");
6181         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6182                                   SubV1, SubV2);
6183         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6184                            Res.getValue(1));
6185       }
6186     }
6187   }
6188 
6189   // If the shuffle is not directly supported and it has 4 elements, use
6190   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6191   unsigned NumElts = VT.getVectorNumElements();
6192   if (NumElts == 4) {
6193     unsigned PFIndexes[4];
6194     for (unsigned i = 0; i != 4; ++i) {
6195       if (ShuffleMask[i] < 0)
6196         PFIndexes[i] = 8;
6197       else
6198         PFIndexes[i] = ShuffleMask[i];
6199     }
6200 
6201     // Compute the index in the perfect shuffle table.
6202     unsigned PFTableIndex =
6203       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6204     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6205     unsigned Cost = (PFEntry >> 30);
6206 
6207     if (Cost <= 4)
6208       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6209   }
6210 
6211   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6212   if (EltSize >= 32) {
6213     // Do the expansion with floating-point types, since that is what the VFP
6214     // registers are defined to use, and since i64 is not legal.
6215     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6216     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6217     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6218     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6219     SmallVector<SDValue, 8> Ops;
6220     for (unsigned i = 0; i < NumElts; ++i) {
6221       if (ShuffleMask[i] < 0)
6222         Ops.push_back(DAG.getUNDEF(EltVT));
6223       else
6224         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6225                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6226                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6227                                                   dl, MVT::i32)));
6228     }
6229     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6230     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6231   }
6232 
6233   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6234     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6235 
6236   if (VT == MVT::v8i8)
6237     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6238       return NewOp;
6239 
6240   return SDValue();
6241 }
6242 
6243 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6244   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6245   SDValue Lane = Op.getOperand(2);
6246   if (!isa<ConstantSDNode>(Lane))
6247     return SDValue();
6248 
6249   return Op;
6250 }
6251 
6252 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6253   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6254   SDValue Lane = Op.getOperand(1);
6255   if (!isa<ConstantSDNode>(Lane))
6256     return SDValue();
6257 
6258   SDValue Vec = Op.getOperand(0);
6259   if (Op.getValueType() == MVT::i32 &&
6260       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6261     SDLoc dl(Op);
6262     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6263   }
6264 
6265   return Op;
6266 }
6267 
6268 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6269   // The only time a CONCAT_VECTORS operation can have legal types is when
6270   // two 64-bit vectors are concatenated to a 128-bit vector.
6271   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6272          "unexpected CONCAT_VECTORS");
6273   SDLoc dl(Op);
6274   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6275   SDValue Op0 = Op.getOperand(0);
6276   SDValue Op1 = Op.getOperand(1);
6277   if (Op0.getOpcode() != ISD::UNDEF)
6278     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6279                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6280                       DAG.getIntPtrConstant(0, dl));
6281   if (Op1.getOpcode() != ISD::UNDEF)
6282     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6283                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6284                       DAG.getIntPtrConstant(1, dl));
6285   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6286 }
6287 
6288 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6289 /// element has been zero/sign-extended, depending on the isSigned parameter,
6290 /// from an integer type half its size.
6291 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6292                                    bool isSigned) {
6293   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6294   EVT VT = N->getValueType(0);
6295   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6296     SDNode *BVN = N->getOperand(0).getNode();
6297     if (BVN->getValueType(0) != MVT::v4i32 ||
6298         BVN->getOpcode() != ISD::BUILD_VECTOR)
6299       return false;
6300     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6301     unsigned HiElt = 1 - LoElt;
6302     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6303     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6304     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6305     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6306     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6307       return false;
6308     if (isSigned) {
6309       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6310           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6311         return true;
6312     } else {
6313       if (Hi0->isNullValue() && Hi1->isNullValue())
6314         return true;
6315     }
6316     return false;
6317   }
6318 
6319   if (N->getOpcode() != ISD::BUILD_VECTOR)
6320     return false;
6321 
6322   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6323     SDNode *Elt = N->getOperand(i).getNode();
6324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6325       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6326       unsigned HalfSize = EltSize / 2;
6327       if (isSigned) {
6328         if (!isIntN(HalfSize, C->getSExtValue()))
6329           return false;
6330       } else {
6331         if (!isUIntN(HalfSize, C->getZExtValue()))
6332           return false;
6333       }
6334       continue;
6335     }
6336     return false;
6337   }
6338 
6339   return true;
6340 }
6341 
6342 /// isSignExtended - Check if a node is a vector value that is sign-extended
6343 /// or a constant BUILD_VECTOR with sign-extended elements.
6344 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6345   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6346     return true;
6347   if (isExtendedBUILD_VECTOR(N, DAG, true))
6348     return true;
6349   return false;
6350 }
6351 
6352 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6353 /// or a constant BUILD_VECTOR with zero-extended elements.
6354 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6355   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6356     return true;
6357   if (isExtendedBUILD_VECTOR(N, DAG, false))
6358     return true;
6359   return false;
6360 }
6361 
6362 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6363   if (OrigVT.getSizeInBits() >= 64)
6364     return OrigVT;
6365 
6366   assert(OrigVT.isSimple() && "Expecting a simple value type");
6367 
6368   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6369   switch (OrigSimpleTy) {
6370   default: llvm_unreachable("Unexpected Vector Type");
6371   case MVT::v2i8:
6372   case MVT::v2i16:
6373      return MVT::v2i32;
6374   case MVT::v4i8:
6375     return  MVT::v4i16;
6376   }
6377 }
6378 
6379 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6380 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6381 /// We insert the required extension here to get the vector to fill a D register.
6382 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6383                                             const EVT &OrigTy,
6384                                             const EVT &ExtTy,
6385                                             unsigned ExtOpcode) {
6386   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6387   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6388   // 64-bits we need to insert a new extension so that it will be 64-bits.
6389   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6390   if (OrigTy.getSizeInBits() >= 64)
6391     return N;
6392 
6393   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6394   EVT NewVT = getExtensionTo64Bits(OrigTy);
6395 
6396   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6397 }
6398 
6399 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6400 /// does not do any sign/zero extension. If the original vector is less
6401 /// than 64 bits, an appropriate extension will be added after the load to
6402 /// reach a total size of 64 bits. We have to add the extension separately
6403 /// because ARM does not have a sign/zero extending load for vectors.
6404 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6405   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6406 
6407   // The load already has the right type.
6408   if (ExtendedTy == LD->getMemoryVT())
6409     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6410                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6411                 LD->isNonTemporal(), LD->isInvariant(),
6412                 LD->getAlignment());
6413 
6414   // We need to create a zextload/sextload. We cannot just create a load
6415   // followed by a zext/zext node because LowerMUL is also run during normal
6416   // operation legalization where we can't create illegal types.
6417   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6418                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6419                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6420                         LD->isNonTemporal(), LD->getAlignment());
6421 }
6422 
6423 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6424 /// extending load, or BUILD_VECTOR with extended elements, return the
6425 /// unextended value. The unextended vector should be 64 bits so that it can
6426 /// be used as an operand to a VMULL instruction. If the original vector size
6427 /// before extension is less than 64 bits we add a an extension to resize
6428 /// the vector to 64 bits.
6429 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6430   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6431     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6432                                         N->getOperand(0)->getValueType(0),
6433                                         N->getValueType(0),
6434                                         N->getOpcode());
6435 
6436   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6437     return SkipLoadExtensionForVMULL(LD, DAG);
6438 
6439   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6440   // have been legalized as a BITCAST from v4i32.
6441   if (N->getOpcode() == ISD::BITCAST) {
6442     SDNode *BVN = N->getOperand(0).getNode();
6443     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6444            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6445     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6446     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6447                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6448   }
6449   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6450   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6451   EVT VT = N->getValueType(0);
6452   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6453   unsigned NumElts = VT.getVectorNumElements();
6454   MVT TruncVT = MVT::getIntegerVT(EltSize);
6455   SmallVector<SDValue, 8> Ops;
6456   SDLoc dl(N);
6457   for (unsigned i = 0; i != NumElts; ++i) {
6458     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6459     const APInt &CInt = C->getAPIntValue();
6460     // Element types smaller than 32 bits are not legal, so use i32 elements.
6461     // The values are implicitly truncated so sext vs. zext doesn't matter.
6462     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6463   }
6464   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6465                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6466 }
6467 
6468 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6469   unsigned Opcode = N->getOpcode();
6470   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6471     SDNode *N0 = N->getOperand(0).getNode();
6472     SDNode *N1 = N->getOperand(1).getNode();
6473     return N0->hasOneUse() && N1->hasOneUse() &&
6474       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6475   }
6476   return false;
6477 }
6478 
6479 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6480   unsigned Opcode = N->getOpcode();
6481   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6482     SDNode *N0 = N->getOperand(0).getNode();
6483     SDNode *N1 = N->getOperand(1).getNode();
6484     return N0->hasOneUse() && N1->hasOneUse() &&
6485       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6486   }
6487   return false;
6488 }
6489 
6490 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6491   // Multiplications are only custom-lowered for 128-bit vectors so that
6492   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6493   EVT VT = Op.getValueType();
6494   assert(VT.is128BitVector() && VT.isInteger() &&
6495          "unexpected type for custom-lowering ISD::MUL");
6496   SDNode *N0 = Op.getOperand(0).getNode();
6497   SDNode *N1 = Op.getOperand(1).getNode();
6498   unsigned NewOpc = 0;
6499   bool isMLA = false;
6500   bool isN0SExt = isSignExtended(N0, DAG);
6501   bool isN1SExt = isSignExtended(N1, DAG);
6502   if (isN0SExt && isN1SExt)
6503     NewOpc = ARMISD::VMULLs;
6504   else {
6505     bool isN0ZExt = isZeroExtended(N0, DAG);
6506     bool isN1ZExt = isZeroExtended(N1, DAG);
6507     if (isN0ZExt && isN1ZExt)
6508       NewOpc = ARMISD::VMULLu;
6509     else if (isN1SExt || isN1ZExt) {
6510       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6511       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6512       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6513         NewOpc = ARMISD::VMULLs;
6514         isMLA = true;
6515       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6516         NewOpc = ARMISD::VMULLu;
6517         isMLA = true;
6518       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6519         std::swap(N0, N1);
6520         NewOpc = ARMISD::VMULLu;
6521         isMLA = true;
6522       }
6523     }
6524 
6525     if (!NewOpc) {
6526       if (VT == MVT::v2i64)
6527         // Fall through to expand this.  It is not legal.
6528         return SDValue();
6529       else
6530         // Other vector multiplications are legal.
6531         return Op;
6532     }
6533   }
6534 
6535   // Legalize to a VMULL instruction.
6536   SDLoc DL(Op);
6537   SDValue Op0;
6538   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6539   if (!isMLA) {
6540     Op0 = SkipExtensionForVMULL(N0, DAG);
6541     assert(Op0.getValueType().is64BitVector() &&
6542            Op1.getValueType().is64BitVector() &&
6543            "unexpected types for extended operands to VMULL");
6544     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6545   }
6546 
6547   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6548   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6549   //   vmull q0, d4, d6
6550   //   vmlal q0, d5, d6
6551   // is faster than
6552   //   vaddl q0, d4, d5
6553   //   vmovl q1, d6
6554   //   vmul  q0, q0, q1
6555   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6556   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6557   EVT Op1VT = Op1.getValueType();
6558   return DAG.getNode(N0->getOpcode(), DL, VT,
6559                      DAG.getNode(NewOpc, DL, VT,
6560                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6561                      DAG.getNode(NewOpc, DL, VT,
6562                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6563 }
6564 
6565 static SDValue
6566 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6567   // TODO: Should this propagate fast-math-flags?
6568 
6569   // Convert to float
6570   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6571   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6572   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6573   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6574   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6575   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6576   // Get reciprocal estimate.
6577   // float4 recip = vrecpeq_f32(yf);
6578   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6579                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6580                    Y);
6581   // Because char has a smaller range than uchar, we can actually get away
6582   // without any newton steps.  This requires that we use a weird bias
6583   // of 0xb000, however (again, this has been exhaustively tested).
6584   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6585   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6586   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6587   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
6588   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6589   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6590   // Convert back to short.
6591   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6592   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6593   return X;
6594 }
6595 
6596 static SDValue
6597 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6598   // TODO: Should this propagate fast-math-flags?
6599 
6600   SDValue N2;
6601   // Convert to float.
6602   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6603   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6604   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6605   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6606   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6607   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6608 
6609   // Use reciprocal estimate and one refinement step.
6610   // float4 recip = vrecpeq_f32(yf);
6611   // recip *= vrecpsq_f32(yf, recip);
6612   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6613                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6614                    N1);
6615   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6616                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6617                    N1, N2);
6618   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6619   // Because short has a smaller range than ushort, we can actually get away
6620   // with only a single newton step.  This requires that we use a weird bias
6621   // of 89, however (again, this has been exhaustively tested).
6622   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6623   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6624   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6625   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
6626   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6627   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6628   // Convert back to integer and return.
6629   // return vmovn_s32(vcvt_s32_f32(result));
6630   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6631   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6632   return N0;
6633 }
6634 
6635 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6636   EVT VT = Op.getValueType();
6637   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6638          "unexpected type for custom-lowering ISD::SDIV");
6639 
6640   SDLoc dl(Op);
6641   SDValue N0 = Op.getOperand(0);
6642   SDValue N1 = Op.getOperand(1);
6643   SDValue N2, N3;
6644 
6645   if (VT == MVT::v8i8) {
6646     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6647     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6648 
6649     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6650                      DAG.getIntPtrConstant(4, dl));
6651     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6652                      DAG.getIntPtrConstant(4, dl));
6653     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6654                      DAG.getIntPtrConstant(0, dl));
6655     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6656                      DAG.getIntPtrConstant(0, dl));
6657 
6658     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6659     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6660 
6661     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6662     N0 = LowerCONCAT_VECTORS(N0, DAG);
6663 
6664     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6665     return N0;
6666   }
6667   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6668 }
6669 
6670 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6671   // TODO: Should this propagate fast-math-flags?
6672   EVT VT = Op.getValueType();
6673   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6674          "unexpected type for custom-lowering ISD::UDIV");
6675 
6676   SDLoc dl(Op);
6677   SDValue N0 = Op.getOperand(0);
6678   SDValue N1 = Op.getOperand(1);
6679   SDValue N2, N3;
6680 
6681   if (VT == MVT::v8i8) {
6682     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6683     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6684 
6685     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6686                      DAG.getIntPtrConstant(4, dl));
6687     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6688                      DAG.getIntPtrConstant(4, dl));
6689     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6690                      DAG.getIntPtrConstant(0, dl));
6691     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6692                      DAG.getIntPtrConstant(0, dl));
6693 
6694     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6695     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6696 
6697     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6698     N0 = LowerCONCAT_VECTORS(N0, DAG);
6699 
6700     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6701                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6702                                      MVT::i32),
6703                      N0);
6704     return N0;
6705   }
6706 
6707   // v4i16 sdiv ... Convert to float.
6708   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6709   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6710   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6711   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6712   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6713   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6714 
6715   // Use reciprocal estimate and two refinement steps.
6716   // float4 recip = vrecpeq_f32(yf);
6717   // recip *= vrecpsq_f32(yf, recip);
6718   // recip *= vrecpsq_f32(yf, recip);
6719   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6720                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6721                    BN1);
6722   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6723                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6724                    BN1, N2);
6725   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6726   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6727                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6728                    BN1, N2);
6729   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6730   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6731   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6732   // and that it will never cause us to return an answer too large).
6733   // float4 result = as_float4(as_int4(xf*recip) + 2);
6734   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6735   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6736   N1 = DAG.getConstant(2, dl, MVT::v4i32);
6737   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6738   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6739   // Convert back to integer and return.
6740   // return vmovn_u32(vcvt_s32_f32(result));
6741   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6742   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6743   return N0;
6744 }
6745 
6746 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6747   EVT VT = Op.getNode()->getValueType(0);
6748   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6749 
6750   unsigned Opc;
6751   bool ExtraOp = false;
6752   switch (Op.getOpcode()) {
6753   default: llvm_unreachable("Invalid code");
6754   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6755   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6756   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6757   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6758   }
6759 
6760   if (!ExtraOp)
6761     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6762                        Op.getOperand(1));
6763   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6764                      Op.getOperand(1), Op.getOperand(2));
6765 }
6766 
6767 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6768   assert(Subtarget->isTargetDarwin());
6769 
6770   // For iOS, we want to call an alternative entry point: __sincos_stret,
6771   // return values are passed via sret.
6772   SDLoc dl(Op);
6773   SDValue Arg = Op.getOperand(0);
6774   EVT ArgVT = Arg.getValueType();
6775   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6776   auto PtrVT = getPointerTy(DAG.getDataLayout());
6777 
6778   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6780 
6781   // Pair of floats / doubles used to pass the result.
6782   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6783   auto &DL = DAG.getDataLayout();
6784 
6785   ArgListTy Args;
6786   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6787   SDValue SRet;
6788   if (ShouldUseSRet) {
6789     // Create stack object for sret.
6790     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6791     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6792     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6793     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6794 
6795     ArgListEntry Entry;
6796     Entry.Node = SRet;
6797     Entry.Ty = RetTy->getPointerTo();
6798     Entry.isSExt = false;
6799     Entry.isZExt = false;
6800     Entry.isSRet = true;
6801     Args.push_back(Entry);
6802     RetTy = Type::getVoidTy(*DAG.getContext());
6803   }
6804 
6805   ArgListEntry Entry;
6806   Entry.Node = Arg;
6807   Entry.Ty = ArgTy;
6808   Entry.isSExt = false;
6809   Entry.isZExt = false;
6810   Args.push_back(Entry);
6811 
6812   const char *LibcallName =
6813       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6814   RTLIB::Libcall LC =
6815       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6816   CallingConv::ID CC = getLibcallCallingConv(LC);
6817   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6818 
6819   TargetLowering::CallLoweringInfo CLI(DAG);
6820   CLI.setDebugLoc(dl)
6821       .setChain(DAG.getEntryNode())
6822       .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6823       .setDiscardResult(ShouldUseSRet);
6824   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6825 
6826   if (!ShouldUseSRet)
6827     return CallResult.first;
6828 
6829   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6830                                 MachinePointerInfo(), false, false, false, 0);
6831 
6832   // Address of cos field.
6833   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6834                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6835   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6836                                 MachinePointerInfo(), false, false, false, 0);
6837 
6838   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6839   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6840                      LoadSin.getValue(0), LoadCos.getValue(0));
6841 }
6842 
6843 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6844                                                   bool Signed,
6845                                                   SDValue &Chain) const {
6846   EVT VT = Op.getValueType();
6847   assert((VT == MVT::i32 || VT == MVT::i64) &&
6848          "unexpected type for custom lowering DIV");
6849   SDLoc dl(Op);
6850 
6851   const auto &DL = DAG.getDataLayout();
6852   const auto &TLI = DAG.getTargetLoweringInfo();
6853 
6854   const char *Name = nullptr;
6855   if (Signed)
6856     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6857   else
6858     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6859 
6860   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6861 
6862   ARMTargetLowering::ArgListTy Args;
6863 
6864   for (auto AI : {1, 0}) {
6865     ArgListEntry Arg;
6866     Arg.Node = Op.getOperand(AI);
6867     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6868     Args.push_back(Arg);
6869   }
6870 
6871   CallLoweringInfo CLI(DAG);
6872   CLI.setDebugLoc(dl)
6873     .setChain(Chain)
6874     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6875                ES, std::move(Args), 0);
6876 
6877   return LowerCallTo(CLI).first;
6878 }
6879 
6880 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6881                                             bool Signed) const {
6882   assert(Op.getValueType() == MVT::i32 &&
6883          "unexpected type for custom lowering DIV");
6884   SDLoc dl(Op);
6885 
6886   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6887                                DAG.getEntryNode(), Op.getOperand(1));
6888 
6889   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6890 }
6891 
6892 void ARMTargetLowering::ExpandDIV_Windows(
6893     SDValue Op, SelectionDAG &DAG, bool Signed,
6894     SmallVectorImpl<SDValue> &Results) const {
6895   const auto &DL = DAG.getDataLayout();
6896   const auto &TLI = DAG.getTargetLoweringInfo();
6897 
6898   assert(Op.getValueType() == MVT::i64 &&
6899          "unexpected type for custom lowering DIV");
6900   SDLoc dl(Op);
6901 
6902   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6903                            DAG.getConstant(0, dl, MVT::i32));
6904   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6905                            DAG.getConstant(1, dl, MVT::i32));
6906   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6907 
6908   SDValue DBZCHK =
6909       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6910 
6911   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6912 
6913   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6914   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6915                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6916   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6917 
6918   Results.push_back(Lower);
6919   Results.push_back(Upper);
6920 }
6921 
6922 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6923   // Monotonic load/store is legal for all targets
6924   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6925     return Op;
6926 
6927   // Acquire/Release load/store is not legal for targets without a
6928   // dmb or equivalent available.
6929   return SDValue();
6930 }
6931 
6932 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6933                                     SmallVectorImpl<SDValue> &Results,
6934                                     SelectionDAG &DAG,
6935                                     const ARMSubtarget *Subtarget) {
6936   SDLoc DL(N);
6937   // Under Power Management extensions, the cycle-count is:
6938   //    mrc p15, #0, <Rt>, c9, c13, #0
6939   SDValue Ops[] = { N->getOperand(0), // Chain
6940                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6941                     DAG.getConstant(15, DL, MVT::i32),
6942                     DAG.getConstant(0, DL, MVT::i32),
6943                     DAG.getConstant(9, DL, MVT::i32),
6944                     DAG.getConstant(13, DL, MVT::i32),
6945                     DAG.getConstant(0, DL, MVT::i32)
6946   };
6947 
6948   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6949                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6950   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6951                                 DAG.getConstant(0, DL, MVT::i32)));
6952   Results.push_back(Cycles32.getValue(1));
6953 }
6954 
6955 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6956   switch (Op.getOpcode()) {
6957   default: llvm_unreachable("Don't know how to custom lower this!");
6958   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6959   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6960   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6961   case ISD::GlobalAddress:
6962     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6963     default: llvm_unreachable("unknown object format");
6964     case Triple::COFF:
6965       return LowerGlobalAddressWindows(Op, DAG);
6966     case Triple::ELF:
6967       return LowerGlobalAddressELF(Op, DAG);
6968     case Triple::MachO:
6969       return LowerGlobalAddressDarwin(Op, DAG);
6970     }
6971   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6972   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6973   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6974   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6975   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6976   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6977   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6978   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6979   case ISD::SINT_TO_FP:
6980   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6981   case ISD::FP_TO_SINT:
6982   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6983   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6984   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6985   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6986   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6987   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6988   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6989   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6990                                                                Subtarget);
6991   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6992   case ISD::SHL:
6993   case ISD::SRL:
6994   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6995   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6996   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6997   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6998   case ISD::SRL_PARTS:
6999   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7000   case ISD::CTTZ:
7001   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7002   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7003   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7004   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7005   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7006   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7007   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7008   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7009   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7010   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7011   case ISD::MUL:           return LowerMUL(Op, DAG);
7012   case ISD::SDIV:          return LowerSDIV(Op, DAG);
7013   case ISD::UDIV:          return LowerUDIV(Op, DAG);
7014   case ISD::ADDC:
7015   case ISD::ADDE:
7016   case ISD::SUBC:
7017   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7018   case ISD::SADDO:
7019   case ISD::UADDO:
7020   case ISD::SSUBO:
7021   case ISD::USUBO:
7022     return LowerXALUO(Op, DAG);
7023   case ISD::ATOMIC_LOAD:
7024   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7025   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7026   case ISD::SDIVREM:
7027   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7028   case ISD::DYNAMIC_STACKALLOC:
7029     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7030       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7031     llvm_unreachable("Don't know how to custom lower this!");
7032   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7033   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7034   case ARMISD::WIN__DBZCHK: return SDValue();
7035   }
7036 }
7037 
7038 /// ReplaceNodeResults - Replace the results of node with an illegal result
7039 /// type with new values built out of custom code.
7040 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7041                                            SmallVectorImpl<SDValue> &Results,
7042                                            SelectionDAG &DAG) const {
7043   SDValue Res;
7044   switch (N->getOpcode()) {
7045   default:
7046     llvm_unreachable("Don't know how to custom expand this!");
7047   case ISD::READ_REGISTER:
7048     ExpandREAD_REGISTER(N, Results, DAG);
7049     break;
7050   case ISD::BITCAST:
7051     Res = ExpandBITCAST(N, DAG);
7052     break;
7053   case ISD::SRL:
7054   case ISD::SRA:
7055     Res = Expand64BitShift(N, DAG, Subtarget);
7056     break;
7057   case ISD::SREM:
7058   case ISD::UREM:
7059     Res = LowerREM(N, DAG);
7060     break;
7061   case ISD::SDIVREM:
7062   case ISD::UDIVREM:
7063     Res = LowerDivRem(SDValue(N, 0), DAG);
7064     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7065     Results.push_back(Res.getValue(0));
7066     Results.push_back(Res.getValue(1));
7067     return;
7068   case ISD::READCYCLECOUNTER:
7069     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7070     return;
7071   case ISD::UDIV:
7072   case ISD::SDIV:
7073     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7074     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7075                              Results);
7076   }
7077   if (Res.getNode())
7078     Results.push_back(Res);
7079 }
7080 
7081 //===----------------------------------------------------------------------===//
7082 //                           ARM Scheduler Hooks
7083 //===----------------------------------------------------------------------===//
7084 
7085 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7086 /// registers the function context.
7087 void ARMTargetLowering::
7088 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
7089                        MachineBasicBlock *DispatchBB, int FI) const {
7090   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7091   DebugLoc dl = MI->getDebugLoc();
7092   MachineFunction *MF = MBB->getParent();
7093   MachineRegisterInfo *MRI = &MF->getRegInfo();
7094   MachineConstantPool *MCP = MF->getConstantPool();
7095   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7096   const Function *F = MF->getFunction();
7097 
7098   bool isThumb = Subtarget->isThumb();
7099   bool isThumb2 = Subtarget->isThumb2();
7100 
7101   unsigned PCLabelId = AFI->createPICLabelUId();
7102   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7103   ARMConstantPoolValue *CPV =
7104     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7105   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7106 
7107   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7108                                            : &ARM::GPRRegClass;
7109 
7110   // Grab constant pool and fixed stack memory operands.
7111   MachineMemOperand *CPMMO =
7112       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7113                                MachineMemOperand::MOLoad, 4, 4);
7114 
7115   MachineMemOperand *FIMMOSt =
7116       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7117                                MachineMemOperand::MOStore, 4, 4);
7118 
7119   // Load the address of the dispatch MBB into the jump buffer.
7120   if (isThumb2) {
7121     // Incoming value: jbuf
7122     //   ldr.n  r5, LCPI1_1
7123     //   orr    r5, r5, #1
7124     //   add    r5, pc
7125     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7126     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7127     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7128                    .addConstantPoolIndex(CPI)
7129                    .addMemOperand(CPMMO));
7130     // Set the low bit because of thumb mode.
7131     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7132     AddDefaultCC(
7133       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7134                      .addReg(NewVReg1, RegState::Kill)
7135                      .addImm(0x01)));
7136     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7137     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7138       .addReg(NewVReg2, RegState::Kill)
7139       .addImm(PCLabelId);
7140     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7141                    .addReg(NewVReg3, RegState::Kill)
7142                    .addFrameIndex(FI)
7143                    .addImm(36)  // &jbuf[1] :: pc
7144                    .addMemOperand(FIMMOSt));
7145   } else if (isThumb) {
7146     // Incoming value: jbuf
7147     //   ldr.n  r1, LCPI1_4
7148     //   add    r1, pc
7149     //   mov    r2, #1
7150     //   orrs   r1, r2
7151     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7152     //   str    r1, [r2]
7153     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7154     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7155                    .addConstantPoolIndex(CPI)
7156                    .addMemOperand(CPMMO));
7157     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7158     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7159       .addReg(NewVReg1, RegState::Kill)
7160       .addImm(PCLabelId);
7161     // Set the low bit because of thumb mode.
7162     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7163     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7164                    .addReg(ARM::CPSR, RegState::Define)
7165                    .addImm(1));
7166     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7167     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7168                    .addReg(ARM::CPSR, RegState::Define)
7169                    .addReg(NewVReg2, RegState::Kill)
7170                    .addReg(NewVReg3, RegState::Kill));
7171     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7172     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7173             .addFrameIndex(FI)
7174             .addImm(36); // &jbuf[1] :: pc
7175     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7176                    .addReg(NewVReg4, RegState::Kill)
7177                    .addReg(NewVReg5, RegState::Kill)
7178                    .addImm(0)
7179                    .addMemOperand(FIMMOSt));
7180   } else {
7181     // Incoming value: jbuf
7182     //   ldr  r1, LCPI1_1
7183     //   add  r1, pc, r1
7184     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7185     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7186     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7187                    .addConstantPoolIndex(CPI)
7188                    .addImm(0)
7189                    .addMemOperand(CPMMO));
7190     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7191     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7192                    .addReg(NewVReg1, RegState::Kill)
7193                    .addImm(PCLabelId));
7194     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7195                    .addReg(NewVReg2, RegState::Kill)
7196                    .addFrameIndex(FI)
7197                    .addImm(36)  // &jbuf[1] :: pc
7198                    .addMemOperand(FIMMOSt));
7199   }
7200 }
7201 
7202 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7203                                               MachineBasicBlock *MBB) const {
7204   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7205   DebugLoc dl = MI->getDebugLoc();
7206   MachineFunction *MF = MBB->getParent();
7207   MachineRegisterInfo *MRI = &MF->getRegInfo();
7208   MachineFrameInfo *MFI = MF->getFrameInfo();
7209   int FI = MFI->getFunctionContextIndex();
7210 
7211   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7212                                                         : &ARM::GPRnopcRegClass;
7213 
7214   // Get a mapping of the call site numbers to all of the landing pads they're
7215   // associated with.
7216   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7217   unsigned MaxCSNum = 0;
7218   MachineModuleInfo &MMI = MF->getMMI();
7219   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7220        ++BB) {
7221     if (!BB->isEHPad()) continue;
7222 
7223     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7224     // pad.
7225     for (MachineBasicBlock::iterator
7226            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7227       if (!II->isEHLabel()) continue;
7228 
7229       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7230       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7231 
7232       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7233       for (SmallVectorImpl<unsigned>::iterator
7234              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7235            CSI != CSE; ++CSI) {
7236         CallSiteNumToLPad[*CSI].push_back(&*BB);
7237         MaxCSNum = std::max(MaxCSNum, *CSI);
7238       }
7239       break;
7240     }
7241   }
7242 
7243   // Get an ordered list of the machine basic blocks for the jump table.
7244   std::vector<MachineBasicBlock*> LPadList;
7245   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7246   LPadList.reserve(CallSiteNumToLPad.size());
7247   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7248     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7249     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7250            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7251       LPadList.push_back(*II);
7252       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7253     }
7254   }
7255 
7256   assert(!LPadList.empty() &&
7257          "No landing pad destinations for the dispatch jump table!");
7258 
7259   // Create the jump table and associated information.
7260   MachineJumpTableInfo *JTI =
7261     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7262   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7263   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7264 
7265   // Create the MBBs for the dispatch code.
7266 
7267   // Shove the dispatch's address into the return slot in the function context.
7268   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7269   DispatchBB->setIsEHPad();
7270 
7271   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7272   unsigned trap_opcode;
7273   if (Subtarget->isThumb())
7274     trap_opcode = ARM::tTRAP;
7275   else
7276     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7277 
7278   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7279   DispatchBB->addSuccessor(TrapBB);
7280 
7281   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7282   DispatchBB->addSuccessor(DispContBB);
7283 
7284   // Insert and MBBs.
7285   MF->insert(MF->end(), DispatchBB);
7286   MF->insert(MF->end(), DispContBB);
7287   MF->insert(MF->end(), TrapBB);
7288 
7289   // Insert code into the entry block that creates and registers the function
7290   // context.
7291   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7292 
7293   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7294       MachinePointerInfo::getFixedStack(*MF, FI),
7295       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7296 
7297   MachineInstrBuilder MIB;
7298   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7299 
7300   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7301   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7302 
7303   // Add a register mask with no preserved registers.  This results in all
7304   // registers being marked as clobbered.
7305   MIB.addRegMask(RI.getNoPreservedMask());
7306 
7307   unsigned NumLPads = LPadList.size();
7308   if (Subtarget->isThumb2()) {
7309     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7310     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7311                    .addFrameIndex(FI)
7312                    .addImm(4)
7313                    .addMemOperand(FIMMOLd));
7314 
7315     if (NumLPads < 256) {
7316       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7317                      .addReg(NewVReg1)
7318                      .addImm(LPadList.size()));
7319     } else {
7320       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7321       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7322                      .addImm(NumLPads & 0xFFFF));
7323 
7324       unsigned VReg2 = VReg1;
7325       if ((NumLPads & 0xFFFF0000) != 0) {
7326         VReg2 = MRI->createVirtualRegister(TRC);
7327         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7328                        .addReg(VReg1)
7329                        .addImm(NumLPads >> 16));
7330       }
7331 
7332       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7333                      .addReg(NewVReg1)
7334                      .addReg(VReg2));
7335     }
7336 
7337     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7338       .addMBB(TrapBB)
7339       .addImm(ARMCC::HI)
7340       .addReg(ARM::CPSR);
7341 
7342     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7343     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7344                    .addJumpTableIndex(MJTI));
7345 
7346     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7347     AddDefaultCC(
7348       AddDefaultPred(
7349         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7350         .addReg(NewVReg3, RegState::Kill)
7351         .addReg(NewVReg1)
7352         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7353 
7354     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7355       .addReg(NewVReg4, RegState::Kill)
7356       .addReg(NewVReg1)
7357       .addJumpTableIndex(MJTI);
7358   } else if (Subtarget->isThumb()) {
7359     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7360     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7361                    .addFrameIndex(FI)
7362                    .addImm(1)
7363                    .addMemOperand(FIMMOLd));
7364 
7365     if (NumLPads < 256) {
7366       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7367                      .addReg(NewVReg1)
7368                      .addImm(NumLPads));
7369     } else {
7370       MachineConstantPool *ConstantPool = MF->getConstantPool();
7371       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7372       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7373 
7374       // MachineConstantPool wants an explicit alignment.
7375       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7376       if (Align == 0)
7377         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7378       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7379 
7380       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7381       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7382                      .addReg(VReg1, RegState::Define)
7383                      .addConstantPoolIndex(Idx));
7384       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7385                      .addReg(NewVReg1)
7386                      .addReg(VReg1));
7387     }
7388 
7389     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7390       .addMBB(TrapBB)
7391       .addImm(ARMCC::HI)
7392       .addReg(ARM::CPSR);
7393 
7394     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7395     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7396                    .addReg(ARM::CPSR, RegState::Define)
7397                    .addReg(NewVReg1)
7398                    .addImm(2));
7399 
7400     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7401     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7402                    .addJumpTableIndex(MJTI));
7403 
7404     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7405     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7406                    .addReg(ARM::CPSR, RegState::Define)
7407                    .addReg(NewVReg2, RegState::Kill)
7408                    .addReg(NewVReg3));
7409 
7410     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7411         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7412 
7413     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7414     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7415                    .addReg(NewVReg4, RegState::Kill)
7416                    .addImm(0)
7417                    .addMemOperand(JTMMOLd));
7418 
7419     unsigned NewVReg6 = NewVReg5;
7420     if (RelocM == Reloc::PIC_) {
7421       NewVReg6 = MRI->createVirtualRegister(TRC);
7422       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7423                      .addReg(ARM::CPSR, RegState::Define)
7424                      .addReg(NewVReg5, RegState::Kill)
7425                      .addReg(NewVReg3));
7426     }
7427 
7428     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7429       .addReg(NewVReg6, RegState::Kill)
7430       .addJumpTableIndex(MJTI);
7431   } else {
7432     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7433     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7434                    .addFrameIndex(FI)
7435                    .addImm(4)
7436                    .addMemOperand(FIMMOLd));
7437 
7438     if (NumLPads < 256) {
7439       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7440                      .addReg(NewVReg1)
7441                      .addImm(NumLPads));
7442     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7443       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7444       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7445                      .addImm(NumLPads & 0xFFFF));
7446 
7447       unsigned VReg2 = VReg1;
7448       if ((NumLPads & 0xFFFF0000) != 0) {
7449         VReg2 = MRI->createVirtualRegister(TRC);
7450         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7451                        .addReg(VReg1)
7452                        .addImm(NumLPads >> 16));
7453       }
7454 
7455       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7456                      .addReg(NewVReg1)
7457                      .addReg(VReg2));
7458     } else {
7459       MachineConstantPool *ConstantPool = MF->getConstantPool();
7460       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7461       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7462 
7463       // MachineConstantPool wants an explicit alignment.
7464       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7465       if (Align == 0)
7466         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7467       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7468 
7469       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7470       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7471                      .addReg(VReg1, RegState::Define)
7472                      .addConstantPoolIndex(Idx)
7473                      .addImm(0));
7474       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7475                      .addReg(NewVReg1)
7476                      .addReg(VReg1, RegState::Kill));
7477     }
7478 
7479     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7480       .addMBB(TrapBB)
7481       .addImm(ARMCC::HI)
7482       .addReg(ARM::CPSR);
7483 
7484     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7485     AddDefaultCC(
7486       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7487                      .addReg(NewVReg1)
7488                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7489     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7490     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7491                    .addJumpTableIndex(MJTI));
7492 
7493     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7494         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7495     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7496     AddDefaultPred(
7497       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7498       .addReg(NewVReg3, RegState::Kill)
7499       .addReg(NewVReg4)
7500       .addImm(0)
7501       .addMemOperand(JTMMOLd));
7502 
7503     if (RelocM == Reloc::PIC_) {
7504       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7505         .addReg(NewVReg5, RegState::Kill)
7506         .addReg(NewVReg4)
7507         .addJumpTableIndex(MJTI);
7508     } else {
7509       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7510         .addReg(NewVReg5, RegState::Kill)
7511         .addJumpTableIndex(MJTI);
7512     }
7513   }
7514 
7515   // Add the jump table entries as successors to the MBB.
7516   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7517   for (std::vector<MachineBasicBlock*>::iterator
7518          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7519     MachineBasicBlock *CurMBB = *I;
7520     if (SeenMBBs.insert(CurMBB).second)
7521       DispContBB->addSuccessor(CurMBB);
7522   }
7523 
7524   // N.B. the order the invoke BBs are processed in doesn't matter here.
7525   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7526   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7527   for (MachineBasicBlock *BB : InvokeBBs) {
7528 
7529     // Remove the landing pad successor from the invoke block and replace it
7530     // with the new dispatch block.
7531     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7532                                                   BB->succ_end());
7533     while (!Successors.empty()) {
7534       MachineBasicBlock *SMBB = Successors.pop_back_val();
7535       if (SMBB->isEHPad()) {
7536         BB->removeSuccessor(SMBB);
7537         MBBLPads.push_back(SMBB);
7538       }
7539     }
7540 
7541     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7542     BB->normalizeSuccProbs();
7543 
7544     // Find the invoke call and mark all of the callee-saved registers as
7545     // 'implicit defined' so that they're spilled. This prevents code from
7546     // moving instructions to before the EH block, where they will never be
7547     // executed.
7548     for (MachineBasicBlock::reverse_iterator
7549            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7550       if (!II->isCall()) continue;
7551 
7552       DenseMap<unsigned, bool> DefRegs;
7553       for (MachineInstr::mop_iterator
7554              OI = II->operands_begin(), OE = II->operands_end();
7555            OI != OE; ++OI) {
7556         if (!OI->isReg()) continue;
7557         DefRegs[OI->getReg()] = true;
7558       }
7559 
7560       MachineInstrBuilder MIB(*MF, &*II);
7561 
7562       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7563         unsigned Reg = SavedRegs[i];
7564         if (Subtarget->isThumb2() &&
7565             !ARM::tGPRRegClass.contains(Reg) &&
7566             !ARM::hGPRRegClass.contains(Reg))
7567           continue;
7568         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7569           continue;
7570         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7571           continue;
7572         if (!DefRegs[Reg])
7573           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7574       }
7575 
7576       break;
7577     }
7578   }
7579 
7580   // Mark all former landing pads as non-landing pads. The dispatch is the only
7581   // landing pad now.
7582   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7583          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7584     (*I)->setIsEHPad(false);
7585 
7586   // The instruction is gone now.
7587   MI->eraseFromParent();
7588 }
7589 
7590 static
7591 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7592   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7593        E = MBB->succ_end(); I != E; ++I)
7594     if (*I != Succ)
7595       return *I;
7596   llvm_unreachable("Expecting a BB with two successors!");
7597 }
7598 
7599 /// Return the load opcode for a given load size. If load size >= 8,
7600 /// neon opcode will be returned.
7601 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7602   if (LdSize >= 8)
7603     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7604                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7605   if (IsThumb1)
7606     return LdSize == 4 ? ARM::tLDRi
7607                        : LdSize == 2 ? ARM::tLDRHi
7608                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7609   if (IsThumb2)
7610     return LdSize == 4 ? ARM::t2LDR_POST
7611                        : LdSize == 2 ? ARM::t2LDRH_POST
7612                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7613   return LdSize == 4 ? ARM::LDR_POST_IMM
7614                      : LdSize == 2 ? ARM::LDRH_POST
7615                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7616 }
7617 
7618 /// Return the store opcode for a given store size. If store size >= 8,
7619 /// neon opcode will be returned.
7620 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7621   if (StSize >= 8)
7622     return StSize == 16 ? ARM::VST1q32wb_fixed
7623                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7624   if (IsThumb1)
7625     return StSize == 4 ? ARM::tSTRi
7626                        : StSize == 2 ? ARM::tSTRHi
7627                                      : StSize == 1 ? ARM::tSTRBi : 0;
7628   if (IsThumb2)
7629     return StSize == 4 ? ARM::t2STR_POST
7630                        : StSize == 2 ? ARM::t2STRH_POST
7631                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7632   return StSize == 4 ? ARM::STR_POST_IMM
7633                      : StSize == 2 ? ARM::STRH_POST
7634                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7635 }
7636 
7637 /// Emit a post-increment load operation with given size. The instructions
7638 /// will be added to BB at Pos.
7639 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7640                        const TargetInstrInfo *TII, DebugLoc dl,
7641                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7642                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7643   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7644   assert(LdOpc != 0 && "Should have a load opcode");
7645   if (LdSize >= 8) {
7646     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7647                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7648                        .addImm(0));
7649   } else if (IsThumb1) {
7650     // load + update AddrIn
7651     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7652                        .addReg(AddrIn).addImm(0));
7653     MachineInstrBuilder MIB =
7654         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7655     MIB = AddDefaultT1CC(MIB);
7656     MIB.addReg(AddrIn).addImm(LdSize);
7657     AddDefaultPred(MIB);
7658   } else if (IsThumb2) {
7659     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7660                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7661                        .addImm(LdSize));
7662   } else { // arm
7663     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7664                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7665                        .addReg(0).addImm(LdSize));
7666   }
7667 }
7668 
7669 /// Emit a post-increment store operation with given size. The instructions
7670 /// will be added to BB at Pos.
7671 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7672                        const TargetInstrInfo *TII, DebugLoc dl,
7673                        unsigned StSize, unsigned Data, unsigned AddrIn,
7674                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7675   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7676   assert(StOpc != 0 && "Should have a store opcode");
7677   if (StSize >= 8) {
7678     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7679                        .addReg(AddrIn).addImm(0).addReg(Data));
7680   } else if (IsThumb1) {
7681     // store + update AddrIn
7682     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7683                        .addReg(AddrIn).addImm(0));
7684     MachineInstrBuilder MIB =
7685         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7686     MIB = AddDefaultT1CC(MIB);
7687     MIB.addReg(AddrIn).addImm(StSize);
7688     AddDefaultPred(MIB);
7689   } else if (IsThumb2) {
7690     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7691                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7692   } else { // arm
7693     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7694                        .addReg(Data).addReg(AddrIn).addReg(0)
7695                        .addImm(StSize));
7696   }
7697 }
7698 
7699 MachineBasicBlock *
7700 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7701                                    MachineBasicBlock *BB) const {
7702   // This pseudo instruction has 3 operands: dst, src, size
7703   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7704   // Otherwise, we will generate unrolled scalar copies.
7705   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7706   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7707   MachineFunction::iterator It = ++BB->getIterator();
7708 
7709   unsigned dest = MI->getOperand(0).getReg();
7710   unsigned src = MI->getOperand(1).getReg();
7711   unsigned SizeVal = MI->getOperand(2).getImm();
7712   unsigned Align = MI->getOperand(3).getImm();
7713   DebugLoc dl = MI->getDebugLoc();
7714 
7715   MachineFunction *MF = BB->getParent();
7716   MachineRegisterInfo &MRI = MF->getRegInfo();
7717   unsigned UnitSize = 0;
7718   const TargetRegisterClass *TRC = nullptr;
7719   const TargetRegisterClass *VecTRC = nullptr;
7720 
7721   bool IsThumb1 = Subtarget->isThumb1Only();
7722   bool IsThumb2 = Subtarget->isThumb2();
7723 
7724   if (Align & 1) {
7725     UnitSize = 1;
7726   } else if (Align & 2) {
7727     UnitSize = 2;
7728   } else {
7729     // Check whether we can use NEON instructions.
7730     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7731         Subtarget->hasNEON()) {
7732       if ((Align % 16 == 0) && SizeVal >= 16)
7733         UnitSize = 16;
7734       else if ((Align % 8 == 0) && SizeVal >= 8)
7735         UnitSize = 8;
7736     }
7737     // Can't use NEON instructions.
7738     if (UnitSize == 0)
7739       UnitSize = 4;
7740   }
7741 
7742   // Select the correct opcode and register class for unit size load/store
7743   bool IsNeon = UnitSize >= 8;
7744   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7745   if (IsNeon)
7746     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7747                             : UnitSize == 8 ? &ARM::DPRRegClass
7748                                             : nullptr;
7749 
7750   unsigned BytesLeft = SizeVal % UnitSize;
7751   unsigned LoopSize = SizeVal - BytesLeft;
7752 
7753   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7754     // Use LDR and STR to copy.
7755     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7756     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7757     unsigned srcIn = src;
7758     unsigned destIn = dest;
7759     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7760       unsigned srcOut = MRI.createVirtualRegister(TRC);
7761       unsigned destOut = MRI.createVirtualRegister(TRC);
7762       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7763       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7764                  IsThumb1, IsThumb2);
7765       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7766                  IsThumb1, IsThumb2);
7767       srcIn = srcOut;
7768       destIn = destOut;
7769     }
7770 
7771     // Handle the leftover bytes with LDRB and STRB.
7772     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7773     // [destOut] = STRB_POST(scratch, destIn, 1)
7774     for (unsigned i = 0; i < BytesLeft; i++) {
7775       unsigned srcOut = MRI.createVirtualRegister(TRC);
7776       unsigned destOut = MRI.createVirtualRegister(TRC);
7777       unsigned scratch = MRI.createVirtualRegister(TRC);
7778       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7779                  IsThumb1, IsThumb2);
7780       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7781                  IsThumb1, IsThumb2);
7782       srcIn = srcOut;
7783       destIn = destOut;
7784     }
7785     MI->eraseFromParent();   // The instruction is gone now.
7786     return BB;
7787   }
7788 
7789   // Expand the pseudo op to a loop.
7790   // thisMBB:
7791   //   ...
7792   //   movw varEnd, # --> with thumb2
7793   //   movt varEnd, #
7794   //   ldrcp varEnd, idx --> without thumb2
7795   //   fallthrough --> loopMBB
7796   // loopMBB:
7797   //   PHI varPhi, varEnd, varLoop
7798   //   PHI srcPhi, src, srcLoop
7799   //   PHI destPhi, dst, destLoop
7800   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7801   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7802   //   subs varLoop, varPhi, #UnitSize
7803   //   bne loopMBB
7804   //   fallthrough --> exitMBB
7805   // exitMBB:
7806   //   epilogue to handle left-over bytes
7807   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7808   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7809   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7810   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7811   MF->insert(It, loopMBB);
7812   MF->insert(It, exitMBB);
7813 
7814   // Transfer the remainder of BB and its successor edges to exitMBB.
7815   exitMBB->splice(exitMBB->begin(), BB,
7816                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7817   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7818 
7819   // Load an immediate to varEnd.
7820   unsigned varEnd = MRI.createVirtualRegister(TRC);
7821   if (Subtarget->useMovt(*MF)) {
7822     unsigned Vtmp = varEnd;
7823     if ((LoopSize & 0xFFFF0000) != 0)
7824       Vtmp = MRI.createVirtualRegister(TRC);
7825     AddDefaultPred(BuildMI(BB, dl,
7826                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7827                            Vtmp).addImm(LoopSize & 0xFFFF));
7828 
7829     if ((LoopSize & 0xFFFF0000) != 0)
7830       AddDefaultPred(BuildMI(BB, dl,
7831                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7832                              varEnd)
7833                          .addReg(Vtmp)
7834                          .addImm(LoopSize >> 16));
7835   } else {
7836     MachineConstantPool *ConstantPool = MF->getConstantPool();
7837     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7838     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7839 
7840     // MachineConstantPool wants an explicit alignment.
7841     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7842     if (Align == 0)
7843       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7844     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7845 
7846     if (IsThumb1)
7847       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7848           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7849     else
7850       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7851           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7852   }
7853   BB->addSuccessor(loopMBB);
7854 
7855   // Generate the loop body:
7856   //   varPhi = PHI(varLoop, varEnd)
7857   //   srcPhi = PHI(srcLoop, src)
7858   //   destPhi = PHI(destLoop, dst)
7859   MachineBasicBlock *entryBB = BB;
7860   BB = loopMBB;
7861   unsigned varLoop = MRI.createVirtualRegister(TRC);
7862   unsigned varPhi = MRI.createVirtualRegister(TRC);
7863   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7864   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7865   unsigned destLoop = MRI.createVirtualRegister(TRC);
7866   unsigned destPhi = MRI.createVirtualRegister(TRC);
7867 
7868   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7869     .addReg(varLoop).addMBB(loopMBB)
7870     .addReg(varEnd).addMBB(entryBB);
7871   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7872     .addReg(srcLoop).addMBB(loopMBB)
7873     .addReg(src).addMBB(entryBB);
7874   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7875     .addReg(destLoop).addMBB(loopMBB)
7876     .addReg(dest).addMBB(entryBB);
7877 
7878   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7879   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7880   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7881   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7882              IsThumb1, IsThumb2);
7883   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7884              IsThumb1, IsThumb2);
7885 
7886   // Decrement loop variable by UnitSize.
7887   if (IsThumb1) {
7888     MachineInstrBuilder MIB =
7889         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7890     MIB = AddDefaultT1CC(MIB);
7891     MIB.addReg(varPhi).addImm(UnitSize);
7892     AddDefaultPred(MIB);
7893   } else {
7894     MachineInstrBuilder MIB =
7895         BuildMI(*BB, BB->end(), dl,
7896                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7897     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7898     MIB->getOperand(5).setReg(ARM::CPSR);
7899     MIB->getOperand(5).setIsDef(true);
7900   }
7901   BuildMI(*BB, BB->end(), dl,
7902           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7903       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7904 
7905   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7906   BB->addSuccessor(loopMBB);
7907   BB->addSuccessor(exitMBB);
7908 
7909   // Add epilogue to handle BytesLeft.
7910   BB = exitMBB;
7911   MachineInstr *StartOfExit = exitMBB->begin();
7912 
7913   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7914   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7915   unsigned srcIn = srcLoop;
7916   unsigned destIn = destLoop;
7917   for (unsigned i = 0; i < BytesLeft; i++) {
7918     unsigned srcOut = MRI.createVirtualRegister(TRC);
7919     unsigned destOut = MRI.createVirtualRegister(TRC);
7920     unsigned scratch = MRI.createVirtualRegister(TRC);
7921     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7922                IsThumb1, IsThumb2);
7923     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7924                IsThumb1, IsThumb2);
7925     srcIn = srcOut;
7926     destIn = destOut;
7927   }
7928 
7929   MI->eraseFromParent();   // The instruction is gone now.
7930   return BB;
7931 }
7932 
7933 MachineBasicBlock *
7934 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7935                                        MachineBasicBlock *MBB) const {
7936   const TargetMachine &TM = getTargetMachine();
7937   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7938   DebugLoc DL = MI->getDebugLoc();
7939 
7940   assert(Subtarget->isTargetWindows() &&
7941          "__chkstk is only supported on Windows");
7942   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7943 
7944   // __chkstk takes the number of words to allocate on the stack in R4, and
7945   // returns the stack adjustment in number of bytes in R4.  This will not
7946   // clober any other registers (other than the obvious lr).
7947   //
7948   // Although, technically, IP should be considered a register which may be
7949   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7950   // thumb-2 environment, so there is no interworking required.  As a result, we
7951   // do not expect a veneer to be emitted by the linker, clobbering IP.
7952   //
7953   // Each module receives its own copy of __chkstk, so no import thunk is
7954   // required, again, ensuring that IP is not clobbered.
7955   //
7956   // Finally, although some linkers may theoretically provide a trampoline for
7957   // out of range calls (which is quite common due to a 32M range limitation of
7958   // branches for Thumb), we can generate the long-call version via
7959   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7960   // IP.
7961 
7962   switch (TM.getCodeModel()) {
7963   case CodeModel::Small:
7964   case CodeModel::Medium:
7965   case CodeModel::Default:
7966   case CodeModel::Kernel:
7967     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7968       .addImm((unsigned)ARMCC::AL).addReg(0)
7969       .addExternalSymbol("__chkstk")
7970       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7971       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7972       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7973     break;
7974   case CodeModel::Large:
7975   case CodeModel::JITDefault: {
7976     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7977     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7978 
7979     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7980       .addExternalSymbol("__chkstk");
7981     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7982       .addImm((unsigned)ARMCC::AL).addReg(0)
7983       .addReg(Reg, RegState::Kill)
7984       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7985       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7986       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7987     break;
7988   }
7989   }
7990 
7991   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7992                                       ARM::SP)
7993                               .addReg(ARM::SP).addReg(ARM::R4)));
7994 
7995   MI->eraseFromParent();
7996   return MBB;
7997 }
7998 
7999 MachineBasicBlock *
8000 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
8001                                        MachineBasicBlock *MBB) const {
8002   DebugLoc DL = MI->getDebugLoc();
8003   MachineFunction *MF = MBB->getParent();
8004   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8005 
8006   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8007   MF->push_back(ContBB);
8008   ContBB->splice(ContBB->begin(), MBB,
8009                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8010   MBB->addSuccessor(ContBB);
8011 
8012   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8013   MF->push_back(TrapBB);
8014   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
8015   MBB->addSuccessor(TrapBB);
8016 
8017   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
8018       .addReg(MI->getOperand(0).getReg())
8019       .addMBB(TrapBB);
8020 
8021   MI->eraseFromParent();
8022   return ContBB;
8023 }
8024 
8025 MachineBasicBlock *
8026 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8027                                                MachineBasicBlock *BB) const {
8028   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8029   DebugLoc dl = MI->getDebugLoc();
8030   bool isThumb2 = Subtarget->isThumb2();
8031   switch (MI->getOpcode()) {
8032   default: {
8033     MI->dump();
8034     llvm_unreachable("Unexpected instr type to insert");
8035   }
8036   // The Thumb2 pre-indexed stores have the same MI operands, they just
8037   // define them differently in the .td files from the isel patterns, so
8038   // they need pseudos.
8039   case ARM::t2STR_preidx:
8040     MI->setDesc(TII->get(ARM::t2STR_PRE));
8041     return BB;
8042   case ARM::t2STRB_preidx:
8043     MI->setDesc(TII->get(ARM::t2STRB_PRE));
8044     return BB;
8045   case ARM::t2STRH_preidx:
8046     MI->setDesc(TII->get(ARM::t2STRH_PRE));
8047     return BB;
8048 
8049   case ARM::STRi_preidx:
8050   case ARM::STRBi_preidx: {
8051     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
8052       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
8053     // Decode the offset.
8054     unsigned Offset = MI->getOperand(4).getImm();
8055     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8056     Offset = ARM_AM::getAM2Offset(Offset);
8057     if (isSub)
8058       Offset = -Offset;
8059 
8060     MachineMemOperand *MMO = *MI->memoperands_begin();
8061     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8062       .addOperand(MI->getOperand(0))  // Rn_wb
8063       .addOperand(MI->getOperand(1))  // Rt
8064       .addOperand(MI->getOperand(2))  // Rn
8065       .addImm(Offset)                 // offset (skip GPR==zero_reg)
8066       .addOperand(MI->getOperand(5))  // pred
8067       .addOperand(MI->getOperand(6))
8068       .addMemOperand(MMO);
8069     MI->eraseFromParent();
8070     return BB;
8071   }
8072   case ARM::STRr_preidx:
8073   case ARM::STRBr_preidx:
8074   case ARM::STRH_preidx: {
8075     unsigned NewOpc;
8076     switch (MI->getOpcode()) {
8077     default: llvm_unreachable("unexpected opcode!");
8078     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8079     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8080     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8081     }
8082     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8083     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
8084       MIB.addOperand(MI->getOperand(i));
8085     MI->eraseFromParent();
8086     return BB;
8087   }
8088 
8089   case ARM::tMOVCCr_pseudo: {
8090     // To "insert" a SELECT_CC instruction, we actually have to insert the
8091     // diamond control-flow pattern.  The incoming instruction knows the
8092     // destination vreg to set, the condition code register to branch on, the
8093     // true/false values to select between, and a branch opcode to use.
8094     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8095     MachineFunction::iterator It = ++BB->getIterator();
8096 
8097     //  thisMBB:
8098     //  ...
8099     //   TrueVal = ...
8100     //   cmpTY ccX, r1, r2
8101     //   bCC copy1MBB
8102     //   fallthrough --> copy0MBB
8103     MachineBasicBlock *thisMBB  = BB;
8104     MachineFunction *F = BB->getParent();
8105     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8106     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8107     F->insert(It, copy0MBB);
8108     F->insert(It, sinkMBB);
8109 
8110     // Transfer the remainder of BB and its successor edges to sinkMBB.
8111     sinkMBB->splice(sinkMBB->begin(), BB,
8112                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8113     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8114 
8115     BB->addSuccessor(copy0MBB);
8116     BB->addSuccessor(sinkMBB);
8117 
8118     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
8119       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
8120 
8121     //  copy0MBB:
8122     //   %FalseValue = ...
8123     //   # fallthrough to sinkMBB
8124     BB = copy0MBB;
8125 
8126     // Update machine-CFG edges
8127     BB->addSuccessor(sinkMBB);
8128 
8129     //  sinkMBB:
8130     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8131     //  ...
8132     BB = sinkMBB;
8133     BuildMI(*BB, BB->begin(), dl,
8134             TII->get(ARM::PHI), MI->getOperand(0).getReg())
8135       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8136       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8137 
8138     MI->eraseFromParent();   // The pseudo instruction is gone now.
8139     return BB;
8140   }
8141 
8142   case ARM::BCCi64:
8143   case ARM::BCCZi64: {
8144     // If there is an unconditional branch to the other successor, remove it.
8145     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8146 
8147     // Compare both parts that make up the double comparison separately for
8148     // equality.
8149     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8150 
8151     unsigned LHS1 = MI->getOperand(1).getReg();
8152     unsigned LHS2 = MI->getOperand(2).getReg();
8153     if (RHSisZero) {
8154       AddDefaultPred(BuildMI(BB, dl,
8155                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8156                      .addReg(LHS1).addImm(0));
8157       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8158         .addReg(LHS2).addImm(0)
8159         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8160     } else {
8161       unsigned RHS1 = MI->getOperand(3).getReg();
8162       unsigned RHS2 = MI->getOperand(4).getReg();
8163       AddDefaultPred(BuildMI(BB, dl,
8164                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8165                      .addReg(LHS1).addReg(RHS1));
8166       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8167         .addReg(LHS2).addReg(RHS2)
8168         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8169     }
8170 
8171     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8172     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8173     if (MI->getOperand(0).getImm() == ARMCC::NE)
8174       std::swap(destMBB, exitMBB);
8175 
8176     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8177       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8178     if (isThumb2)
8179       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8180     else
8181       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8182 
8183     MI->eraseFromParent();   // The pseudo instruction is gone now.
8184     return BB;
8185   }
8186 
8187   case ARM::Int_eh_sjlj_setjmp:
8188   case ARM::Int_eh_sjlj_setjmp_nofp:
8189   case ARM::tInt_eh_sjlj_setjmp:
8190   case ARM::t2Int_eh_sjlj_setjmp:
8191   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8192     return BB;
8193 
8194   case ARM::Int_eh_sjlj_setup_dispatch:
8195     EmitSjLjDispatchBlock(MI, BB);
8196     return BB;
8197 
8198   case ARM::ABS:
8199   case ARM::t2ABS: {
8200     // To insert an ABS instruction, we have to insert the
8201     // diamond control-flow pattern.  The incoming instruction knows the
8202     // source vreg to test against 0, the destination vreg to set,
8203     // the condition code register to branch on, the
8204     // true/false values to select between, and a branch opcode to use.
8205     // It transforms
8206     //     V1 = ABS V0
8207     // into
8208     //     V2 = MOVS V0
8209     //     BCC                      (branch to SinkBB if V0 >= 0)
8210     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8211     //     SinkBB: V1 = PHI(V2, V3)
8212     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8213     MachineFunction::iterator BBI = ++BB->getIterator();
8214     MachineFunction *Fn = BB->getParent();
8215     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8216     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8217     Fn->insert(BBI, RSBBB);
8218     Fn->insert(BBI, SinkBB);
8219 
8220     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8221     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8222     bool ABSSrcKIll = MI->getOperand(1).isKill();
8223     bool isThumb2 = Subtarget->isThumb2();
8224     MachineRegisterInfo &MRI = Fn->getRegInfo();
8225     // In Thumb mode S must not be specified if source register is the SP or
8226     // PC and if destination register is the SP, so restrict register class
8227     unsigned NewRsbDstReg =
8228       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8229 
8230     // Transfer the remainder of BB and its successor edges to sinkMBB.
8231     SinkBB->splice(SinkBB->begin(), BB,
8232                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8233     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8234 
8235     BB->addSuccessor(RSBBB);
8236     BB->addSuccessor(SinkBB);
8237 
8238     // fall through to SinkMBB
8239     RSBBB->addSuccessor(SinkBB);
8240 
8241     // insert a cmp at the end of BB
8242     AddDefaultPred(BuildMI(BB, dl,
8243                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8244                    .addReg(ABSSrcReg).addImm(0));
8245 
8246     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8247     BuildMI(BB, dl,
8248       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8249       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8250 
8251     // insert rsbri in RSBBB
8252     // Note: BCC and rsbri will be converted into predicated rsbmi
8253     // by if-conversion pass
8254     BuildMI(*RSBBB, RSBBB->begin(), dl,
8255       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8256       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8257       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8258 
8259     // insert PHI in SinkBB,
8260     // reuse ABSDstReg to not change uses of ABS instruction
8261     BuildMI(*SinkBB, SinkBB->begin(), dl,
8262       TII->get(ARM::PHI), ABSDstReg)
8263       .addReg(NewRsbDstReg).addMBB(RSBBB)
8264       .addReg(ABSSrcReg).addMBB(BB);
8265 
8266     // remove ABS instruction
8267     MI->eraseFromParent();
8268 
8269     // return last added BB
8270     return SinkBB;
8271   }
8272   case ARM::COPY_STRUCT_BYVAL_I32:
8273     ++NumLoopByVals;
8274     return EmitStructByval(MI, BB);
8275   case ARM::WIN__CHKSTK:
8276     return EmitLowered__chkstk(MI, BB);
8277   case ARM::WIN__DBZCHK:
8278     return EmitLowered__dbzchk(MI, BB);
8279   }
8280 }
8281 
8282 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8283 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8284 /// instead of as a custom inserter because we need the use list from the SDNode.
8285 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8286                                    MachineInstr *MI, const SDNode *Node) {
8287   bool isThumb1 = Subtarget->isThumb1Only();
8288 
8289   DebugLoc DL = MI->getDebugLoc();
8290   MachineFunction *MF = MI->getParent()->getParent();
8291   MachineRegisterInfo &MRI = MF->getRegInfo();
8292   MachineInstrBuilder MIB(*MF, MI);
8293 
8294   // If the new dst/src is unused mark it as dead.
8295   if (!Node->hasAnyUseOfValue(0)) {
8296     MI->getOperand(0).setIsDead(true);
8297   }
8298   if (!Node->hasAnyUseOfValue(1)) {
8299     MI->getOperand(1).setIsDead(true);
8300   }
8301 
8302   // The MEMCPY both defines and kills the scratch registers.
8303   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8304     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8305                                                          : &ARM::GPRRegClass);
8306     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8307   }
8308 }
8309 
8310 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8311                                                       SDNode *Node) const {
8312   if (MI->getOpcode() == ARM::MEMCPY) {
8313     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8314     return;
8315   }
8316 
8317   const MCInstrDesc *MCID = &MI->getDesc();
8318   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8319   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8320   // operand is still set to noreg. If needed, set the optional operand's
8321   // register to CPSR, and remove the redundant implicit def.
8322   //
8323   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8324 
8325   // Rename pseudo opcodes.
8326   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8327   if (NewOpc) {
8328     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8329     MCID = &TII->get(NewOpc);
8330 
8331     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8332            "converted opcode should be the same except for cc_out");
8333 
8334     MI->setDesc(*MCID);
8335 
8336     // Add the optional cc_out operand
8337     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8338   }
8339   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8340 
8341   // Any ARM instruction that sets the 's' bit should specify an optional
8342   // "cc_out" operand in the last operand position.
8343   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8344     assert(!NewOpc && "Optional cc_out operand required");
8345     return;
8346   }
8347   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8348   // since we already have an optional CPSR def.
8349   bool definesCPSR = false;
8350   bool deadCPSR = false;
8351   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8352        i != e; ++i) {
8353     const MachineOperand &MO = MI->getOperand(i);
8354     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8355       definesCPSR = true;
8356       if (MO.isDead())
8357         deadCPSR = true;
8358       MI->RemoveOperand(i);
8359       break;
8360     }
8361   }
8362   if (!definesCPSR) {
8363     assert(!NewOpc && "Optional cc_out operand required");
8364     return;
8365   }
8366   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8367   if (deadCPSR) {
8368     assert(!MI->getOperand(ccOutIdx).getReg() &&
8369            "expect uninitialized optional cc_out operand");
8370     return;
8371   }
8372 
8373   // If this instruction was defined with an optional CPSR def and its dag node
8374   // had a live implicit CPSR def, then activate the optional CPSR def.
8375   MachineOperand &MO = MI->getOperand(ccOutIdx);
8376   MO.setReg(ARM::CPSR);
8377   MO.setIsDef(true);
8378 }
8379 
8380 //===----------------------------------------------------------------------===//
8381 //                           ARM Optimization Hooks
8382 //===----------------------------------------------------------------------===//
8383 
8384 // Helper function that checks if N is a null or all ones constant.
8385 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8386   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8387 }
8388 
8389 // Return true if N is conditionally 0 or all ones.
8390 // Detects these expressions where cc is an i1 value:
8391 //
8392 //   (select cc 0, y)   [AllOnes=0]
8393 //   (select cc y, 0)   [AllOnes=0]
8394 //   (zext cc)          [AllOnes=0]
8395 //   (sext cc)          [AllOnes=0/1]
8396 //   (select cc -1, y)  [AllOnes=1]
8397 //   (select cc y, -1)  [AllOnes=1]
8398 //
8399 // Invert is set when N is the null/all ones constant when CC is false.
8400 // OtherOp is set to the alternative value of N.
8401 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8402                                        SDValue &CC, bool &Invert,
8403                                        SDValue &OtherOp,
8404                                        SelectionDAG &DAG) {
8405   switch (N->getOpcode()) {
8406   default: return false;
8407   case ISD::SELECT: {
8408     CC = N->getOperand(0);
8409     SDValue N1 = N->getOperand(1);
8410     SDValue N2 = N->getOperand(2);
8411     if (isZeroOrAllOnes(N1, AllOnes)) {
8412       Invert = false;
8413       OtherOp = N2;
8414       return true;
8415     }
8416     if (isZeroOrAllOnes(N2, AllOnes)) {
8417       Invert = true;
8418       OtherOp = N1;
8419       return true;
8420     }
8421     return false;
8422   }
8423   case ISD::ZERO_EXTEND:
8424     // (zext cc) can never be the all ones value.
8425     if (AllOnes)
8426       return false;
8427     // Fall through.
8428   case ISD::SIGN_EXTEND: {
8429     SDLoc dl(N);
8430     EVT VT = N->getValueType(0);
8431     CC = N->getOperand(0);
8432     if (CC.getValueType() != MVT::i1)
8433       return false;
8434     Invert = !AllOnes;
8435     if (AllOnes)
8436       // When looking for an AllOnes constant, N is an sext, and the 'other'
8437       // value is 0.
8438       OtherOp = DAG.getConstant(0, dl, VT);
8439     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8440       // When looking for a 0 constant, N can be zext or sext.
8441       OtherOp = DAG.getConstant(1, dl, VT);
8442     else
8443       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8444                                 VT);
8445     return true;
8446   }
8447   }
8448 }
8449 
8450 // Combine a constant select operand into its use:
8451 //
8452 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8453 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8454 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8455 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8456 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8457 //
8458 // The transform is rejected if the select doesn't have a constant operand that
8459 // is null, or all ones when AllOnes is set.
8460 //
8461 // Also recognize sext/zext from i1:
8462 //
8463 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8464 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8465 //
8466 // These transformations eventually create predicated instructions.
8467 //
8468 // @param N       The node to transform.
8469 // @param Slct    The N operand that is a select.
8470 // @param OtherOp The other N operand (x above).
8471 // @param DCI     Context.
8472 // @param AllOnes Require the select constant to be all ones instead of null.
8473 // @returns The new node, or SDValue() on failure.
8474 static
8475 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8476                             TargetLowering::DAGCombinerInfo &DCI,
8477                             bool AllOnes = false) {
8478   SelectionDAG &DAG = DCI.DAG;
8479   EVT VT = N->getValueType(0);
8480   SDValue NonConstantVal;
8481   SDValue CCOp;
8482   bool SwapSelectOps;
8483   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8484                                   NonConstantVal, DAG))
8485     return SDValue();
8486 
8487   // Slct is now know to be the desired identity constant when CC is true.
8488   SDValue TrueVal = OtherOp;
8489   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8490                                  OtherOp, NonConstantVal);
8491   // Unless SwapSelectOps says CC should be false.
8492   if (SwapSelectOps)
8493     std::swap(TrueVal, FalseVal);
8494 
8495   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8496                      CCOp, TrueVal, FalseVal);
8497 }
8498 
8499 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8500 static
8501 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8502                                        TargetLowering::DAGCombinerInfo &DCI) {
8503   SDValue N0 = N->getOperand(0);
8504   SDValue N1 = N->getOperand(1);
8505   if (N0.getNode()->hasOneUse())
8506     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
8507       return Result;
8508   if (N1.getNode()->hasOneUse())
8509     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
8510       return Result;
8511   return SDValue();
8512 }
8513 
8514 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8515 // (only after legalization).
8516 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8517                                  TargetLowering::DAGCombinerInfo &DCI,
8518                                  const ARMSubtarget *Subtarget) {
8519 
8520   // Only perform optimization if after legalize, and if NEON is available. We
8521   // also expected both operands to be BUILD_VECTORs.
8522   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8523       || N0.getOpcode() != ISD::BUILD_VECTOR
8524       || N1.getOpcode() != ISD::BUILD_VECTOR)
8525     return SDValue();
8526 
8527   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8528   EVT VT = N->getValueType(0);
8529   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8530     return SDValue();
8531 
8532   // Check that the vector operands are of the right form.
8533   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8534   // operands, where N is the size of the formed vector.
8535   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8536   // index such that we have a pair wise add pattern.
8537 
8538   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8539   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8540     return SDValue();
8541   SDValue Vec = N0->getOperand(0)->getOperand(0);
8542   SDNode *V = Vec.getNode();
8543   unsigned nextIndex = 0;
8544 
8545   // For each operands to the ADD which are BUILD_VECTORs,
8546   // check to see if each of their operands are an EXTRACT_VECTOR with
8547   // the same vector and appropriate index.
8548   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8549     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8550         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8551 
8552       SDValue ExtVec0 = N0->getOperand(i);
8553       SDValue ExtVec1 = N1->getOperand(i);
8554 
8555       // First operand is the vector, verify its the same.
8556       if (V != ExtVec0->getOperand(0).getNode() ||
8557           V != ExtVec1->getOperand(0).getNode())
8558         return SDValue();
8559 
8560       // Second is the constant, verify its correct.
8561       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8562       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8563 
8564       // For the constant, we want to see all the even or all the odd.
8565       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8566           || C1->getZExtValue() != nextIndex+1)
8567         return SDValue();
8568 
8569       // Increment index.
8570       nextIndex+=2;
8571     } else
8572       return SDValue();
8573   }
8574 
8575   // Create VPADDL node.
8576   SelectionDAG &DAG = DCI.DAG;
8577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8578 
8579   SDLoc dl(N);
8580 
8581   // Build operand list.
8582   SmallVector<SDValue, 8> Ops;
8583   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8584                                 TLI.getPointerTy(DAG.getDataLayout())));
8585 
8586   // Input is the vector.
8587   Ops.push_back(Vec);
8588 
8589   // Get widened type and narrowed type.
8590   MVT widenType;
8591   unsigned numElem = VT.getVectorNumElements();
8592 
8593   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8594   switch (inputLaneType.getSimpleVT().SimpleTy) {
8595     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8596     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8597     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8598     default:
8599       llvm_unreachable("Invalid vector element type for padd optimization.");
8600   }
8601 
8602   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8603   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8604   return DAG.getNode(ExtOp, dl, VT, tmp);
8605 }
8606 
8607 static SDValue findMUL_LOHI(SDValue V) {
8608   if (V->getOpcode() == ISD::UMUL_LOHI ||
8609       V->getOpcode() == ISD::SMUL_LOHI)
8610     return V;
8611   return SDValue();
8612 }
8613 
8614 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8615                                      TargetLowering::DAGCombinerInfo &DCI,
8616                                      const ARMSubtarget *Subtarget) {
8617 
8618   if (Subtarget->isThumb1Only()) return SDValue();
8619 
8620   // Only perform the checks after legalize when the pattern is available.
8621   if (DCI.isBeforeLegalize()) return SDValue();
8622 
8623   // Look for multiply add opportunities.
8624   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8625   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8626   // a glue link from the first add to the second add.
8627   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8628   // a S/UMLAL instruction.
8629   //                  UMUL_LOHI
8630   //                 / :lo    \ :hi
8631   //                /          \          [no multiline comment]
8632   //    loAdd ->  ADDE         |
8633   //                 \ :glue  /
8634   //                  \      /
8635   //                    ADDC   <- hiAdd
8636   //
8637   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8638   SDValue AddcOp0 = AddcNode->getOperand(0);
8639   SDValue AddcOp1 = AddcNode->getOperand(1);
8640 
8641   // Check if the two operands are from the same mul_lohi node.
8642   if (AddcOp0.getNode() == AddcOp1.getNode())
8643     return SDValue();
8644 
8645   assert(AddcNode->getNumValues() == 2 &&
8646          AddcNode->getValueType(0) == MVT::i32 &&
8647          "Expect ADDC with two result values. First: i32");
8648 
8649   // Check that we have a glued ADDC node.
8650   if (AddcNode->getValueType(1) != MVT::Glue)
8651     return SDValue();
8652 
8653   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8654   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8655       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8656       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8657       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8658     return SDValue();
8659 
8660   // Look for the glued ADDE.
8661   SDNode* AddeNode = AddcNode->getGluedUser();
8662   if (!AddeNode)
8663     return SDValue();
8664 
8665   // Make sure it is really an ADDE.
8666   if (AddeNode->getOpcode() != ISD::ADDE)
8667     return SDValue();
8668 
8669   assert(AddeNode->getNumOperands() == 3 &&
8670          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8671          "ADDE node has the wrong inputs");
8672 
8673   // Check for the triangle shape.
8674   SDValue AddeOp0 = AddeNode->getOperand(0);
8675   SDValue AddeOp1 = AddeNode->getOperand(1);
8676 
8677   // Make sure that the ADDE operands are not coming from the same node.
8678   if (AddeOp0.getNode() == AddeOp1.getNode())
8679     return SDValue();
8680 
8681   // Find the MUL_LOHI node walking up ADDE's operands.
8682   bool IsLeftOperandMUL = false;
8683   SDValue MULOp = findMUL_LOHI(AddeOp0);
8684   if (MULOp == SDValue())
8685    MULOp = findMUL_LOHI(AddeOp1);
8686   else
8687     IsLeftOperandMUL = true;
8688   if (MULOp == SDValue())
8689     return SDValue();
8690 
8691   // Figure out the right opcode.
8692   unsigned Opc = MULOp->getOpcode();
8693   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8694 
8695   // Figure out the high and low input values to the MLAL node.
8696   SDValue* HiAdd = nullptr;
8697   SDValue* LoMul = nullptr;
8698   SDValue* LowAdd = nullptr;
8699 
8700   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8701   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8702     return SDValue();
8703 
8704   if (IsLeftOperandMUL)
8705     HiAdd = &AddeOp1;
8706   else
8707     HiAdd = &AddeOp0;
8708 
8709 
8710   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8711   // whose low result is fed to the ADDC we are checking.
8712 
8713   if (AddcOp0 == MULOp.getValue(0)) {
8714     LoMul = &AddcOp0;
8715     LowAdd = &AddcOp1;
8716   }
8717   if (AddcOp1 == MULOp.getValue(0)) {
8718     LoMul = &AddcOp1;
8719     LowAdd = &AddcOp0;
8720   }
8721 
8722   if (!LoMul)
8723     return SDValue();
8724 
8725   // Create the merged node.
8726   SelectionDAG &DAG = DCI.DAG;
8727 
8728   // Build operand list.
8729   SmallVector<SDValue, 8> Ops;
8730   Ops.push_back(LoMul->getOperand(0));
8731   Ops.push_back(LoMul->getOperand(1));
8732   Ops.push_back(*LowAdd);
8733   Ops.push_back(*HiAdd);
8734 
8735   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8736                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8737 
8738   // Replace the ADDs' nodes uses by the MLA node's values.
8739   SDValue HiMLALResult(MLALNode.getNode(), 1);
8740   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8741 
8742   SDValue LoMLALResult(MLALNode.getNode(), 0);
8743   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8744 
8745   // Return original node to notify the driver to stop replacing.
8746   SDValue resNode(AddcNode, 0);
8747   return resNode;
8748 }
8749 
8750 /// PerformADDCCombine - Target-specific dag combine transform from
8751 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8752 static SDValue PerformADDCCombine(SDNode *N,
8753                                  TargetLowering::DAGCombinerInfo &DCI,
8754                                  const ARMSubtarget *Subtarget) {
8755 
8756   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8757 
8758 }
8759 
8760 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8761 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8762 /// called with the default operands, and if that fails, with commuted
8763 /// operands.
8764 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8765                                           TargetLowering::DAGCombinerInfo &DCI,
8766                                           const ARMSubtarget *Subtarget){
8767 
8768   // Attempt to create vpaddl for this add.
8769   if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
8770     return Result;
8771 
8772   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8773   if (N0.getNode()->hasOneUse())
8774     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
8775       return Result;
8776   return SDValue();
8777 }
8778 
8779 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8780 ///
8781 static SDValue PerformADDCombine(SDNode *N,
8782                                  TargetLowering::DAGCombinerInfo &DCI,
8783                                  const ARMSubtarget *Subtarget) {
8784   SDValue N0 = N->getOperand(0);
8785   SDValue N1 = N->getOperand(1);
8786 
8787   // First try with the default operand order.
8788   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
8789     return Result;
8790 
8791   // If that didn't work, try again with the operands commuted.
8792   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8793 }
8794 
8795 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8796 ///
8797 static SDValue PerformSUBCombine(SDNode *N,
8798                                  TargetLowering::DAGCombinerInfo &DCI) {
8799   SDValue N0 = N->getOperand(0);
8800   SDValue N1 = N->getOperand(1);
8801 
8802   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8803   if (N1.getNode()->hasOneUse())
8804     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
8805       return Result;
8806 
8807   return SDValue();
8808 }
8809 
8810 /// PerformVMULCombine
8811 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8812 /// special multiplier accumulator forwarding.
8813 ///   vmul d3, d0, d2
8814 ///   vmla d3, d1, d2
8815 /// is faster than
8816 ///   vadd d3, d0, d1
8817 ///   vmul d3, d3, d2
8818 //  However, for (A + B) * (A + B),
8819 //    vadd d2, d0, d1
8820 //    vmul d3, d0, d2
8821 //    vmla d3, d1, d2
8822 //  is slower than
8823 //    vadd d2, d0, d1
8824 //    vmul d3, d2, d2
8825 static SDValue PerformVMULCombine(SDNode *N,
8826                                   TargetLowering::DAGCombinerInfo &DCI,
8827                                   const ARMSubtarget *Subtarget) {
8828   if (!Subtarget->hasVMLxForwarding())
8829     return SDValue();
8830 
8831   SelectionDAG &DAG = DCI.DAG;
8832   SDValue N0 = N->getOperand(0);
8833   SDValue N1 = N->getOperand(1);
8834   unsigned Opcode = N0.getOpcode();
8835   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8836       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8837     Opcode = N1.getOpcode();
8838     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8839         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8840       return SDValue();
8841     std::swap(N0, N1);
8842   }
8843 
8844   if (N0 == N1)
8845     return SDValue();
8846 
8847   EVT VT = N->getValueType(0);
8848   SDLoc DL(N);
8849   SDValue N00 = N0->getOperand(0);
8850   SDValue N01 = N0->getOperand(1);
8851   return DAG.getNode(Opcode, DL, VT,
8852                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8853                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8854 }
8855 
8856 static SDValue PerformMULCombine(SDNode *N,
8857                                  TargetLowering::DAGCombinerInfo &DCI,
8858                                  const ARMSubtarget *Subtarget) {
8859   SelectionDAG &DAG = DCI.DAG;
8860 
8861   if (Subtarget->isThumb1Only())
8862     return SDValue();
8863 
8864   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8865     return SDValue();
8866 
8867   EVT VT = N->getValueType(0);
8868   if (VT.is64BitVector() || VT.is128BitVector())
8869     return PerformVMULCombine(N, DCI, Subtarget);
8870   if (VT != MVT::i32)
8871     return SDValue();
8872 
8873   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8874   if (!C)
8875     return SDValue();
8876 
8877   int64_t MulAmt = C->getSExtValue();
8878   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8879 
8880   ShiftAmt = ShiftAmt & (32 - 1);
8881   SDValue V = N->getOperand(0);
8882   SDLoc DL(N);
8883 
8884   SDValue Res;
8885   MulAmt >>= ShiftAmt;
8886 
8887   if (MulAmt >= 0) {
8888     if (isPowerOf2_32(MulAmt - 1)) {
8889       // (mul x, 2^N + 1) => (add (shl x, N), x)
8890       Res = DAG.getNode(ISD::ADD, DL, VT,
8891                         V,
8892                         DAG.getNode(ISD::SHL, DL, VT,
8893                                     V,
8894                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8895                                                     MVT::i32)));
8896     } else if (isPowerOf2_32(MulAmt + 1)) {
8897       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8898       Res = DAG.getNode(ISD::SUB, DL, VT,
8899                         DAG.getNode(ISD::SHL, DL, VT,
8900                                     V,
8901                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8902                                                     MVT::i32)),
8903                         V);
8904     } else
8905       return SDValue();
8906   } else {
8907     uint64_t MulAmtAbs = -MulAmt;
8908     if (isPowerOf2_32(MulAmtAbs + 1)) {
8909       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8910       Res = DAG.getNode(ISD::SUB, DL, VT,
8911                         V,
8912                         DAG.getNode(ISD::SHL, DL, VT,
8913                                     V,
8914                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8915                                                     MVT::i32)));
8916     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8917       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8918       Res = DAG.getNode(ISD::ADD, DL, VT,
8919                         V,
8920                         DAG.getNode(ISD::SHL, DL, VT,
8921                                     V,
8922                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8923                                                     MVT::i32)));
8924       Res = DAG.getNode(ISD::SUB, DL, VT,
8925                         DAG.getConstant(0, DL, MVT::i32), Res);
8926 
8927     } else
8928       return SDValue();
8929   }
8930 
8931   if (ShiftAmt != 0)
8932     Res = DAG.getNode(ISD::SHL, DL, VT,
8933                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8934 
8935   // Do not add new nodes to DAG combiner worklist.
8936   DCI.CombineTo(N, Res, false);
8937   return SDValue();
8938 }
8939 
8940 static SDValue PerformANDCombine(SDNode *N,
8941                                  TargetLowering::DAGCombinerInfo &DCI,
8942                                  const ARMSubtarget *Subtarget) {
8943 
8944   // Attempt to use immediate-form VBIC
8945   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8946   SDLoc dl(N);
8947   EVT VT = N->getValueType(0);
8948   SelectionDAG &DAG = DCI.DAG;
8949 
8950   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8951     return SDValue();
8952 
8953   APInt SplatBits, SplatUndef;
8954   unsigned SplatBitSize;
8955   bool HasAnyUndefs;
8956   if (BVN &&
8957       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8958     if (SplatBitSize <= 64) {
8959       EVT VbicVT;
8960       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8961                                       SplatUndef.getZExtValue(), SplatBitSize,
8962                                       DAG, dl, VbicVT, VT.is128BitVector(),
8963                                       OtherModImm);
8964       if (Val.getNode()) {
8965         SDValue Input =
8966           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8967         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8968         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8969       }
8970     }
8971   }
8972 
8973   if (!Subtarget->isThumb1Only()) {
8974     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8975     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
8976       return Result;
8977   }
8978 
8979   return SDValue();
8980 }
8981 
8982 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8983 static SDValue PerformORCombine(SDNode *N,
8984                                 TargetLowering::DAGCombinerInfo &DCI,
8985                                 const ARMSubtarget *Subtarget) {
8986   // Attempt to use immediate-form VORR
8987   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8988   SDLoc dl(N);
8989   EVT VT = N->getValueType(0);
8990   SelectionDAG &DAG = DCI.DAG;
8991 
8992   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8993     return SDValue();
8994 
8995   APInt SplatBits, SplatUndef;
8996   unsigned SplatBitSize;
8997   bool HasAnyUndefs;
8998   if (BVN && Subtarget->hasNEON() &&
8999       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9000     if (SplatBitSize <= 64) {
9001       EVT VorrVT;
9002       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9003                                       SplatUndef.getZExtValue(), SplatBitSize,
9004                                       DAG, dl, VorrVT, VT.is128BitVector(),
9005                                       OtherModImm);
9006       if (Val.getNode()) {
9007         SDValue Input =
9008           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9009         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9010         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9011       }
9012     }
9013   }
9014 
9015   if (!Subtarget->isThumb1Only()) {
9016     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9017     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9018       return Result;
9019   }
9020 
9021   // The code below optimizes (or (and X, Y), Z).
9022   // The AND operand needs to have a single user to make these optimizations
9023   // profitable.
9024   SDValue N0 = N->getOperand(0);
9025   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9026     return SDValue();
9027   SDValue N1 = N->getOperand(1);
9028 
9029   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9030   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9031       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9032     APInt SplatUndef;
9033     unsigned SplatBitSize;
9034     bool HasAnyUndefs;
9035 
9036     APInt SplatBits0, SplatBits1;
9037     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9038     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9039     // Ensure that the second operand of both ands are constants
9040     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9041                                       HasAnyUndefs) && !HasAnyUndefs) {
9042         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9043                                           HasAnyUndefs) && !HasAnyUndefs) {
9044             // Ensure that the bit width of the constants are the same and that
9045             // the splat arguments are logical inverses as per the pattern we
9046             // are trying to simplify.
9047             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9048                 SplatBits0 == ~SplatBits1) {
9049                 // Canonicalize the vector type to make instruction selection
9050                 // simpler.
9051                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9052                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9053                                              N0->getOperand(1),
9054                                              N0->getOperand(0),
9055                                              N1->getOperand(0));
9056                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9057             }
9058         }
9059     }
9060   }
9061 
9062   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9063   // reasonable.
9064 
9065   // BFI is only available on V6T2+
9066   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9067     return SDValue();
9068 
9069   SDLoc DL(N);
9070   // 1) or (and A, mask), val => ARMbfi A, val, mask
9071   //      iff (val & mask) == val
9072   //
9073   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9074   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9075   //          && mask == ~mask2
9076   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9077   //          && ~mask == mask2
9078   //  (i.e., copy a bitfield value into another bitfield of the same width)
9079 
9080   if (VT != MVT::i32)
9081     return SDValue();
9082 
9083   SDValue N00 = N0.getOperand(0);
9084 
9085   // The value and the mask need to be constants so we can verify this is
9086   // actually a bitfield set. If the mask is 0xffff, we can do better
9087   // via a movt instruction, so don't use BFI in that case.
9088   SDValue MaskOp = N0.getOperand(1);
9089   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9090   if (!MaskC)
9091     return SDValue();
9092   unsigned Mask = MaskC->getZExtValue();
9093   if (Mask == 0xffff)
9094     return SDValue();
9095   SDValue Res;
9096   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9097   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9098   if (N1C) {
9099     unsigned Val = N1C->getZExtValue();
9100     if ((Val & ~Mask) != Val)
9101       return SDValue();
9102 
9103     if (ARM::isBitFieldInvertedMask(Mask)) {
9104       Val >>= countTrailingZeros(~Mask);
9105 
9106       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9107                         DAG.getConstant(Val, DL, MVT::i32),
9108                         DAG.getConstant(Mask, DL, MVT::i32));
9109 
9110       // Do not add new nodes to DAG combiner worklist.
9111       DCI.CombineTo(N, Res, false);
9112       return SDValue();
9113     }
9114   } else if (N1.getOpcode() == ISD::AND) {
9115     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9116     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9117     if (!N11C)
9118       return SDValue();
9119     unsigned Mask2 = N11C->getZExtValue();
9120 
9121     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9122     // as is to match.
9123     if (ARM::isBitFieldInvertedMask(Mask) &&
9124         (Mask == ~Mask2)) {
9125       // The pack halfword instruction works better for masks that fit it,
9126       // so use that when it's available.
9127       if (Subtarget->hasT2ExtractPack() &&
9128           (Mask == 0xffff || Mask == 0xffff0000))
9129         return SDValue();
9130       // 2a
9131       unsigned amt = countTrailingZeros(Mask2);
9132       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9133                         DAG.getConstant(amt, DL, MVT::i32));
9134       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9135                         DAG.getConstant(Mask, DL, MVT::i32));
9136       // Do not add new nodes to DAG combiner worklist.
9137       DCI.CombineTo(N, Res, false);
9138       return SDValue();
9139     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9140                (~Mask == Mask2)) {
9141       // The pack halfword instruction works better for masks that fit it,
9142       // so use that when it's available.
9143       if (Subtarget->hasT2ExtractPack() &&
9144           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9145         return SDValue();
9146       // 2b
9147       unsigned lsb = countTrailingZeros(Mask);
9148       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9149                         DAG.getConstant(lsb, DL, MVT::i32));
9150       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9151                         DAG.getConstant(Mask2, DL, MVT::i32));
9152       // Do not add new nodes to DAG combiner worklist.
9153       DCI.CombineTo(N, Res, false);
9154       return SDValue();
9155     }
9156   }
9157 
9158   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9159       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9160       ARM::isBitFieldInvertedMask(~Mask)) {
9161     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9162     // where lsb(mask) == #shamt and masked bits of B are known zero.
9163     SDValue ShAmt = N00.getOperand(1);
9164     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9165     unsigned LSB = countTrailingZeros(Mask);
9166     if (ShAmtC != LSB)
9167       return SDValue();
9168 
9169     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9170                       DAG.getConstant(~Mask, DL, MVT::i32));
9171 
9172     // Do not add new nodes to DAG combiner worklist.
9173     DCI.CombineTo(N, Res, false);
9174   }
9175 
9176   return SDValue();
9177 }
9178 
9179 static SDValue PerformXORCombine(SDNode *N,
9180                                  TargetLowering::DAGCombinerInfo &DCI,
9181                                  const ARMSubtarget *Subtarget) {
9182   EVT VT = N->getValueType(0);
9183   SelectionDAG &DAG = DCI.DAG;
9184 
9185   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9186     return SDValue();
9187 
9188   if (!Subtarget->isThumb1Only()) {
9189     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9190     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9191       return Result;
9192   }
9193 
9194   return SDValue();
9195 }
9196 
9197 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9198 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9199 // their position in "to" (Rd).
9200 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9201   assert(N->getOpcode() == ARMISD::BFI);
9202 
9203   SDValue From = N->getOperand(1);
9204   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9205   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9206 
9207   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9208   // #C in the base of the SHR.
9209   if (From->getOpcode() == ISD::SRL &&
9210       isa<ConstantSDNode>(From->getOperand(1))) {
9211     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9212     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9213     FromMask <<= Shift.getLimitedValue(31);
9214     From = From->getOperand(0);
9215   }
9216 
9217   return From;
9218 }
9219 
9220 // If A and B contain one contiguous set of bits, does A | B == A . B?
9221 //
9222 // Neither A nor B must be zero.
9223 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9224   unsigned LastActiveBitInA =  A.countTrailingZeros();
9225   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9226   return LastActiveBitInA - 1 == FirstActiveBitInB;
9227 }
9228 
9229 static SDValue FindBFIToCombineWith(SDNode *N) {
9230   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9231   // if one exists.
9232   APInt ToMask, FromMask;
9233   SDValue From = ParseBFI(N, ToMask, FromMask);
9234   SDValue To = N->getOperand(0);
9235 
9236   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9237   // aren't compatible, but not if they set the same bit in their destination as
9238   // we do (or that of any BFI we're going to combine with).
9239   SDValue V = To;
9240   APInt CombinedToMask = ToMask;
9241   while (V.getOpcode() == ARMISD::BFI) {
9242     APInt NewToMask, NewFromMask;
9243     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9244     if (NewFrom != From) {
9245       // This BFI has a different base. Keep going.
9246       CombinedToMask |= NewToMask;
9247       V = V.getOperand(0);
9248       continue;
9249     }
9250 
9251     // Do the written bits conflict with any we've seen so far?
9252     if ((NewToMask & CombinedToMask).getBoolValue())
9253       // Conflicting bits - bail out because going further is unsafe.
9254       return SDValue();
9255 
9256     // Are the new bits contiguous when combined with the old bits?
9257     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9258         BitsProperlyConcatenate(FromMask, NewFromMask))
9259       return V;
9260     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9261         BitsProperlyConcatenate(NewFromMask, FromMask))
9262       return V;
9263 
9264     // We've seen a write to some bits, so track it.
9265     CombinedToMask |= NewToMask;
9266     // Keep going...
9267     V = V.getOperand(0);
9268   }
9269 
9270   return SDValue();
9271 }
9272 
9273 static SDValue PerformBFICombine(SDNode *N,
9274                                  TargetLowering::DAGCombinerInfo &DCI) {
9275   SDValue N1 = N->getOperand(1);
9276   if (N1.getOpcode() == ISD::AND) {
9277     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9278     // the bits being cleared by the AND are not demanded by the BFI.
9279     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9280     if (!N11C)
9281       return SDValue();
9282     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9283     unsigned LSB = countTrailingZeros(~InvMask);
9284     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9285     assert(Width <
9286                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9287            "undefined behavior");
9288     unsigned Mask = (1u << Width) - 1;
9289     unsigned Mask2 = N11C->getZExtValue();
9290     if ((Mask & (~Mask2)) == 0)
9291       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9292                              N->getOperand(0), N1.getOperand(0),
9293                              N->getOperand(2));
9294   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9295     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9296     // Keep track of any consecutive bits set that all come from the same base
9297     // value. We can combine these together into a single BFI.
9298     SDValue CombineBFI = FindBFIToCombineWith(N);
9299     if (CombineBFI == SDValue())
9300       return SDValue();
9301 
9302     // We've found a BFI.
9303     APInt ToMask1, FromMask1;
9304     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9305 
9306     APInt ToMask2, FromMask2;
9307     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9308     assert(From1 == From2);
9309     (void)From2;
9310 
9311     // First, unlink CombineBFI.
9312     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9313     // Then create a new BFI, combining the two together.
9314     APInt NewFromMask = FromMask1 | FromMask2;
9315     APInt NewToMask = ToMask1 | ToMask2;
9316 
9317     EVT VT = N->getValueType(0);
9318     SDLoc dl(N);
9319 
9320     if (NewFromMask[0] == 0)
9321       From1 = DCI.DAG.getNode(
9322         ISD::SRL, dl, VT, From1,
9323         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9324     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9325                            DCI.DAG.getConstant(~NewToMask, dl, VT));
9326   }
9327   return SDValue();
9328 }
9329 
9330 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9331 /// ARMISD::VMOVRRD.
9332 static SDValue PerformVMOVRRDCombine(SDNode *N,
9333                                      TargetLowering::DAGCombinerInfo &DCI,
9334                                      const ARMSubtarget *Subtarget) {
9335   // vmovrrd(vmovdrr x, y) -> x,y
9336   SDValue InDouble = N->getOperand(0);
9337   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9338     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9339 
9340   // vmovrrd(load f64) -> (load i32), (load i32)
9341   SDNode *InNode = InDouble.getNode();
9342   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9343       InNode->getValueType(0) == MVT::f64 &&
9344       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9345       !cast<LoadSDNode>(InNode)->isVolatile()) {
9346     // TODO: Should this be done for non-FrameIndex operands?
9347     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9348 
9349     SelectionDAG &DAG = DCI.DAG;
9350     SDLoc DL(LD);
9351     SDValue BasePtr = LD->getBasePtr();
9352     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9353                                  LD->getPointerInfo(), LD->isVolatile(),
9354                                  LD->isNonTemporal(), LD->isInvariant(),
9355                                  LD->getAlignment());
9356 
9357     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9358                                     DAG.getConstant(4, DL, MVT::i32));
9359     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9360                                  LD->getPointerInfo(), LD->isVolatile(),
9361                                  LD->isNonTemporal(), LD->isInvariant(),
9362                                  std::min(4U, LD->getAlignment() / 2));
9363 
9364     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9365     if (DCI.DAG.getDataLayout().isBigEndian())
9366       std::swap (NewLD1, NewLD2);
9367     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9368     return Result;
9369   }
9370 
9371   return SDValue();
9372 }
9373 
9374 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9375 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9376 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9377   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9378   SDValue Op0 = N->getOperand(0);
9379   SDValue Op1 = N->getOperand(1);
9380   if (Op0.getOpcode() == ISD::BITCAST)
9381     Op0 = Op0.getOperand(0);
9382   if (Op1.getOpcode() == ISD::BITCAST)
9383     Op1 = Op1.getOperand(0);
9384   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9385       Op0.getNode() == Op1.getNode() &&
9386       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9387     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9388                        N->getValueType(0), Op0.getOperand(0));
9389   return SDValue();
9390 }
9391 
9392 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9393 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9394 /// i64 vector to have f64 elements, since the value can then be loaded
9395 /// directly into a VFP register.
9396 static bool hasNormalLoadOperand(SDNode *N) {
9397   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9398   for (unsigned i = 0; i < NumElts; ++i) {
9399     SDNode *Elt = N->getOperand(i).getNode();
9400     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9401       return true;
9402   }
9403   return false;
9404 }
9405 
9406 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9407 /// ISD::BUILD_VECTOR.
9408 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9409                                           TargetLowering::DAGCombinerInfo &DCI,
9410                                           const ARMSubtarget *Subtarget) {
9411   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9412   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9413   // into a pair of GPRs, which is fine when the value is used as a scalar,
9414   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9415   SelectionDAG &DAG = DCI.DAG;
9416   if (N->getNumOperands() == 2)
9417     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
9418       return RV;
9419 
9420   // Load i64 elements as f64 values so that type legalization does not split
9421   // them up into i32 values.
9422   EVT VT = N->getValueType(0);
9423   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9424     return SDValue();
9425   SDLoc dl(N);
9426   SmallVector<SDValue, 8> Ops;
9427   unsigned NumElts = VT.getVectorNumElements();
9428   for (unsigned i = 0; i < NumElts; ++i) {
9429     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9430     Ops.push_back(V);
9431     // Make the DAGCombiner fold the bitcast.
9432     DCI.AddToWorklist(V.getNode());
9433   }
9434   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9435   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9436   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9437 }
9438 
9439 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9440 static SDValue
9441 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9442   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9443   // At that time, we may have inserted bitcasts from integer to float.
9444   // If these bitcasts have survived DAGCombine, change the lowering of this
9445   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9446   // force to use floating point types.
9447 
9448   // Make sure we can change the type of the vector.
9449   // This is possible iff:
9450   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9451   //    1.1. Vector is used only once.
9452   //    1.2. Use is a bit convert to an integer type.
9453   // 2. The size of its operands are 32-bits (64-bits are not legal).
9454   EVT VT = N->getValueType(0);
9455   EVT EltVT = VT.getVectorElementType();
9456 
9457   // Check 1.1. and 2.
9458   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9459     return SDValue();
9460 
9461   // By construction, the input type must be float.
9462   assert(EltVT == MVT::f32 && "Unexpected type!");
9463 
9464   // Check 1.2.
9465   SDNode *Use = *N->use_begin();
9466   if (Use->getOpcode() != ISD::BITCAST ||
9467       Use->getValueType(0).isFloatingPoint())
9468     return SDValue();
9469 
9470   // Check profitability.
9471   // Model is, if more than half of the relevant operands are bitcast from
9472   // i32, turn the build_vector into a sequence of insert_vector_elt.
9473   // Relevant operands are everything that is not statically
9474   // (i.e., at compile time) bitcasted.
9475   unsigned NumOfBitCastedElts = 0;
9476   unsigned NumElts = VT.getVectorNumElements();
9477   unsigned NumOfRelevantElts = NumElts;
9478   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9479     SDValue Elt = N->getOperand(Idx);
9480     if (Elt->getOpcode() == ISD::BITCAST) {
9481       // Assume only bit cast to i32 will go away.
9482       if (Elt->getOperand(0).getValueType() == MVT::i32)
9483         ++NumOfBitCastedElts;
9484     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
9485       // Constants are statically casted, thus do not count them as
9486       // relevant operands.
9487       --NumOfRelevantElts;
9488   }
9489 
9490   // Check if more than half of the elements require a non-free bitcast.
9491   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9492     return SDValue();
9493 
9494   SelectionDAG &DAG = DCI.DAG;
9495   // Create the new vector type.
9496   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9497   // Check if the type is legal.
9498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9499   if (!TLI.isTypeLegal(VecVT))
9500     return SDValue();
9501 
9502   // Combine:
9503   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9504   // => BITCAST INSERT_VECTOR_ELT
9505   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9506   //                      (BITCAST EN), N.
9507   SDValue Vec = DAG.getUNDEF(VecVT);
9508   SDLoc dl(N);
9509   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9510     SDValue V = N->getOperand(Idx);
9511     if (V.isUndef())
9512       continue;
9513     if (V.getOpcode() == ISD::BITCAST &&
9514         V->getOperand(0).getValueType() == MVT::i32)
9515       // Fold obvious case.
9516       V = V.getOperand(0);
9517     else {
9518       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9519       // Make the DAGCombiner fold the bitcasts.
9520       DCI.AddToWorklist(V.getNode());
9521     }
9522     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9523     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9524   }
9525   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9526   // Make the DAGCombiner fold the bitcasts.
9527   DCI.AddToWorklist(Vec.getNode());
9528   return Vec;
9529 }
9530 
9531 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9532 /// ISD::INSERT_VECTOR_ELT.
9533 static SDValue PerformInsertEltCombine(SDNode *N,
9534                                        TargetLowering::DAGCombinerInfo &DCI) {
9535   // Bitcast an i64 load inserted into a vector to f64.
9536   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9537   EVT VT = N->getValueType(0);
9538   SDNode *Elt = N->getOperand(1).getNode();
9539   if (VT.getVectorElementType() != MVT::i64 ||
9540       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9541     return SDValue();
9542 
9543   SelectionDAG &DAG = DCI.DAG;
9544   SDLoc dl(N);
9545   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9546                                  VT.getVectorNumElements());
9547   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9548   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9549   // Make the DAGCombiner fold the bitcasts.
9550   DCI.AddToWorklist(Vec.getNode());
9551   DCI.AddToWorklist(V.getNode());
9552   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9553                                Vec, V, N->getOperand(2));
9554   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9555 }
9556 
9557 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9558 /// ISD::VECTOR_SHUFFLE.
9559 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9560   // The LLVM shufflevector instruction does not require the shuffle mask
9561   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9562   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9563   // operands do not match the mask length, they are extended by concatenating
9564   // them with undef vectors.  That is probably the right thing for other
9565   // targets, but for NEON it is better to concatenate two double-register
9566   // size vector operands into a single quad-register size vector.  Do that
9567   // transformation here:
9568   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9569   //   shuffle(concat(v1, v2), undef)
9570   SDValue Op0 = N->getOperand(0);
9571   SDValue Op1 = N->getOperand(1);
9572   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9573       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9574       Op0.getNumOperands() != 2 ||
9575       Op1.getNumOperands() != 2)
9576     return SDValue();
9577   SDValue Concat0Op1 = Op0.getOperand(1);
9578   SDValue Concat1Op1 = Op1.getOperand(1);
9579   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9580       Concat1Op1.getOpcode() != ISD::UNDEF)
9581     return SDValue();
9582   // Skip the transformation if any of the types are illegal.
9583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9584   EVT VT = N->getValueType(0);
9585   if (!TLI.isTypeLegal(VT) ||
9586       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9587       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9588     return SDValue();
9589 
9590   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9591                                   Op0.getOperand(0), Op1.getOperand(0));
9592   // Translate the shuffle mask.
9593   SmallVector<int, 16> NewMask;
9594   unsigned NumElts = VT.getVectorNumElements();
9595   unsigned HalfElts = NumElts/2;
9596   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9597   for (unsigned n = 0; n < NumElts; ++n) {
9598     int MaskElt = SVN->getMaskElt(n);
9599     int NewElt = -1;
9600     if (MaskElt < (int)HalfElts)
9601       NewElt = MaskElt;
9602     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9603       NewElt = HalfElts + MaskElt - NumElts;
9604     NewMask.push_back(NewElt);
9605   }
9606   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9607                               DAG.getUNDEF(VT), NewMask.data());
9608 }
9609 
9610 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9611 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9612 /// base address updates.
9613 /// For generic load/stores, the memory type is assumed to be a vector.
9614 /// The caller is assumed to have checked legality.
9615 static SDValue CombineBaseUpdate(SDNode *N,
9616                                  TargetLowering::DAGCombinerInfo &DCI) {
9617   SelectionDAG &DAG = DCI.DAG;
9618   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9619                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9620   const bool isStore = N->getOpcode() == ISD::STORE;
9621   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9622   SDValue Addr = N->getOperand(AddrOpIdx);
9623   MemSDNode *MemN = cast<MemSDNode>(N);
9624   SDLoc dl(N);
9625 
9626   // Search for a use of the address operand that is an increment.
9627   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9628          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9629     SDNode *User = *UI;
9630     if (User->getOpcode() != ISD::ADD ||
9631         UI.getUse().getResNo() != Addr.getResNo())
9632       continue;
9633 
9634     // Check that the add is independent of the load/store.  Otherwise, folding
9635     // it would create a cycle.
9636     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9637       continue;
9638 
9639     // Find the new opcode for the updating load/store.
9640     bool isLoadOp = true;
9641     bool isLaneOp = false;
9642     unsigned NewOpc = 0;
9643     unsigned NumVecs = 0;
9644     if (isIntrinsic) {
9645       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9646       switch (IntNo) {
9647       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9648       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9649         NumVecs = 1; break;
9650       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9651         NumVecs = 2; break;
9652       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9653         NumVecs = 3; break;
9654       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9655         NumVecs = 4; break;
9656       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9657         NumVecs = 2; isLaneOp = true; break;
9658       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9659         NumVecs = 3; isLaneOp = true; break;
9660       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9661         NumVecs = 4; isLaneOp = true; break;
9662       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9663         NumVecs = 1; isLoadOp = false; break;
9664       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9665         NumVecs = 2; isLoadOp = false; break;
9666       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9667         NumVecs = 3; isLoadOp = false; break;
9668       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9669         NumVecs = 4; isLoadOp = false; break;
9670       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9671         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9672       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9673         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9674       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9675         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9676       }
9677     } else {
9678       isLaneOp = true;
9679       switch (N->getOpcode()) {
9680       default: llvm_unreachable("unexpected opcode for Neon base update");
9681       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9682       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9683       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9684       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9685         NumVecs = 1; isLaneOp = false; break;
9686       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9687         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9688       }
9689     }
9690 
9691     // Find the size of memory referenced by the load/store.
9692     EVT VecTy;
9693     if (isLoadOp) {
9694       VecTy = N->getValueType(0);
9695     } else if (isIntrinsic) {
9696       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9697     } else {
9698       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9699       VecTy = N->getOperand(1).getValueType();
9700     }
9701 
9702     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9703     if (isLaneOp)
9704       NumBytes /= VecTy.getVectorNumElements();
9705 
9706     // If the increment is a constant, it must match the memory ref size.
9707     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9708     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9709       uint64_t IncVal = CInc->getZExtValue();
9710       if (IncVal != NumBytes)
9711         continue;
9712     } else if (NumBytes >= 3 * 16) {
9713       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9714       // separate instructions that make it harder to use a non-constant update.
9715       continue;
9716     }
9717 
9718     // OK, we found an ADD we can fold into the base update.
9719     // Now, create a _UPD node, taking care of not breaking alignment.
9720 
9721     EVT AlignedVecTy = VecTy;
9722     unsigned Alignment = MemN->getAlignment();
9723 
9724     // If this is a less-than-standard-aligned load/store, change the type to
9725     // match the standard alignment.
9726     // The alignment is overlooked when selecting _UPD variants; and it's
9727     // easier to introduce bitcasts here than fix that.
9728     // There are 3 ways to get to this base-update combine:
9729     // - intrinsics: they are assumed to be properly aligned (to the standard
9730     //   alignment of the memory type), so we don't need to do anything.
9731     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9732     //   intrinsics, so, likewise, there's nothing to do.
9733     // - generic load/store instructions: the alignment is specified as an
9734     //   explicit operand, rather than implicitly as the standard alignment
9735     //   of the memory type (like the intrisics).  We need to change the
9736     //   memory type to match the explicit alignment.  That way, we don't
9737     //   generate non-standard-aligned ARMISD::VLDx nodes.
9738     if (isa<LSBaseSDNode>(N)) {
9739       if (Alignment == 0)
9740         Alignment = 1;
9741       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9742         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9743         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9744         assert(!isLaneOp && "Unexpected generic load/store lane.");
9745         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9746         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9747       }
9748       // Don't set an explicit alignment on regular load/stores that we want
9749       // to transform to VLD/VST 1_UPD nodes.
9750       // This matches the behavior of regular load/stores, which only get an
9751       // explicit alignment if the MMO alignment is larger than the standard
9752       // alignment of the memory type.
9753       // Intrinsics, however, always get an explicit alignment, set to the
9754       // alignment of the MMO.
9755       Alignment = 1;
9756     }
9757 
9758     // Create the new updating load/store node.
9759     // First, create an SDVTList for the new updating node's results.
9760     EVT Tys[6];
9761     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9762     unsigned n;
9763     for (n = 0; n < NumResultVecs; ++n)
9764       Tys[n] = AlignedVecTy;
9765     Tys[n++] = MVT::i32;
9766     Tys[n] = MVT::Other;
9767     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9768 
9769     // Then, gather the new node's operands.
9770     SmallVector<SDValue, 8> Ops;
9771     Ops.push_back(N->getOperand(0)); // incoming chain
9772     Ops.push_back(N->getOperand(AddrOpIdx));
9773     Ops.push_back(Inc);
9774 
9775     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9776       // Try to match the intrinsic's signature
9777       Ops.push_back(StN->getValue());
9778     } else {
9779       // Loads (and of course intrinsics) match the intrinsics' signature,
9780       // so just add all but the alignment operand.
9781       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9782         Ops.push_back(N->getOperand(i));
9783     }
9784 
9785     // For all node types, the alignment operand is always the last one.
9786     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9787 
9788     // If this is a non-standard-aligned STORE, the penultimate operand is the
9789     // stored value.  Bitcast it to the aligned type.
9790     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9791       SDValue &StVal = Ops[Ops.size()-2];
9792       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9793     }
9794 
9795     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9796                                            Ops, AlignedVecTy,
9797                                            MemN->getMemOperand());
9798 
9799     // Update the uses.
9800     SmallVector<SDValue, 5> NewResults;
9801     for (unsigned i = 0; i < NumResultVecs; ++i)
9802       NewResults.push_back(SDValue(UpdN.getNode(), i));
9803 
9804     // If this is an non-standard-aligned LOAD, the first result is the loaded
9805     // value.  Bitcast it to the expected result type.
9806     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9807       SDValue &LdVal = NewResults[0];
9808       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9809     }
9810 
9811     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9812     DCI.CombineTo(N, NewResults);
9813     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9814 
9815     break;
9816   }
9817   return SDValue();
9818 }
9819 
9820 static SDValue PerformVLDCombine(SDNode *N,
9821                                  TargetLowering::DAGCombinerInfo &DCI) {
9822   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9823     return SDValue();
9824 
9825   return CombineBaseUpdate(N, DCI);
9826 }
9827 
9828 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9829 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9830 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9831 /// return true.
9832 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9833   SelectionDAG &DAG = DCI.DAG;
9834   EVT VT = N->getValueType(0);
9835   // vldN-dup instructions only support 64-bit vectors for N > 1.
9836   if (!VT.is64BitVector())
9837     return false;
9838 
9839   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9840   SDNode *VLD = N->getOperand(0).getNode();
9841   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9842     return false;
9843   unsigned NumVecs = 0;
9844   unsigned NewOpc = 0;
9845   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9846   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9847     NumVecs = 2;
9848     NewOpc = ARMISD::VLD2DUP;
9849   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9850     NumVecs = 3;
9851     NewOpc = ARMISD::VLD3DUP;
9852   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9853     NumVecs = 4;
9854     NewOpc = ARMISD::VLD4DUP;
9855   } else {
9856     return false;
9857   }
9858 
9859   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9860   // numbers match the load.
9861   unsigned VLDLaneNo =
9862     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9863   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9864        UI != UE; ++UI) {
9865     // Ignore uses of the chain result.
9866     if (UI.getUse().getResNo() == NumVecs)
9867       continue;
9868     SDNode *User = *UI;
9869     if (User->getOpcode() != ARMISD::VDUPLANE ||
9870         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9871       return false;
9872   }
9873 
9874   // Create the vldN-dup node.
9875   EVT Tys[5];
9876   unsigned n;
9877   for (n = 0; n < NumVecs; ++n)
9878     Tys[n] = VT;
9879   Tys[n] = MVT::Other;
9880   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9881   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9882   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9883   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9884                                            Ops, VLDMemInt->getMemoryVT(),
9885                                            VLDMemInt->getMemOperand());
9886 
9887   // Update the uses.
9888   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9889        UI != UE; ++UI) {
9890     unsigned ResNo = UI.getUse().getResNo();
9891     // Ignore uses of the chain result.
9892     if (ResNo == NumVecs)
9893       continue;
9894     SDNode *User = *UI;
9895     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9896   }
9897 
9898   // Now the vldN-lane intrinsic is dead except for its chain result.
9899   // Update uses of the chain.
9900   std::vector<SDValue> VLDDupResults;
9901   for (unsigned n = 0; n < NumVecs; ++n)
9902     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9903   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9904   DCI.CombineTo(VLD, VLDDupResults);
9905 
9906   return true;
9907 }
9908 
9909 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9910 /// ARMISD::VDUPLANE.
9911 static SDValue PerformVDUPLANECombine(SDNode *N,
9912                                       TargetLowering::DAGCombinerInfo &DCI) {
9913   SDValue Op = N->getOperand(0);
9914 
9915   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9916   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9917   if (CombineVLDDUP(N, DCI))
9918     return SDValue(N, 0);
9919 
9920   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9921   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9922   while (Op.getOpcode() == ISD::BITCAST)
9923     Op = Op.getOperand(0);
9924   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9925     return SDValue();
9926 
9927   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9928   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9929   // The canonical VMOV for a zero vector uses a 32-bit element size.
9930   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9931   unsigned EltBits;
9932   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9933     EltSize = 8;
9934   EVT VT = N->getValueType(0);
9935   if (EltSize > VT.getVectorElementType().getSizeInBits())
9936     return SDValue();
9937 
9938   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9939 }
9940 
9941 static SDValue PerformLOADCombine(SDNode *N,
9942                                   TargetLowering::DAGCombinerInfo &DCI) {
9943   EVT VT = N->getValueType(0);
9944 
9945   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9946   if (ISD::isNormalLoad(N) && VT.isVector() &&
9947       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9948     return CombineBaseUpdate(N, DCI);
9949 
9950   return SDValue();
9951 }
9952 
9953 /// PerformSTORECombine - Target-specific dag combine xforms for
9954 /// ISD::STORE.
9955 static SDValue PerformSTORECombine(SDNode *N,
9956                                    TargetLowering::DAGCombinerInfo &DCI) {
9957   StoreSDNode *St = cast<StoreSDNode>(N);
9958   if (St->isVolatile())
9959     return SDValue();
9960 
9961   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9962   // pack all of the elements in one place.  Next, store to memory in fewer
9963   // chunks.
9964   SDValue StVal = St->getValue();
9965   EVT VT = StVal.getValueType();
9966   if (St->isTruncatingStore() && VT.isVector()) {
9967     SelectionDAG &DAG = DCI.DAG;
9968     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9969     EVT StVT = St->getMemoryVT();
9970     unsigned NumElems = VT.getVectorNumElements();
9971     assert(StVT != VT && "Cannot truncate to the same type");
9972     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9973     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9974 
9975     // From, To sizes and ElemCount must be pow of two
9976     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9977 
9978     // We are going to use the original vector elt for storing.
9979     // Accumulated smaller vector elements must be a multiple of the store size.
9980     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9981 
9982     unsigned SizeRatio  = FromEltSz / ToEltSz;
9983     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9984 
9985     // Create a type on which we perform the shuffle.
9986     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9987                                      NumElems*SizeRatio);
9988     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9989 
9990     SDLoc DL(St);
9991     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9992     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9993     for (unsigned i = 0; i < NumElems; ++i)
9994       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9995                           ? (i + 1) * SizeRatio - 1
9996                           : i * SizeRatio;
9997 
9998     // Can't shuffle using an illegal type.
9999     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10000 
10001     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10002                                 DAG.getUNDEF(WideVec.getValueType()),
10003                                 ShuffleVec.data());
10004     // At this point all of the data is stored at the bottom of the
10005     // register. We now need to save it to mem.
10006 
10007     // Find the largest store unit
10008     MVT StoreType = MVT::i8;
10009     for (MVT Tp : MVT::integer_valuetypes()) {
10010       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10011         StoreType = Tp;
10012     }
10013     // Didn't find a legal store type.
10014     if (!TLI.isTypeLegal(StoreType))
10015       return SDValue();
10016 
10017     // Bitcast the original vector into a vector of store-size units
10018     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10019             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10020     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10021     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10022     SmallVector<SDValue, 8> Chains;
10023     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10024                                         TLI.getPointerTy(DAG.getDataLayout()));
10025     SDValue BasePtr = St->getBasePtr();
10026 
10027     // Perform one or more big stores into memory.
10028     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10029     for (unsigned I = 0; I < E; I++) {
10030       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10031                                    StoreType, ShuffWide,
10032                                    DAG.getIntPtrConstant(I, DL));
10033       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10034                                 St->getPointerInfo(), St->isVolatile(),
10035                                 St->isNonTemporal(), St->getAlignment());
10036       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10037                             Increment);
10038       Chains.push_back(Ch);
10039     }
10040     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10041   }
10042 
10043   if (!ISD::isNormalStore(St))
10044     return SDValue();
10045 
10046   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10047   // ARM stores of arguments in the same cache line.
10048   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10049       StVal.getNode()->hasOneUse()) {
10050     SelectionDAG  &DAG = DCI.DAG;
10051     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10052     SDLoc DL(St);
10053     SDValue BasePtr = St->getBasePtr();
10054     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
10055                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
10056                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
10057                                   St->isNonTemporal(), St->getAlignment());
10058 
10059     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10060                                     DAG.getConstant(4, DL, MVT::i32));
10061     return DAG.getStore(NewST1.getValue(0), DL,
10062                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10063                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
10064                         St->isNonTemporal(),
10065                         std::min(4U, St->getAlignment() / 2));
10066   }
10067 
10068   if (StVal.getValueType() == MVT::i64 &&
10069       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10070 
10071     // Bitcast an i64 store extracted from a vector to f64.
10072     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10073     SelectionDAG &DAG = DCI.DAG;
10074     SDLoc dl(StVal);
10075     SDValue IntVec = StVal.getOperand(0);
10076     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10077                                    IntVec.getValueType().getVectorNumElements());
10078     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10079     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10080                                  Vec, StVal.getOperand(1));
10081     dl = SDLoc(N);
10082     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10083     // Make the DAGCombiner fold the bitcasts.
10084     DCI.AddToWorklist(Vec.getNode());
10085     DCI.AddToWorklist(ExtElt.getNode());
10086     DCI.AddToWorklist(V.getNode());
10087     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10088                         St->getPointerInfo(), St->isVolatile(),
10089                         St->isNonTemporal(), St->getAlignment(),
10090                         St->getAAInfo());
10091   }
10092 
10093   // If this is a legal vector store, try to combine it into a VST1_UPD.
10094   if (ISD::isNormalStore(N) && VT.isVector() &&
10095       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10096     return CombineBaseUpdate(N, DCI);
10097 
10098   return SDValue();
10099 }
10100 
10101 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10102 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10103 /// when the VMUL has a constant operand that is a power of 2.
10104 ///
10105 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10106 ///  vmul.f32        d16, d17, d16
10107 ///  vcvt.s32.f32    d16, d16
10108 /// becomes:
10109 ///  vcvt.s32.f32    d16, d16, #3
10110 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10111                                   const ARMSubtarget *Subtarget) {
10112   if (!Subtarget->hasNEON())
10113     return SDValue();
10114 
10115   SDValue Op = N->getOperand(0);
10116   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
10117     return SDValue();
10118 
10119   SDValue ConstVec = Op->getOperand(1);
10120   if (!isa<BuildVectorSDNode>(ConstVec))
10121     return SDValue();
10122 
10123   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10124   uint32_t FloatBits = FloatTy.getSizeInBits();
10125   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10126   uint32_t IntBits = IntTy.getSizeInBits();
10127   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10128   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10129     // These instructions only exist converting from f32 to i32. We can handle
10130     // smaller integers by generating an extra truncate, but larger ones would
10131     // be lossy. We also can't handle more then 4 lanes, since these intructions
10132     // only support v2i32/v4i32 types.
10133     return SDValue();
10134   }
10135 
10136   BitVector UndefElements;
10137   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10138   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10139   if (C == -1 || C == 0 || C > 32)
10140     return SDValue();
10141 
10142   SDLoc dl(N);
10143   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10144   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10145     Intrinsic::arm_neon_vcvtfp2fxu;
10146   SDValue FixConv = DAG.getNode(
10147       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10148       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10149       DAG.getConstant(C, dl, MVT::i32));
10150 
10151   if (IntBits < FloatBits)
10152     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10153 
10154   return FixConv;
10155 }
10156 
10157 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10158 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10159 /// when the VDIV has a constant operand that is a power of 2.
10160 ///
10161 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10162 ///  vcvt.f32.s32    d16, d16
10163 ///  vdiv.f32        d16, d17, d16
10164 /// becomes:
10165 ///  vcvt.f32.s32    d16, d16, #3
10166 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10167                                   const ARMSubtarget *Subtarget) {
10168   if (!Subtarget->hasNEON())
10169     return SDValue();
10170 
10171   SDValue Op = N->getOperand(0);
10172   unsigned OpOpcode = Op.getNode()->getOpcode();
10173   if (!N->getValueType(0).isVector() ||
10174       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10175     return SDValue();
10176 
10177   SDValue ConstVec = N->getOperand(1);
10178   if (!isa<BuildVectorSDNode>(ConstVec))
10179     return SDValue();
10180 
10181   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10182   uint32_t FloatBits = FloatTy.getSizeInBits();
10183   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10184   uint32_t IntBits = IntTy.getSizeInBits();
10185   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10186   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10187     // These instructions only exist converting from i32 to f32. We can handle
10188     // smaller integers by generating an extra extend, but larger ones would
10189     // be lossy. We also can't handle more then 4 lanes, since these intructions
10190     // only support v2i32/v4i32 types.
10191     return SDValue();
10192   }
10193 
10194   BitVector UndefElements;
10195   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10196   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10197   if (C == -1 || C == 0 || C > 32)
10198     return SDValue();
10199 
10200   SDLoc dl(N);
10201   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10202   SDValue ConvInput = Op.getOperand(0);
10203   if (IntBits < FloatBits)
10204     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10205                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10206                             ConvInput);
10207 
10208   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10209     Intrinsic::arm_neon_vcvtfxu2fp;
10210   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10211                      Op.getValueType(),
10212                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10213                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10214 }
10215 
10216 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10217 /// operand of a vector shift operation, where all the elements of the
10218 /// build_vector must have the same constant integer value.
10219 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10220   // Ignore bit_converts.
10221   while (Op.getOpcode() == ISD::BITCAST)
10222     Op = Op.getOperand(0);
10223   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10224   APInt SplatBits, SplatUndef;
10225   unsigned SplatBitSize;
10226   bool HasAnyUndefs;
10227   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10228                                       HasAnyUndefs, ElementBits) ||
10229       SplatBitSize > ElementBits)
10230     return false;
10231   Cnt = SplatBits.getSExtValue();
10232   return true;
10233 }
10234 
10235 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10236 /// operand of a vector shift left operation.  That value must be in the range:
10237 ///   0 <= Value < ElementBits for a left shift; or
10238 ///   0 <= Value <= ElementBits for a long left shift.
10239 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10240   assert(VT.isVector() && "vector shift count is not a vector type");
10241   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10242   if (! getVShiftImm(Op, ElementBits, Cnt))
10243     return false;
10244   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10245 }
10246 
10247 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10248 /// operand of a vector shift right operation.  For a shift opcode, the value
10249 /// is positive, but for an intrinsic the value count must be negative. The
10250 /// absolute value must be in the range:
10251 ///   1 <= |Value| <= ElementBits for a right shift; or
10252 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10253 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10254                          int64_t &Cnt) {
10255   assert(VT.isVector() && "vector shift count is not a vector type");
10256   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10257   if (! getVShiftImm(Op, ElementBits, Cnt))
10258     return false;
10259   if (!isIntrinsic)
10260     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10261   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10262     Cnt = -Cnt;
10263     return true;
10264   }
10265   return false;
10266 }
10267 
10268 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10269 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10270   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10271   switch (IntNo) {
10272   default:
10273     // Don't do anything for most intrinsics.
10274     break;
10275 
10276   // Vector shifts: check for immediate versions and lower them.
10277   // Note: This is done during DAG combining instead of DAG legalizing because
10278   // the build_vectors for 64-bit vector element shift counts are generally
10279   // not legal, and it is hard to see their values after they get legalized to
10280   // loads from a constant pool.
10281   case Intrinsic::arm_neon_vshifts:
10282   case Intrinsic::arm_neon_vshiftu:
10283   case Intrinsic::arm_neon_vrshifts:
10284   case Intrinsic::arm_neon_vrshiftu:
10285   case Intrinsic::arm_neon_vrshiftn:
10286   case Intrinsic::arm_neon_vqshifts:
10287   case Intrinsic::arm_neon_vqshiftu:
10288   case Intrinsic::arm_neon_vqshiftsu:
10289   case Intrinsic::arm_neon_vqshiftns:
10290   case Intrinsic::arm_neon_vqshiftnu:
10291   case Intrinsic::arm_neon_vqshiftnsu:
10292   case Intrinsic::arm_neon_vqrshiftns:
10293   case Intrinsic::arm_neon_vqrshiftnu:
10294   case Intrinsic::arm_neon_vqrshiftnsu: {
10295     EVT VT = N->getOperand(1).getValueType();
10296     int64_t Cnt;
10297     unsigned VShiftOpc = 0;
10298 
10299     switch (IntNo) {
10300     case Intrinsic::arm_neon_vshifts:
10301     case Intrinsic::arm_neon_vshiftu:
10302       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10303         VShiftOpc = ARMISD::VSHL;
10304         break;
10305       }
10306       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10307         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10308                      ARMISD::VSHRs : ARMISD::VSHRu);
10309         break;
10310       }
10311       return SDValue();
10312 
10313     case Intrinsic::arm_neon_vrshifts:
10314     case Intrinsic::arm_neon_vrshiftu:
10315       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10316         break;
10317       return SDValue();
10318 
10319     case Intrinsic::arm_neon_vqshifts:
10320     case Intrinsic::arm_neon_vqshiftu:
10321       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10322         break;
10323       return SDValue();
10324 
10325     case Intrinsic::arm_neon_vqshiftsu:
10326       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10327         break;
10328       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10329 
10330     case Intrinsic::arm_neon_vrshiftn:
10331     case Intrinsic::arm_neon_vqshiftns:
10332     case Intrinsic::arm_neon_vqshiftnu:
10333     case Intrinsic::arm_neon_vqshiftnsu:
10334     case Intrinsic::arm_neon_vqrshiftns:
10335     case Intrinsic::arm_neon_vqrshiftnu:
10336     case Intrinsic::arm_neon_vqrshiftnsu:
10337       // Narrowing shifts require an immediate right shift.
10338       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10339         break;
10340       llvm_unreachable("invalid shift count for narrowing vector shift "
10341                        "intrinsic");
10342 
10343     default:
10344       llvm_unreachable("unhandled vector shift");
10345     }
10346 
10347     switch (IntNo) {
10348     case Intrinsic::arm_neon_vshifts:
10349     case Intrinsic::arm_neon_vshiftu:
10350       // Opcode already set above.
10351       break;
10352     case Intrinsic::arm_neon_vrshifts:
10353       VShiftOpc = ARMISD::VRSHRs; break;
10354     case Intrinsic::arm_neon_vrshiftu:
10355       VShiftOpc = ARMISD::VRSHRu; break;
10356     case Intrinsic::arm_neon_vrshiftn:
10357       VShiftOpc = ARMISD::VRSHRN; break;
10358     case Intrinsic::arm_neon_vqshifts:
10359       VShiftOpc = ARMISD::VQSHLs; break;
10360     case Intrinsic::arm_neon_vqshiftu:
10361       VShiftOpc = ARMISD::VQSHLu; break;
10362     case Intrinsic::arm_neon_vqshiftsu:
10363       VShiftOpc = ARMISD::VQSHLsu; break;
10364     case Intrinsic::arm_neon_vqshiftns:
10365       VShiftOpc = ARMISD::VQSHRNs; break;
10366     case Intrinsic::arm_neon_vqshiftnu:
10367       VShiftOpc = ARMISD::VQSHRNu; break;
10368     case Intrinsic::arm_neon_vqshiftnsu:
10369       VShiftOpc = ARMISD::VQSHRNsu; break;
10370     case Intrinsic::arm_neon_vqrshiftns:
10371       VShiftOpc = ARMISD::VQRSHRNs; break;
10372     case Intrinsic::arm_neon_vqrshiftnu:
10373       VShiftOpc = ARMISD::VQRSHRNu; break;
10374     case Intrinsic::arm_neon_vqrshiftnsu:
10375       VShiftOpc = ARMISD::VQRSHRNsu; break;
10376     }
10377 
10378     SDLoc dl(N);
10379     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10380                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10381   }
10382 
10383   case Intrinsic::arm_neon_vshiftins: {
10384     EVT VT = N->getOperand(1).getValueType();
10385     int64_t Cnt;
10386     unsigned VShiftOpc = 0;
10387 
10388     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10389       VShiftOpc = ARMISD::VSLI;
10390     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10391       VShiftOpc = ARMISD::VSRI;
10392     else {
10393       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10394     }
10395 
10396     SDLoc dl(N);
10397     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10398                        N->getOperand(1), N->getOperand(2),
10399                        DAG.getConstant(Cnt, dl, MVT::i32));
10400   }
10401 
10402   case Intrinsic::arm_neon_vqrshifts:
10403   case Intrinsic::arm_neon_vqrshiftu:
10404     // No immediate versions of these to check for.
10405     break;
10406   }
10407 
10408   return SDValue();
10409 }
10410 
10411 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10412 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10413 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10414 /// vector element shift counts are generally not legal, and it is hard to see
10415 /// their values after they get legalized to loads from a constant pool.
10416 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10417                                    const ARMSubtarget *ST) {
10418   EVT VT = N->getValueType(0);
10419   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10420     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10421     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10422     SDValue N1 = N->getOperand(1);
10423     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10424       SDValue N0 = N->getOperand(0);
10425       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10426           DAG.MaskedValueIsZero(N0.getOperand(0),
10427                                 APInt::getHighBitsSet(32, 16)))
10428         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10429     }
10430   }
10431 
10432   // Nothing to be done for scalar shifts.
10433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10434   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10435     return SDValue();
10436 
10437   assert(ST->hasNEON() && "unexpected vector shift");
10438   int64_t Cnt;
10439 
10440   switch (N->getOpcode()) {
10441   default: llvm_unreachable("unexpected shift opcode");
10442 
10443   case ISD::SHL:
10444     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10445       SDLoc dl(N);
10446       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10447                          DAG.getConstant(Cnt, dl, MVT::i32));
10448     }
10449     break;
10450 
10451   case ISD::SRA:
10452   case ISD::SRL:
10453     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10454       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10455                             ARMISD::VSHRs : ARMISD::VSHRu);
10456       SDLoc dl(N);
10457       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10458                          DAG.getConstant(Cnt, dl, MVT::i32));
10459     }
10460   }
10461   return SDValue();
10462 }
10463 
10464 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10465 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10466 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10467                                     const ARMSubtarget *ST) {
10468   SDValue N0 = N->getOperand(0);
10469 
10470   // Check for sign- and zero-extensions of vector extract operations of 8-
10471   // and 16-bit vector elements.  NEON supports these directly.  They are
10472   // handled during DAG combining because type legalization will promote them
10473   // to 32-bit types and it is messy to recognize the operations after that.
10474   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10475     SDValue Vec = N0.getOperand(0);
10476     SDValue Lane = N0.getOperand(1);
10477     EVT VT = N->getValueType(0);
10478     EVT EltVT = N0.getValueType();
10479     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10480 
10481     if (VT == MVT::i32 &&
10482         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10483         TLI.isTypeLegal(Vec.getValueType()) &&
10484         isa<ConstantSDNode>(Lane)) {
10485 
10486       unsigned Opc = 0;
10487       switch (N->getOpcode()) {
10488       default: llvm_unreachable("unexpected opcode");
10489       case ISD::SIGN_EXTEND:
10490         Opc = ARMISD::VGETLANEs;
10491         break;
10492       case ISD::ZERO_EXTEND:
10493       case ISD::ANY_EXTEND:
10494         Opc = ARMISD::VGETLANEu;
10495         break;
10496       }
10497       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10498     }
10499   }
10500 
10501   return SDValue();
10502 }
10503 
10504 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10505                              APInt &KnownOne) {
10506   if (Op.getOpcode() == ARMISD::BFI) {
10507     // Conservatively, we can recurse down the first operand
10508     // and just mask out all affected bits.
10509     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10510 
10511     // The operand to BFI is already a mask suitable for removing the bits it
10512     // sets.
10513     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10514     APInt Mask = CI->getAPIntValue();
10515     KnownZero &= Mask;
10516     KnownOne &= Mask;
10517     return;
10518   }
10519   if (Op.getOpcode() == ARMISD::CMOV) {
10520     APInt KZ2(KnownZero.getBitWidth(), 0);
10521     APInt KO2(KnownOne.getBitWidth(), 0);
10522     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10523     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10524 
10525     KnownZero &= KZ2;
10526     KnownOne &= KO2;
10527     return;
10528   }
10529   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10530 }
10531 
10532 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10533   // If we have a CMOV, OR and AND combination such as:
10534   //   if (x & CN)
10535   //     y |= CM;
10536   //
10537   // And:
10538   //   * CN is a single bit;
10539   //   * All bits covered by CM are known zero in y
10540   //
10541   // Then we can convert this into a sequence of BFI instructions. This will
10542   // always be a win if CM is a single bit, will always be no worse than the
10543   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10544   // three bits (due to the extra IT instruction).
10545 
10546   SDValue Op0 = CMOV->getOperand(0);
10547   SDValue Op1 = CMOV->getOperand(1);
10548   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10549   auto CC = CCNode->getAPIntValue().getLimitedValue();
10550   SDValue CmpZ = CMOV->getOperand(4);
10551 
10552   // The compare must be against zero.
10553   if (!isNullConstant(CmpZ->getOperand(1)))
10554     return SDValue();
10555 
10556   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10557   SDValue And = CmpZ->getOperand(0);
10558   if (And->getOpcode() != ISD::AND)
10559     return SDValue();
10560   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10561   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10562     return SDValue();
10563   SDValue X = And->getOperand(0);
10564 
10565   if (CC == ARMCC::EQ) {
10566     // We're performing an "equal to zero" compare. Swap the operands so we
10567     // canonicalize on a "not equal to zero" compare.
10568     std::swap(Op0, Op1);
10569   } else {
10570     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10571   }
10572 
10573   if (Op1->getOpcode() != ISD::OR)
10574     return SDValue();
10575 
10576   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10577   if (!OrC)
10578     return SDValue();
10579   SDValue Y = Op1->getOperand(0);
10580 
10581   if (Op0 != Y)
10582     return SDValue();
10583 
10584   // Now, is it profitable to continue?
10585   APInt OrCI = OrC->getAPIntValue();
10586   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10587   if (OrCI.countPopulation() > Heuristic)
10588     return SDValue();
10589 
10590   // Lastly, can we determine that the bits defined by OrCI
10591   // are zero in Y?
10592   APInt KnownZero, KnownOne;
10593   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10594   if ((OrCI & KnownZero) != OrCI)
10595     return SDValue();
10596 
10597   // OK, we can do the combine.
10598   SDValue V = Y;
10599   SDLoc dl(X);
10600   EVT VT = X.getValueType();
10601   unsigned BitInX = AndC->getAPIntValue().logBase2();
10602 
10603   if (BitInX != 0) {
10604     // We must shift X first.
10605     X = DAG.getNode(ISD::SRL, dl, VT, X,
10606                     DAG.getConstant(BitInX, dl, VT));
10607   }
10608 
10609   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10610        BitInY < NumActiveBits; ++BitInY) {
10611     if (OrCI[BitInY] == 0)
10612       continue;
10613     APInt Mask(VT.getSizeInBits(), 0);
10614     Mask.setBit(BitInY);
10615     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10616                     // Confusingly, the operand is an *inverted* mask.
10617                     DAG.getConstant(~Mask, dl, VT));
10618   }
10619 
10620   return V;
10621 }
10622 
10623 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10624 SDValue
10625 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10626   SDValue Cmp = N->getOperand(4);
10627   if (Cmp.getOpcode() != ARMISD::CMPZ)
10628     // Only looking at EQ and NE cases.
10629     return SDValue();
10630 
10631   EVT VT = N->getValueType(0);
10632   SDLoc dl(N);
10633   SDValue LHS = Cmp.getOperand(0);
10634   SDValue RHS = Cmp.getOperand(1);
10635   SDValue FalseVal = N->getOperand(0);
10636   SDValue TrueVal = N->getOperand(1);
10637   SDValue ARMcc = N->getOperand(2);
10638   ARMCC::CondCodes CC =
10639     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10640 
10641   // BFI is only available on V6T2+.
10642   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10643     SDValue R = PerformCMOVToBFICombine(N, DAG);
10644     if (R)
10645       return R;
10646   }
10647 
10648   // Simplify
10649   //   mov     r1, r0
10650   //   cmp     r1, x
10651   //   mov     r0, y
10652   //   moveq   r0, x
10653   // to
10654   //   cmp     r0, x
10655   //   movne   r0, y
10656   //
10657   //   mov     r1, r0
10658   //   cmp     r1, x
10659   //   mov     r0, x
10660   //   movne   r0, y
10661   // to
10662   //   cmp     r0, x
10663   //   movne   r0, y
10664   /// FIXME: Turn this into a target neutral optimization?
10665   SDValue Res;
10666   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10667     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10668                       N->getOperand(3), Cmp);
10669   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10670     SDValue ARMcc;
10671     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10672     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10673                       N->getOperand(3), NewCmp);
10674   }
10675 
10676   if (Res.getNode()) {
10677     APInt KnownZero, KnownOne;
10678     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10679     // Capture demanded bits information that would be otherwise lost.
10680     if (KnownZero == 0xfffffffe)
10681       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10682                         DAG.getValueType(MVT::i1));
10683     else if (KnownZero == 0xffffff00)
10684       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10685                         DAG.getValueType(MVT::i8));
10686     else if (KnownZero == 0xffff0000)
10687       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10688                         DAG.getValueType(MVT::i16));
10689   }
10690 
10691   return Res;
10692 }
10693 
10694 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10695                                              DAGCombinerInfo &DCI) const {
10696   switch (N->getOpcode()) {
10697   default: break;
10698   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10699   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10700   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10701   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10702   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10703   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10704   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10705   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10706   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10707   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10708   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10709   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10710   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10711   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10712   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10713   case ISD::FP_TO_SINT:
10714   case ISD::FP_TO_UINT:
10715     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10716   case ISD::FDIV:
10717     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10718   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10719   case ISD::SHL:
10720   case ISD::SRA:
10721   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10722   case ISD::SIGN_EXTEND:
10723   case ISD::ZERO_EXTEND:
10724   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10725   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10726   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10727   case ARMISD::VLD2DUP:
10728   case ARMISD::VLD3DUP:
10729   case ARMISD::VLD4DUP:
10730     return PerformVLDCombine(N, DCI);
10731   case ARMISD::BUILD_VECTOR:
10732     return PerformARMBUILD_VECTORCombine(N, DCI);
10733   case ISD::INTRINSIC_VOID:
10734   case ISD::INTRINSIC_W_CHAIN:
10735     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10736     case Intrinsic::arm_neon_vld1:
10737     case Intrinsic::arm_neon_vld2:
10738     case Intrinsic::arm_neon_vld3:
10739     case Intrinsic::arm_neon_vld4:
10740     case Intrinsic::arm_neon_vld2lane:
10741     case Intrinsic::arm_neon_vld3lane:
10742     case Intrinsic::arm_neon_vld4lane:
10743     case Intrinsic::arm_neon_vst1:
10744     case Intrinsic::arm_neon_vst2:
10745     case Intrinsic::arm_neon_vst3:
10746     case Intrinsic::arm_neon_vst4:
10747     case Intrinsic::arm_neon_vst2lane:
10748     case Intrinsic::arm_neon_vst3lane:
10749     case Intrinsic::arm_neon_vst4lane:
10750       return PerformVLDCombine(N, DCI);
10751     default: break;
10752     }
10753     break;
10754   }
10755   return SDValue();
10756 }
10757 
10758 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10759                                                           EVT VT) const {
10760   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10761 }
10762 
10763 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10764                                                        unsigned,
10765                                                        unsigned,
10766                                                        bool *Fast) const {
10767   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10768   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10769 
10770   switch (VT.getSimpleVT().SimpleTy) {
10771   default:
10772     return false;
10773   case MVT::i8:
10774   case MVT::i16:
10775   case MVT::i32: {
10776     // Unaligned access can use (for example) LRDB, LRDH, LDR
10777     if (AllowsUnaligned) {
10778       if (Fast)
10779         *Fast = Subtarget->hasV7Ops();
10780       return true;
10781     }
10782     return false;
10783   }
10784   case MVT::f64:
10785   case MVT::v2f64: {
10786     // For any little-endian targets with neon, we can support unaligned ld/st
10787     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10788     // A big-endian target may also explicitly support unaligned accesses
10789     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10790       if (Fast)
10791         *Fast = true;
10792       return true;
10793     }
10794     return false;
10795   }
10796   }
10797 }
10798 
10799 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10800                        unsigned AlignCheck) {
10801   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10802           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10803 }
10804 
10805 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10806                                            unsigned DstAlign, unsigned SrcAlign,
10807                                            bool IsMemset, bool ZeroMemset,
10808                                            bool MemcpyStrSrc,
10809                                            MachineFunction &MF) const {
10810   const Function *F = MF.getFunction();
10811 
10812   // See if we can use NEON instructions for this...
10813   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10814       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10815     bool Fast;
10816     if (Size >= 16 &&
10817         (memOpAlign(SrcAlign, DstAlign, 16) ||
10818          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10819       return MVT::v2f64;
10820     } else if (Size >= 8 &&
10821                (memOpAlign(SrcAlign, DstAlign, 8) ||
10822                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10823                  Fast))) {
10824       return MVT::f64;
10825     }
10826   }
10827 
10828   // Lowering to i32/i16 if the size permits.
10829   if (Size >= 4)
10830     return MVT::i32;
10831   else if (Size >= 2)
10832     return MVT::i16;
10833 
10834   // Let the target-independent logic figure it out.
10835   return MVT::Other;
10836 }
10837 
10838 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10839   if (Val.getOpcode() != ISD::LOAD)
10840     return false;
10841 
10842   EVT VT1 = Val.getValueType();
10843   if (!VT1.isSimple() || !VT1.isInteger() ||
10844       !VT2.isSimple() || !VT2.isInteger())
10845     return false;
10846 
10847   switch (VT1.getSimpleVT().SimpleTy) {
10848   default: break;
10849   case MVT::i1:
10850   case MVT::i8:
10851   case MVT::i16:
10852     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10853     return true;
10854   }
10855 
10856   return false;
10857 }
10858 
10859 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10860   EVT VT = ExtVal.getValueType();
10861 
10862   if (!isTypeLegal(VT))
10863     return false;
10864 
10865   // Don't create a loadext if we can fold the extension into a wide/long
10866   // instruction.
10867   // If there's more than one user instruction, the loadext is desirable no
10868   // matter what.  There can be two uses by the same instruction.
10869   if (ExtVal->use_empty() ||
10870       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10871     return true;
10872 
10873   SDNode *U = *ExtVal->use_begin();
10874   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10875        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10876     return false;
10877 
10878   return true;
10879 }
10880 
10881 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10882   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10883     return false;
10884 
10885   if (!isTypeLegal(EVT::getEVT(Ty1)))
10886     return false;
10887 
10888   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10889 
10890   // Assuming the caller doesn't have a zeroext or signext return parameter,
10891   // truncation all the way down to i1 is valid.
10892   return true;
10893 }
10894 
10895 
10896 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10897   if (V < 0)
10898     return false;
10899 
10900   unsigned Scale = 1;
10901   switch (VT.getSimpleVT().SimpleTy) {
10902   default: return false;
10903   case MVT::i1:
10904   case MVT::i8:
10905     // Scale == 1;
10906     break;
10907   case MVT::i16:
10908     // Scale == 2;
10909     Scale = 2;
10910     break;
10911   case MVT::i32:
10912     // Scale == 4;
10913     Scale = 4;
10914     break;
10915   }
10916 
10917   if ((V & (Scale - 1)) != 0)
10918     return false;
10919   V /= Scale;
10920   return V == (V & ((1LL << 5) - 1));
10921 }
10922 
10923 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10924                                       const ARMSubtarget *Subtarget) {
10925   bool isNeg = false;
10926   if (V < 0) {
10927     isNeg = true;
10928     V = - V;
10929   }
10930 
10931   switch (VT.getSimpleVT().SimpleTy) {
10932   default: return false;
10933   case MVT::i1:
10934   case MVT::i8:
10935   case MVT::i16:
10936   case MVT::i32:
10937     // + imm12 or - imm8
10938     if (isNeg)
10939       return V == (V & ((1LL << 8) - 1));
10940     return V == (V & ((1LL << 12) - 1));
10941   case MVT::f32:
10942   case MVT::f64:
10943     // Same as ARM mode. FIXME: NEON?
10944     if (!Subtarget->hasVFP2())
10945       return false;
10946     if ((V & 3) != 0)
10947       return false;
10948     V >>= 2;
10949     return V == (V & ((1LL << 8) - 1));
10950   }
10951 }
10952 
10953 /// isLegalAddressImmediate - Return true if the integer value can be used
10954 /// as the offset of the target addressing mode for load / store of the
10955 /// given type.
10956 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10957                                     const ARMSubtarget *Subtarget) {
10958   if (V == 0)
10959     return true;
10960 
10961   if (!VT.isSimple())
10962     return false;
10963 
10964   if (Subtarget->isThumb1Only())
10965     return isLegalT1AddressImmediate(V, VT);
10966   else if (Subtarget->isThumb2())
10967     return isLegalT2AddressImmediate(V, VT, Subtarget);
10968 
10969   // ARM mode.
10970   if (V < 0)
10971     V = - V;
10972   switch (VT.getSimpleVT().SimpleTy) {
10973   default: return false;
10974   case MVT::i1:
10975   case MVT::i8:
10976   case MVT::i32:
10977     // +- imm12
10978     return V == (V & ((1LL << 12) - 1));
10979   case MVT::i16:
10980     // +- imm8
10981     return V == (V & ((1LL << 8) - 1));
10982   case MVT::f32:
10983   case MVT::f64:
10984     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10985       return false;
10986     if ((V & 3) != 0)
10987       return false;
10988     V >>= 2;
10989     return V == (V & ((1LL << 8) - 1));
10990   }
10991 }
10992 
10993 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10994                                                       EVT VT) const {
10995   int Scale = AM.Scale;
10996   if (Scale < 0)
10997     return false;
10998 
10999   switch (VT.getSimpleVT().SimpleTy) {
11000   default: return false;
11001   case MVT::i1:
11002   case MVT::i8:
11003   case MVT::i16:
11004   case MVT::i32:
11005     if (Scale == 1)
11006       return true;
11007     // r + r << imm
11008     Scale = Scale & ~1;
11009     return Scale == 2 || Scale == 4 || Scale == 8;
11010   case MVT::i64:
11011     // r + r
11012     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11013       return true;
11014     return false;
11015   case MVT::isVoid:
11016     // Note, we allow "void" uses (basically, uses that aren't loads or
11017     // stores), because arm allows folding a scale into many arithmetic
11018     // operations.  This should be made more precise and revisited later.
11019 
11020     // Allow r << imm, but the imm has to be a multiple of two.
11021     if (Scale & 1) return false;
11022     return isPowerOf2_32(Scale);
11023   }
11024 }
11025 
11026 /// isLegalAddressingMode - Return true if the addressing mode represented
11027 /// by AM is legal for this target, for a load/store of the specified type.
11028 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11029                                               const AddrMode &AM, Type *Ty,
11030                                               unsigned AS) const {
11031   EVT VT = getValueType(DL, Ty, true);
11032   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11033     return false;
11034 
11035   // Can never fold addr of global into load/store.
11036   if (AM.BaseGV)
11037     return false;
11038 
11039   switch (AM.Scale) {
11040   case 0:  // no scale reg, must be "r+i" or "r", or "i".
11041     break;
11042   case 1:
11043     if (Subtarget->isThumb1Only())
11044       return false;
11045     // FALL THROUGH.
11046   default:
11047     // ARM doesn't support any R+R*scale+imm addr modes.
11048     if (AM.BaseOffs)
11049       return false;
11050 
11051     if (!VT.isSimple())
11052       return false;
11053 
11054     if (Subtarget->isThumb2())
11055       return isLegalT2ScaledAddressingMode(AM, VT);
11056 
11057     int Scale = AM.Scale;
11058     switch (VT.getSimpleVT().SimpleTy) {
11059     default: return false;
11060     case MVT::i1:
11061     case MVT::i8:
11062     case MVT::i32:
11063       if (Scale < 0) Scale = -Scale;
11064       if (Scale == 1)
11065         return true;
11066       // r + r << imm
11067       return isPowerOf2_32(Scale & ~1);
11068     case MVT::i16:
11069     case MVT::i64:
11070       // r + r
11071       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11072         return true;
11073       return false;
11074 
11075     case MVT::isVoid:
11076       // Note, we allow "void" uses (basically, uses that aren't loads or
11077       // stores), because arm allows folding a scale into many arithmetic
11078       // operations.  This should be made more precise and revisited later.
11079 
11080       // Allow r << imm, but the imm has to be a multiple of two.
11081       if (Scale & 1) return false;
11082       return isPowerOf2_32(Scale);
11083     }
11084   }
11085   return true;
11086 }
11087 
11088 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11089 /// icmp immediate, that is the target has icmp instructions which can compare
11090 /// a register against the immediate without having to materialize the
11091 /// immediate into a register.
11092 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11093   // Thumb2 and ARM modes can use cmn for negative immediates.
11094   if (!Subtarget->isThumb())
11095     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11096   if (Subtarget->isThumb2())
11097     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11098   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11099   return Imm >= 0 && Imm <= 255;
11100 }
11101 
11102 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11103 /// *or sub* immediate, that is the target has add or sub instructions which can
11104 /// add a register with the immediate without having to materialize the
11105 /// immediate into a register.
11106 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11107   // Same encoding for add/sub, just flip the sign.
11108   int64_t AbsImm = std::abs(Imm);
11109   if (!Subtarget->isThumb())
11110     return ARM_AM::getSOImmVal(AbsImm) != -1;
11111   if (Subtarget->isThumb2())
11112     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11113   // Thumb1 only has 8-bit unsigned immediate.
11114   return AbsImm >= 0 && AbsImm <= 255;
11115 }
11116 
11117 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11118                                       bool isSEXTLoad, SDValue &Base,
11119                                       SDValue &Offset, bool &isInc,
11120                                       SelectionDAG &DAG) {
11121   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11122     return false;
11123 
11124   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11125     // AddressingMode 3
11126     Base = Ptr->getOperand(0);
11127     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11128       int RHSC = (int)RHS->getZExtValue();
11129       if (RHSC < 0 && RHSC > -256) {
11130         assert(Ptr->getOpcode() == ISD::ADD);
11131         isInc = false;
11132         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11133         return true;
11134       }
11135     }
11136     isInc = (Ptr->getOpcode() == ISD::ADD);
11137     Offset = Ptr->getOperand(1);
11138     return true;
11139   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11140     // AddressingMode 2
11141     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11142       int RHSC = (int)RHS->getZExtValue();
11143       if (RHSC < 0 && RHSC > -0x1000) {
11144         assert(Ptr->getOpcode() == ISD::ADD);
11145         isInc = false;
11146         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11147         Base = Ptr->getOperand(0);
11148         return true;
11149       }
11150     }
11151 
11152     if (Ptr->getOpcode() == ISD::ADD) {
11153       isInc = true;
11154       ARM_AM::ShiftOpc ShOpcVal=
11155         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11156       if (ShOpcVal != ARM_AM::no_shift) {
11157         Base = Ptr->getOperand(1);
11158         Offset = Ptr->getOperand(0);
11159       } else {
11160         Base = Ptr->getOperand(0);
11161         Offset = Ptr->getOperand(1);
11162       }
11163       return true;
11164     }
11165 
11166     isInc = (Ptr->getOpcode() == ISD::ADD);
11167     Base = Ptr->getOperand(0);
11168     Offset = Ptr->getOperand(1);
11169     return true;
11170   }
11171 
11172   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11173   return false;
11174 }
11175 
11176 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11177                                      bool isSEXTLoad, SDValue &Base,
11178                                      SDValue &Offset, bool &isInc,
11179                                      SelectionDAG &DAG) {
11180   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11181     return false;
11182 
11183   Base = Ptr->getOperand(0);
11184   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11185     int RHSC = (int)RHS->getZExtValue();
11186     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11187       assert(Ptr->getOpcode() == ISD::ADD);
11188       isInc = false;
11189       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11190       return true;
11191     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11192       isInc = Ptr->getOpcode() == ISD::ADD;
11193       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11194       return true;
11195     }
11196   }
11197 
11198   return false;
11199 }
11200 
11201 /// getPreIndexedAddressParts - returns true by value, base pointer and
11202 /// offset pointer and addressing mode by reference if the node's address
11203 /// can be legally represented as pre-indexed load / store address.
11204 bool
11205 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11206                                              SDValue &Offset,
11207                                              ISD::MemIndexedMode &AM,
11208                                              SelectionDAG &DAG) const {
11209   if (Subtarget->isThumb1Only())
11210     return false;
11211 
11212   EVT VT;
11213   SDValue Ptr;
11214   bool isSEXTLoad = false;
11215   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11216     Ptr = LD->getBasePtr();
11217     VT  = LD->getMemoryVT();
11218     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11219   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11220     Ptr = ST->getBasePtr();
11221     VT  = ST->getMemoryVT();
11222   } else
11223     return false;
11224 
11225   bool isInc;
11226   bool isLegal = false;
11227   if (Subtarget->isThumb2())
11228     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11229                                        Offset, isInc, DAG);
11230   else
11231     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11232                                         Offset, isInc, DAG);
11233   if (!isLegal)
11234     return false;
11235 
11236   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11237   return true;
11238 }
11239 
11240 /// getPostIndexedAddressParts - returns true by value, base pointer and
11241 /// offset pointer and addressing mode by reference if this node can be
11242 /// combined with a load / store to form a post-indexed load / store.
11243 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11244                                                    SDValue &Base,
11245                                                    SDValue &Offset,
11246                                                    ISD::MemIndexedMode &AM,
11247                                                    SelectionDAG &DAG) const {
11248   if (Subtarget->isThumb1Only())
11249     return false;
11250 
11251   EVT VT;
11252   SDValue Ptr;
11253   bool isSEXTLoad = false;
11254   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11255     VT  = LD->getMemoryVT();
11256     Ptr = LD->getBasePtr();
11257     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11258   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11259     VT  = ST->getMemoryVT();
11260     Ptr = ST->getBasePtr();
11261   } else
11262     return false;
11263 
11264   bool isInc;
11265   bool isLegal = false;
11266   if (Subtarget->isThumb2())
11267     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11268                                        isInc, DAG);
11269   else
11270     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11271                                         isInc, DAG);
11272   if (!isLegal)
11273     return false;
11274 
11275   if (Ptr != Base) {
11276     // Swap base ptr and offset to catch more post-index load / store when
11277     // it's legal. In Thumb2 mode, offset must be an immediate.
11278     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11279         !Subtarget->isThumb2())
11280       std::swap(Base, Offset);
11281 
11282     // Post-indexed load / store update the base pointer.
11283     if (Ptr != Base)
11284       return false;
11285   }
11286 
11287   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11288   return true;
11289 }
11290 
11291 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11292                                                       APInt &KnownZero,
11293                                                       APInt &KnownOne,
11294                                                       const SelectionDAG &DAG,
11295                                                       unsigned Depth) const {
11296   unsigned BitWidth = KnownOne.getBitWidth();
11297   KnownZero = KnownOne = APInt(BitWidth, 0);
11298   switch (Op.getOpcode()) {
11299   default: break;
11300   case ARMISD::ADDC:
11301   case ARMISD::ADDE:
11302   case ARMISD::SUBC:
11303   case ARMISD::SUBE:
11304     // These nodes' second result is a boolean
11305     if (Op.getResNo() == 0)
11306       break;
11307     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11308     break;
11309   case ARMISD::CMOV: {
11310     // Bits are known zero/one if known on the LHS and RHS.
11311     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11312     if (KnownZero == 0 && KnownOne == 0) return;
11313 
11314     APInt KnownZeroRHS, KnownOneRHS;
11315     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11316     KnownZero &= KnownZeroRHS;
11317     KnownOne  &= KnownOneRHS;
11318     return;
11319   }
11320   case ISD::INTRINSIC_W_CHAIN: {
11321     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11322     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11323     switch (IntID) {
11324     default: return;
11325     case Intrinsic::arm_ldaex:
11326     case Intrinsic::arm_ldrex: {
11327       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11328       unsigned MemBits = VT.getScalarType().getSizeInBits();
11329       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11330       return;
11331     }
11332     }
11333   }
11334   }
11335 }
11336 
11337 //===----------------------------------------------------------------------===//
11338 //                           ARM Inline Assembly Support
11339 //===----------------------------------------------------------------------===//
11340 
11341 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11342   // Looking for "rev" which is V6+.
11343   if (!Subtarget->hasV6Ops())
11344     return false;
11345 
11346   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11347   std::string AsmStr = IA->getAsmString();
11348   SmallVector<StringRef, 4> AsmPieces;
11349   SplitString(AsmStr, AsmPieces, ";\n");
11350 
11351   switch (AsmPieces.size()) {
11352   default: return false;
11353   case 1:
11354     AsmStr = AsmPieces[0];
11355     AsmPieces.clear();
11356     SplitString(AsmStr, AsmPieces, " \t,");
11357 
11358     // rev $0, $1
11359     if (AsmPieces.size() == 3 &&
11360         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11361         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11362       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11363       if (Ty && Ty->getBitWidth() == 32)
11364         return IntrinsicLowering::LowerToByteSwap(CI);
11365     }
11366     break;
11367   }
11368 
11369   return false;
11370 }
11371 
11372 /// getConstraintType - Given a constraint letter, return the type of
11373 /// constraint it is for this target.
11374 ARMTargetLowering::ConstraintType
11375 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11376   if (Constraint.size() == 1) {
11377     switch (Constraint[0]) {
11378     default:  break;
11379     case 'l': return C_RegisterClass;
11380     case 'w': return C_RegisterClass;
11381     case 'h': return C_RegisterClass;
11382     case 'x': return C_RegisterClass;
11383     case 't': return C_RegisterClass;
11384     case 'j': return C_Other; // Constant for movw.
11385       // An address with a single base register. Due to the way we
11386       // currently handle addresses it is the same as an 'r' memory constraint.
11387     case 'Q': return C_Memory;
11388     }
11389   } else if (Constraint.size() == 2) {
11390     switch (Constraint[0]) {
11391     default: break;
11392     // All 'U+' constraints are addresses.
11393     case 'U': return C_Memory;
11394     }
11395   }
11396   return TargetLowering::getConstraintType(Constraint);
11397 }
11398 
11399 /// Examine constraint type and operand type and determine a weight value.
11400 /// This object must already have been set up with the operand type
11401 /// and the current alternative constraint selected.
11402 TargetLowering::ConstraintWeight
11403 ARMTargetLowering::getSingleConstraintMatchWeight(
11404     AsmOperandInfo &info, const char *constraint) const {
11405   ConstraintWeight weight = CW_Invalid;
11406   Value *CallOperandVal = info.CallOperandVal;
11407     // If we don't have a value, we can't do a match,
11408     // but allow it at the lowest weight.
11409   if (!CallOperandVal)
11410     return CW_Default;
11411   Type *type = CallOperandVal->getType();
11412   // Look at the constraint type.
11413   switch (*constraint) {
11414   default:
11415     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11416     break;
11417   case 'l':
11418     if (type->isIntegerTy()) {
11419       if (Subtarget->isThumb())
11420         weight = CW_SpecificReg;
11421       else
11422         weight = CW_Register;
11423     }
11424     break;
11425   case 'w':
11426     if (type->isFloatingPointTy())
11427       weight = CW_Register;
11428     break;
11429   }
11430   return weight;
11431 }
11432 
11433 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11434 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11435     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11436   if (Constraint.size() == 1) {
11437     // GCC ARM Constraint Letters
11438     switch (Constraint[0]) {
11439     case 'l': // Low regs or general regs.
11440       if (Subtarget->isThumb())
11441         return RCPair(0U, &ARM::tGPRRegClass);
11442       return RCPair(0U, &ARM::GPRRegClass);
11443     case 'h': // High regs or no regs.
11444       if (Subtarget->isThumb())
11445         return RCPair(0U, &ARM::hGPRRegClass);
11446       break;
11447     case 'r':
11448       if (Subtarget->isThumb1Only())
11449         return RCPair(0U, &ARM::tGPRRegClass);
11450       return RCPair(0U, &ARM::GPRRegClass);
11451     case 'w':
11452       if (VT == MVT::Other)
11453         break;
11454       if (VT == MVT::f32)
11455         return RCPair(0U, &ARM::SPRRegClass);
11456       if (VT.getSizeInBits() == 64)
11457         return RCPair(0U, &ARM::DPRRegClass);
11458       if (VT.getSizeInBits() == 128)
11459         return RCPair(0U, &ARM::QPRRegClass);
11460       break;
11461     case 'x':
11462       if (VT == MVT::Other)
11463         break;
11464       if (VT == MVT::f32)
11465         return RCPair(0U, &ARM::SPR_8RegClass);
11466       if (VT.getSizeInBits() == 64)
11467         return RCPair(0U, &ARM::DPR_8RegClass);
11468       if (VT.getSizeInBits() == 128)
11469         return RCPair(0U, &ARM::QPR_8RegClass);
11470       break;
11471     case 't':
11472       if (VT == MVT::f32)
11473         return RCPair(0U, &ARM::SPRRegClass);
11474       break;
11475     }
11476   }
11477   if (StringRef("{cc}").equals_lower(Constraint))
11478     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11479 
11480   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11481 }
11482 
11483 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11484 /// vector.  If it is invalid, don't add anything to Ops.
11485 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11486                                                      std::string &Constraint,
11487                                                      std::vector<SDValue>&Ops,
11488                                                      SelectionDAG &DAG) const {
11489   SDValue Result;
11490 
11491   // Currently only support length 1 constraints.
11492   if (Constraint.length() != 1) return;
11493 
11494   char ConstraintLetter = Constraint[0];
11495   switch (ConstraintLetter) {
11496   default: break;
11497   case 'j':
11498   case 'I': case 'J': case 'K': case 'L':
11499   case 'M': case 'N': case 'O':
11500     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11501     if (!C)
11502       return;
11503 
11504     int64_t CVal64 = C->getSExtValue();
11505     int CVal = (int) CVal64;
11506     // None of these constraints allow values larger than 32 bits.  Check
11507     // that the value fits in an int.
11508     if (CVal != CVal64)
11509       return;
11510 
11511     switch (ConstraintLetter) {
11512       case 'j':
11513         // Constant suitable for movw, must be between 0 and
11514         // 65535.
11515         if (Subtarget->hasV6T2Ops())
11516           if (CVal >= 0 && CVal <= 65535)
11517             break;
11518         return;
11519       case 'I':
11520         if (Subtarget->isThumb1Only()) {
11521           // This must be a constant between 0 and 255, for ADD
11522           // immediates.
11523           if (CVal >= 0 && CVal <= 255)
11524             break;
11525         } else if (Subtarget->isThumb2()) {
11526           // A constant that can be used as an immediate value in a
11527           // data-processing instruction.
11528           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11529             break;
11530         } else {
11531           // A constant that can be used as an immediate value in a
11532           // data-processing instruction.
11533           if (ARM_AM::getSOImmVal(CVal) != -1)
11534             break;
11535         }
11536         return;
11537 
11538       case 'J':
11539         if (Subtarget->isThumb1Only()) {
11540           // This must be a constant between -255 and -1, for negated ADD
11541           // immediates. This can be used in GCC with an "n" modifier that
11542           // prints the negated value, for use with SUB instructions. It is
11543           // not useful otherwise but is implemented for compatibility.
11544           if (CVal >= -255 && CVal <= -1)
11545             break;
11546         } else {
11547           // This must be a constant between -4095 and 4095. It is not clear
11548           // what this constraint is intended for. Implemented for
11549           // compatibility with GCC.
11550           if (CVal >= -4095 && CVal <= 4095)
11551             break;
11552         }
11553         return;
11554 
11555       case 'K':
11556         if (Subtarget->isThumb1Only()) {
11557           // A 32-bit value where only one byte has a nonzero value. Exclude
11558           // zero to match GCC. This constraint is used by GCC internally for
11559           // constants that can be loaded with a move/shift combination.
11560           // It is not useful otherwise but is implemented for compatibility.
11561           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11562             break;
11563         } else if (Subtarget->isThumb2()) {
11564           // A constant whose bitwise inverse can be used as an immediate
11565           // value in a data-processing instruction. This can be used in GCC
11566           // with a "B" modifier that prints the inverted value, for use with
11567           // BIC and MVN instructions. It is not useful otherwise but is
11568           // implemented for compatibility.
11569           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11570             break;
11571         } else {
11572           // A constant whose bitwise inverse can be used as an immediate
11573           // value in a data-processing instruction. This can be used in GCC
11574           // with a "B" modifier that prints the inverted value, for use with
11575           // BIC and MVN instructions. It is not useful otherwise but is
11576           // implemented for compatibility.
11577           if (ARM_AM::getSOImmVal(~CVal) != -1)
11578             break;
11579         }
11580         return;
11581 
11582       case 'L':
11583         if (Subtarget->isThumb1Only()) {
11584           // This must be a constant between -7 and 7,
11585           // for 3-operand ADD/SUB immediate instructions.
11586           if (CVal >= -7 && CVal < 7)
11587             break;
11588         } else if (Subtarget->isThumb2()) {
11589           // A constant whose negation can be used as an immediate value in a
11590           // data-processing instruction. This can be used in GCC with an "n"
11591           // modifier that prints the negated value, for use with SUB
11592           // instructions. It is not useful otherwise but is implemented for
11593           // compatibility.
11594           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11595             break;
11596         } else {
11597           // A constant whose negation can be used as an immediate value in a
11598           // data-processing instruction. This can be used in GCC with an "n"
11599           // modifier that prints the negated value, for use with SUB
11600           // instructions. It is not useful otherwise but is implemented for
11601           // compatibility.
11602           if (ARM_AM::getSOImmVal(-CVal) != -1)
11603             break;
11604         }
11605         return;
11606 
11607       case 'M':
11608         if (Subtarget->isThumb1Only()) {
11609           // This must be a multiple of 4 between 0 and 1020, for
11610           // ADD sp + immediate.
11611           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11612             break;
11613         } else {
11614           // A power of two or a constant between 0 and 32.  This is used in
11615           // GCC for the shift amount on shifted register operands, but it is
11616           // useful in general for any shift amounts.
11617           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11618             break;
11619         }
11620         return;
11621 
11622       case 'N':
11623         if (Subtarget->isThumb()) {  // FIXME thumb2
11624           // This must be a constant between 0 and 31, for shift amounts.
11625           if (CVal >= 0 && CVal <= 31)
11626             break;
11627         }
11628         return;
11629 
11630       case 'O':
11631         if (Subtarget->isThumb()) {  // FIXME thumb2
11632           // This must be a multiple of 4 between -508 and 508, for
11633           // ADD/SUB sp = sp + immediate.
11634           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11635             break;
11636         }
11637         return;
11638     }
11639     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11640     break;
11641   }
11642 
11643   if (Result.getNode()) {
11644     Ops.push_back(Result);
11645     return;
11646   }
11647   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11648 }
11649 
11650 static RTLIB::Libcall getDivRemLibcall(
11651     const SDNode *N, MVT::SimpleValueType SVT) {
11652   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11653           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11654          "Unhandled Opcode in getDivRemLibcall");
11655   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11656                   N->getOpcode() == ISD::SREM;
11657   RTLIB::Libcall LC;
11658   switch (SVT) {
11659   default: llvm_unreachable("Unexpected request for libcall!");
11660   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11661   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11662   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11663   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11664   }
11665   return LC;
11666 }
11667 
11668 static TargetLowering::ArgListTy getDivRemArgList(
11669     const SDNode *N, LLVMContext *Context) {
11670   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11671           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11672          "Unhandled Opcode in getDivRemArgList");
11673   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11674                   N->getOpcode() == ISD::SREM;
11675   TargetLowering::ArgListTy Args;
11676   TargetLowering::ArgListEntry Entry;
11677   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11678     EVT ArgVT = N->getOperand(i).getValueType();
11679     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11680     Entry.Node = N->getOperand(i);
11681     Entry.Ty = ArgTy;
11682     Entry.isSExt = isSigned;
11683     Entry.isZExt = !isSigned;
11684     Args.push_back(Entry);
11685   }
11686   return Args;
11687 }
11688 
11689 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11690   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
11691           Subtarget->isTargetGNUAEABI()) &&
11692          "Register-based DivRem lowering only");
11693   unsigned Opcode = Op->getOpcode();
11694   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11695          "Invalid opcode for Div/Rem lowering");
11696   bool isSigned = (Opcode == ISD::SDIVREM);
11697   EVT VT = Op->getValueType(0);
11698   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11699 
11700   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11701                                        VT.getSimpleVT().SimpleTy);
11702   SDValue InChain = DAG.getEntryNode();
11703 
11704   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11705                                                     DAG.getContext());
11706 
11707   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11708                                          getPointerTy(DAG.getDataLayout()));
11709 
11710   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11711 
11712   SDLoc dl(Op);
11713   TargetLowering::CallLoweringInfo CLI(DAG);
11714   CLI.setDebugLoc(dl).setChain(InChain)
11715     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11716     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11717 
11718   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11719   return CallInfo.first;
11720 }
11721 
11722 // Lowers REM using divmod helpers
11723 // see RTABI section 4.2/4.3
11724 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11725   // Build return types (div and rem)
11726   std::vector<Type*> RetTyParams;
11727   Type *RetTyElement;
11728 
11729   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11730   default: llvm_unreachable("Unexpected request for libcall!");
11731   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11732   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11733   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11734   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11735   }
11736 
11737   RetTyParams.push_back(RetTyElement);
11738   RetTyParams.push_back(RetTyElement);
11739   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11740   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11741 
11742   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11743                                                              SimpleTy);
11744   SDValue InChain = DAG.getEntryNode();
11745   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11746   bool isSigned = N->getOpcode() == ISD::SREM;
11747   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11748                                          getPointerTy(DAG.getDataLayout()));
11749 
11750   // Lower call
11751   CallLoweringInfo CLI(DAG);
11752   CLI.setChain(InChain)
11753      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11754      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11755   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11756 
11757   // Return second (rem) result operand (first contains div)
11758   SDNode *ResNode = CallResult.first.getNode();
11759   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11760   return ResNode->getOperand(1);
11761 }
11762 
11763 SDValue
11764 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11765   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11766   SDLoc DL(Op);
11767 
11768   // Get the inputs.
11769   SDValue Chain = Op.getOperand(0);
11770   SDValue Size  = Op.getOperand(1);
11771 
11772   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11773                               DAG.getConstant(2, DL, MVT::i32));
11774 
11775   SDValue Flag;
11776   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11777   Flag = Chain.getValue(1);
11778 
11779   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11780   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11781 
11782   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11783   Chain = NewSP.getValue(1);
11784 
11785   SDValue Ops[2] = { NewSP, Chain };
11786   return DAG.getMergeValues(Ops, DL);
11787 }
11788 
11789 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11790   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11791          "Unexpected type for custom-lowering FP_EXTEND");
11792 
11793   RTLIB::Libcall LC;
11794   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11795 
11796   SDValue SrcVal = Op.getOperand(0);
11797   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11798                      SDLoc(Op)).first;
11799 }
11800 
11801 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11802   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11803          Subtarget->isFPOnlySP() &&
11804          "Unexpected type for custom-lowering FP_ROUND");
11805 
11806   RTLIB::Libcall LC;
11807   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11808 
11809   SDValue SrcVal = Op.getOperand(0);
11810   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11811                      SDLoc(Op)).first;
11812 }
11813 
11814 bool
11815 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11816   // The ARM target isn't yet aware of offsets.
11817   return false;
11818 }
11819 
11820 bool ARM::isBitFieldInvertedMask(unsigned v) {
11821   if (v == 0xffffffff)
11822     return false;
11823 
11824   // there can be 1's on either or both "outsides", all the "inside"
11825   // bits must be 0's
11826   return isShiftedMask_32(~v);
11827 }
11828 
11829 /// isFPImmLegal - Returns true if the target can instruction select the
11830 /// specified FP immediate natively. If false, the legalizer will
11831 /// materialize the FP immediate as a load from a constant pool.
11832 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11833   if (!Subtarget->hasVFP3())
11834     return false;
11835   if (VT == MVT::f32)
11836     return ARM_AM::getFP32Imm(Imm) != -1;
11837   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11838     return ARM_AM::getFP64Imm(Imm) != -1;
11839   return false;
11840 }
11841 
11842 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11843 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11844 /// specified in the intrinsic calls.
11845 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11846                                            const CallInst &I,
11847                                            unsigned Intrinsic) const {
11848   switch (Intrinsic) {
11849   case Intrinsic::arm_neon_vld1:
11850   case Intrinsic::arm_neon_vld2:
11851   case Intrinsic::arm_neon_vld3:
11852   case Intrinsic::arm_neon_vld4:
11853   case Intrinsic::arm_neon_vld2lane:
11854   case Intrinsic::arm_neon_vld3lane:
11855   case Intrinsic::arm_neon_vld4lane: {
11856     Info.opc = ISD::INTRINSIC_W_CHAIN;
11857     // Conservatively set memVT to the entire set of vectors loaded.
11858     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11859     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11860     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11861     Info.ptrVal = I.getArgOperand(0);
11862     Info.offset = 0;
11863     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11864     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11865     Info.vol = false; // volatile loads with NEON intrinsics not supported
11866     Info.readMem = true;
11867     Info.writeMem = false;
11868     return true;
11869   }
11870   case Intrinsic::arm_neon_vst1:
11871   case Intrinsic::arm_neon_vst2:
11872   case Intrinsic::arm_neon_vst3:
11873   case Intrinsic::arm_neon_vst4:
11874   case Intrinsic::arm_neon_vst2lane:
11875   case Intrinsic::arm_neon_vst3lane:
11876   case Intrinsic::arm_neon_vst4lane: {
11877     Info.opc = ISD::INTRINSIC_VOID;
11878     // Conservatively set memVT to the entire set of vectors stored.
11879     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11880     unsigned NumElts = 0;
11881     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11882       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11883       if (!ArgTy->isVectorTy())
11884         break;
11885       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11886     }
11887     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11888     Info.ptrVal = I.getArgOperand(0);
11889     Info.offset = 0;
11890     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11891     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11892     Info.vol = false; // volatile stores with NEON intrinsics not supported
11893     Info.readMem = false;
11894     Info.writeMem = true;
11895     return true;
11896   }
11897   case Intrinsic::arm_ldaex:
11898   case Intrinsic::arm_ldrex: {
11899     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11900     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11901     Info.opc = ISD::INTRINSIC_W_CHAIN;
11902     Info.memVT = MVT::getVT(PtrTy->getElementType());
11903     Info.ptrVal = I.getArgOperand(0);
11904     Info.offset = 0;
11905     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11906     Info.vol = true;
11907     Info.readMem = true;
11908     Info.writeMem = false;
11909     return true;
11910   }
11911   case Intrinsic::arm_stlex:
11912   case Intrinsic::arm_strex: {
11913     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11914     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11915     Info.opc = ISD::INTRINSIC_W_CHAIN;
11916     Info.memVT = MVT::getVT(PtrTy->getElementType());
11917     Info.ptrVal = I.getArgOperand(1);
11918     Info.offset = 0;
11919     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11920     Info.vol = true;
11921     Info.readMem = false;
11922     Info.writeMem = true;
11923     return true;
11924   }
11925   case Intrinsic::arm_stlexd:
11926   case Intrinsic::arm_strexd: {
11927     Info.opc = ISD::INTRINSIC_W_CHAIN;
11928     Info.memVT = MVT::i64;
11929     Info.ptrVal = I.getArgOperand(2);
11930     Info.offset = 0;
11931     Info.align = 8;
11932     Info.vol = true;
11933     Info.readMem = false;
11934     Info.writeMem = true;
11935     return true;
11936   }
11937   case Intrinsic::arm_ldaexd:
11938   case Intrinsic::arm_ldrexd: {
11939     Info.opc = ISD::INTRINSIC_W_CHAIN;
11940     Info.memVT = MVT::i64;
11941     Info.ptrVal = I.getArgOperand(0);
11942     Info.offset = 0;
11943     Info.align = 8;
11944     Info.vol = true;
11945     Info.readMem = true;
11946     Info.writeMem = false;
11947     return true;
11948   }
11949   default:
11950     break;
11951   }
11952 
11953   return false;
11954 }
11955 
11956 /// \brief Returns true if it is beneficial to convert a load of a constant
11957 /// to just the constant itself.
11958 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11959                                                           Type *Ty) const {
11960   assert(Ty->isIntegerTy());
11961 
11962   unsigned Bits = Ty->getPrimitiveSizeInBits();
11963   if (Bits == 0 || Bits > 32)
11964     return false;
11965   return true;
11966 }
11967 
11968 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11969                                         ARM_MB::MemBOpt Domain) const {
11970   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11971 
11972   // First, if the target has no DMB, see what fallback we can use.
11973   if (!Subtarget->hasDataBarrier()) {
11974     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11975     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11976     // here.
11977     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11978       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11979       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11980                         Builder.getInt32(0), Builder.getInt32(7),
11981                         Builder.getInt32(10), Builder.getInt32(5)};
11982       return Builder.CreateCall(MCR, args);
11983     } else {
11984       // Instead of using barriers, atomic accesses on these subtargets use
11985       // libcalls.
11986       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11987     }
11988   } else {
11989     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11990     // Only a full system barrier exists in the M-class architectures.
11991     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11992     Constant *CDomain = Builder.getInt32(Domain);
11993     return Builder.CreateCall(DMB, CDomain);
11994   }
11995 }
11996 
11997 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11998 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11999                                          AtomicOrdering Ord, bool IsStore,
12000                                          bool IsLoad) const {
12001   if (!getInsertFencesForAtomic())
12002     return nullptr;
12003 
12004   switch (Ord) {
12005   case NotAtomic:
12006   case Unordered:
12007     llvm_unreachable("Invalid fence: unordered/non-atomic");
12008   case Monotonic:
12009   case Acquire:
12010     return nullptr; // Nothing to do
12011   case SequentiallyConsistent:
12012     if (!IsStore)
12013       return nullptr; // Nothing to do
12014     /*FALLTHROUGH*/
12015   case Release:
12016   case AcquireRelease:
12017     if (Subtarget->isSwift())
12018       return makeDMB(Builder, ARM_MB::ISHST);
12019     // FIXME: add a comment with a link to documentation justifying this.
12020     else
12021       return makeDMB(Builder, ARM_MB::ISH);
12022   }
12023   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12024 }
12025 
12026 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12027                                           AtomicOrdering Ord, bool IsStore,
12028                                           bool IsLoad) const {
12029   if (!getInsertFencesForAtomic())
12030     return nullptr;
12031 
12032   switch (Ord) {
12033   case NotAtomic:
12034   case Unordered:
12035     llvm_unreachable("Invalid fence: unordered/not-atomic");
12036   case Monotonic:
12037   case Release:
12038     return nullptr; // Nothing to do
12039   case Acquire:
12040   case AcquireRelease:
12041   case SequentiallyConsistent:
12042     return makeDMB(Builder, ARM_MB::ISH);
12043   }
12044   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12045 }
12046 
12047 // Loads and stores less than 64-bits are already atomic; ones above that
12048 // are doomed anyway, so defer to the default libcall and blame the OS when
12049 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12050 // anything for those.
12051 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12052   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12053   return (Size == 64) && !Subtarget->isMClass();
12054 }
12055 
12056 // Loads and stores less than 64-bits are already atomic; ones above that
12057 // are doomed anyway, so defer to the default libcall and blame the OS when
12058 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12059 // anything for those.
12060 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12061 // guarantee, see DDI0406C ARM architecture reference manual,
12062 // sections A8.8.72-74 LDRD)
12063 TargetLowering::AtomicExpansionKind
12064 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12065   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12066   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12067                                                   : AtomicExpansionKind::None;
12068 }
12069 
12070 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12071 // and up to 64 bits on the non-M profiles
12072 TargetLowering::AtomicExpansionKind
12073 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12074   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12075   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12076              ? AtomicExpansionKind::LLSC
12077              : AtomicExpansionKind::None;
12078 }
12079 
12080 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12081     AtomicCmpXchgInst *AI) const {
12082   return true;
12083 }
12084 
12085 // This has so far only been implemented for MachO.
12086 bool ARMTargetLowering::useLoadStackGuardNode() const {
12087   return Subtarget->isTargetMachO();
12088 }
12089 
12090 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12091                                                   unsigned &Cost) const {
12092   // If we do not have NEON, vector types are not natively supported.
12093   if (!Subtarget->hasNEON())
12094     return false;
12095 
12096   // Floating point values and vector values map to the same register file.
12097   // Therefore, although we could do a store extract of a vector type, this is
12098   // better to leave at float as we have more freedom in the addressing mode for
12099   // those.
12100   if (VectorTy->isFPOrFPVectorTy())
12101     return false;
12102 
12103   // If the index is unknown at compile time, this is very expensive to lower
12104   // and it is not possible to combine the store with the extract.
12105   if (!isa<ConstantInt>(Idx))
12106     return false;
12107 
12108   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12109   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12110   // We can do a store + vector extract on any vector that fits perfectly in a D
12111   // or Q register.
12112   if (BitWidth == 64 || BitWidth == 128) {
12113     Cost = 0;
12114     return true;
12115   }
12116   return false;
12117 }
12118 
12119 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12120   return Subtarget->hasV6T2Ops();
12121 }
12122 
12123 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12124   return Subtarget->hasV6T2Ops();
12125 }
12126 
12127 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12128                                          AtomicOrdering Ord) const {
12129   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12130   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12131   bool IsAcquire = isAtLeastAcquire(Ord);
12132 
12133   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12134   // intrinsic must return {i32, i32} and we have to recombine them into a
12135   // single i64 here.
12136   if (ValTy->getPrimitiveSizeInBits() == 64) {
12137     Intrinsic::ID Int =
12138         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12139     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12140 
12141     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12142     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12143 
12144     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12145     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12146     if (!Subtarget->isLittle())
12147       std::swap (Lo, Hi);
12148     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12149     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12150     return Builder.CreateOr(
12151         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12152   }
12153 
12154   Type *Tys[] = { Addr->getType() };
12155   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12156   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12157 
12158   return Builder.CreateTruncOrBitCast(
12159       Builder.CreateCall(Ldrex, Addr),
12160       cast<PointerType>(Addr->getType())->getElementType());
12161 }
12162 
12163 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12164     IRBuilder<> &Builder) const {
12165   if (!Subtarget->hasV7Ops())
12166     return;
12167   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12168   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12169 }
12170 
12171 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12172                                                Value *Addr,
12173                                                AtomicOrdering Ord) const {
12174   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12175   bool IsRelease = isAtLeastRelease(Ord);
12176 
12177   // Since the intrinsics must have legal type, the i64 intrinsics take two
12178   // parameters: "i32, i32". We must marshal Val into the appropriate form
12179   // before the call.
12180   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12181     Intrinsic::ID Int =
12182         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12183     Function *Strex = Intrinsic::getDeclaration(M, Int);
12184     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12185 
12186     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12187     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12188     if (!Subtarget->isLittle())
12189       std::swap (Lo, Hi);
12190     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12191     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12192   }
12193 
12194   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12195   Type *Tys[] = { Addr->getType() };
12196   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12197 
12198   return Builder.CreateCall(
12199       Strex, {Builder.CreateZExtOrBitCast(
12200                   Val, Strex->getFunctionType()->getParamType(0)),
12201               Addr});
12202 }
12203 
12204 /// \brief Lower an interleaved load into a vldN intrinsic.
12205 ///
12206 /// E.g. Lower an interleaved load (Factor = 2):
12207 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12208 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12209 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12210 ///
12211 ///      Into:
12212 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12213 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12214 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12215 bool ARMTargetLowering::lowerInterleavedLoad(
12216     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12217     ArrayRef<unsigned> Indices, unsigned Factor) const {
12218   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12219          "Invalid interleave factor");
12220   assert(!Shuffles.empty() && "Empty shufflevector input");
12221   assert(Shuffles.size() == Indices.size() &&
12222          "Unmatched number of shufflevectors and indices");
12223 
12224   VectorType *VecTy = Shuffles[0]->getType();
12225   Type *EltTy = VecTy->getVectorElementType();
12226 
12227   const DataLayout &DL = LI->getModule()->getDataLayout();
12228   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12229   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12230 
12231   // Skip if we do not have NEON and skip illegal vector types and vector types
12232   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12233   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12234     return false;
12235 
12236   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12237   // load integer vectors first and then convert to pointer vectors.
12238   if (EltTy->isPointerTy())
12239     VecTy =
12240         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12241 
12242   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12243                                             Intrinsic::arm_neon_vld3,
12244                                             Intrinsic::arm_neon_vld4};
12245 
12246   IRBuilder<> Builder(LI);
12247   SmallVector<Value *, 2> Ops;
12248 
12249   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12250   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12251   Ops.push_back(Builder.getInt32(LI->getAlignment()));
12252 
12253   Type *Tys[] = { VecTy, Int8Ptr };
12254   Function *VldnFunc =
12255       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12256   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12257 
12258   // Replace uses of each shufflevector with the corresponding vector loaded
12259   // by ldN.
12260   for (unsigned i = 0; i < Shuffles.size(); i++) {
12261     ShuffleVectorInst *SV = Shuffles[i];
12262     unsigned Index = Indices[i];
12263 
12264     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12265 
12266     // Convert the integer vector to pointer vector if the element is pointer.
12267     if (EltTy->isPointerTy())
12268       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12269 
12270     SV->replaceAllUsesWith(SubVec);
12271   }
12272 
12273   return true;
12274 }
12275 
12276 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12277 ///
12278 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12279 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12280                                    unsigned NumElts) {
12281   SmallVector<Constant *, 16> Mask;
12282   for (unsigned i = 0; i < NumElts; i++)
12283     Mask.push_back(Builder.getInt32(Start + i));
12284 
12285   return ConstantVector::get(Mask);
12286 }
12287 
12288 /// \brief Lower an interleaved store into a vstN intrinsic.
12289 ///
12290 /// E.g. Lower an interleaved store (Factor = 3):
12291 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12292 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12293 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12294 ///
12295 ///      Into:
12296 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12297 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12298 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12299 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12300 ///
12301 /// Note that the new shufflevectors will be removed and we'll only generate one
12302 /// vst3 instruction in CodeGen.
12303 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12304                                               ShuffleVectorInst *SVI,
12305                                               unsigned Factor) const {
12306   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12307          "Invalid interleave factor");
12308 
12309   VectorType *VecTy = SVI->getType();
12310   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12311          "Invalid interleaved store");
12312 
12313   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12314   Type *EltTy = VecTy->getVectorElementType();
12315   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12316 
12317   const DataLayout &DL = SI->getModule()->getDataLayout();
12318   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12319   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12320 
12321   // Skip if we do not have NEON and skip illegal vector types and vector types
12322   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12323   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12324       EltIs64Bits)
12325     return false;
12326 
12327   Value *Op0 = SVI->getOperand(0);
12328   Value *Op1 = SVI->getOperand(1);
12329   IRBuilder<> Builder(SI);
12330 
12331   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12332   // vectors to integer vectors.
12333   if (EltTy->isPointerTy()) {
12334     Type *IntTy = DL.getIntPtrType(EltTy);
12335 
12336     // Convert to the corresponding integer vector.
12337     Type *IntVecTy =
12338         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12339     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12340     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12341 
12342     SubVecTy = VectorType::get(IntTy, NumSubElts);
12343   }
12344 
12345   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12346                                              Intrinsic::arm_neon_vst3,
12347                                              Intrinsic::arm_neon_vst4};
12348   SmallVector<Value *, 6> Ops;
12349 
12350   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12351   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12352 
12353   Type *Tys[] = { Int8Ptr, SubVecTy };
12354   Function *VstNFunc = Intrinsic::getDeclaration(
12355       SI->getModule(), StoreInts[Factor - 2], Tys);
12356 
12357   // Split the shufflevector operands into sub vectors for the new vstN call.
12358   for (unsigned i = 0; i < Factor; i++)
12359     Ops.push_back(Builder.CreateShuffleVector(
12360         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12361 
12362   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12363   Builder.CreateCall(VstNFunc, Ops);
12364   return true;
12365 }
12366 
12367 enum HABaseType {
12368   HA_UNKNOWN = 0,
12369   HA_FLOAT,
12370   HA_DOUBLE,
12371   HA_VECT64,
12372   HA_VECT128
12373 };
12374 
12375 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12376                                    uint64_t &Members) {
12377   if (auto *ST = dyn_cast<StructType>(Ty)) {
12378     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12379       uint64_t SubMembers = 0;
12380       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12381         return false;
12382       Members += SubMembers;
12383     }
12384   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12385     uint64_t SubMembers = 0;
12386     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12387       return false;
12388     Members += SubMembers * AT->getNumElements();
12389   } else if (Ty->isFloatTy()) {
12390     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12391       return false;
12392     Members = 1;
12393     Base = HA_FLOAT;
12394   } else if (Ty->isDoubleTy()) {
12395     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12396       return false;
12397     Members = 1;
12398     Base = HA_DOUBLE;
12399   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12400     Members = 1;
12401     switch (Base) {
12402     case HA_FLOAT:
12403     case HA_DOUBLE:
12404       return false;
12405     case HA_VECT64:
12406       return VT->getBitWidth() == 64;
12407     case HA_VECT128:
12408       return VT->getBitWidth() == 128;
12409     case HA_UNKNOWN:
12410       switch (VT->getBitWidth()) {
12411       case 64:
12412         Base = HA_VECT64;
12413         return true;
12414       case 128:
12415         Base = HA_VECT128;
12416         return true;
12417       default:
12418         return false;
12419       }
12420     }
12421   }
12422 
12423   return (Members > 0 && Members <= 4);
12424 }
12425 
12426 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12427 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12428 /// passing according to AAPCS rules.
12429 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12430     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12431   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12432       CallingConv::ARM_AAPCS_VFP)
12433     return false;
12434 
12435   HABaseType Base = HA_UNKNOWN;
12436   uint64_t Members = 0;
12437   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12438   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12439 
12440   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12441   return IsHA || IsIntArray;
12442 }
12443 
12444 unsigned ARMTargetLowering::getExceptionPointerRegister(
12445     const Constant *PersonalityFn) const {
12446   // Platforms which do not use SjLj EH may return values in these registers
12447   // via the personality function.
12448   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12449 }
12450 
12451 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12452     const Constant *PersonalityFn) const {
12453   // Platforms which do not use SjLj EH may return values in these registers
12454   // via the personality function.
12455   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12456 }
12457 
12458 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12459   // Update IsSplitCSR in ARMFunctionInfo.
12460   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12461   AFI->setIsSplitCSR(true);
12462 }
12463 
12464 void ARMTargetLowering::insertCopiesSplitCSR(
12465     MachineBasicBlock *Entry,
12466     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12467   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12468   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12469   if (!IStart)
12470     return;
12471 
12472   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12473   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12474   MachineBasicBlock::iterator MBBI = Entry->begin();
12475   for (const MCPhysReg *I = IStart; *I; ++I) {
12476     const TargetRegisterClass *RC = nullptr;
12477     if (ARM::GPRRegClass.contains(*I))
12478       RC = &ARM::GPRRegClass;
12479     else if (ARM::DPRRegClass.contains(*I))
12480       RC = &ARM::DPRRegClass;
12481     else
12482       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12483 
12484     unsigned NewVR = MRI->createVirtualRegister(RC);
12485     // Create copy from CSR to a virtual register.
12486     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12487     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12488     // nounwind. If we want to generalize this later, we may need to emit
12489     // CFI pseudo-instructions.
12490     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12491                Attribute::NoUnwind) &&
12492            "Function should be nounwind in insertCopiesSplitCSR!");
12493     Entry->addLiveIn(*I);
12494     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12495         .addReg(*I);
12496 
12497     // Insert the copy-back instructions right before the terminator.
12498     for (auto *Exit : Exits)
12499       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12500               TII->get(TargetOpcode::COPY), *I)
12501           .addReg(NewVR);
12502   }
12503 }
12504