[ARM] Don't try and custom lower a vNi64 SETCC.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
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.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150   if (!VT.isFloatingPoint() &&
151       VT != MVT::v2i64 && VT != MVT::v1i64)
152     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153       setOperationAction(Opcode, VT, Legal);
154
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPRRegClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163   addRegisterClass(VT, &ARM::DPairRegClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168                                      const ARMSubtarget &STI)
169     : TargetLowering(TM), Subtarget(&STI) {
170   RegInfo = Subtarget->getRegisterInfo();
171   Itins = Subtarget->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179       static const struct {
180         const RTLIB::Libcall Op;
181         const char * const Name;
182         const ISD::CondCode Cond;
183       } LibraryCalls[] = {
184         // Single-precision floating-point arithmetic.
185         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
189
190         // Double-precision floating-point arithmetic.
191         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
195
196         // Single-precision comparisons.
197         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
198         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
199         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
200         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
201         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
202         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
203         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
204         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
205
206         // Double-precision comparisons.
207         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
208         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
209         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
210         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
211         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
212         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
213         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
214         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
215
216         // Floating-point to integer conversions.
217         // i64 conversions are done via library routines even when generating VFP
218         // instructions, so use the same ones.
219         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
220         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
222         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
223
224         // Conversions between floating types.
225         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
226         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
227
228         // Integer to floating-point conversions.
229         // i64 conversions are done via library routines even when generating VFP
230         // instructions, so use the same ones.
231         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232         // e.g., __floatunsidf vs. __floatunssidfvfp.
233         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
234         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
236         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
237       };
238
239       for (const auto &LC : LibraryCalls) {
240         setLibcallName(LC.Op, LC.Name);
241         if (LC.Cond != ISD::SETCC_INVALID)
242           setCmpLibcallCC(LC.Op, LC.Cond);
243       }
244     }
245   }
246
247   // These libcalls are not available in 32-bit.
248   setLibcallName(RTLIB::SHL_I128, nullptr);
249   setLibcallName(RTLIB::SRL_I128, nullptr);
250   setLibcallName(RTLIB::SRA_I128, nullptr);
251
252   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253       !Subtarget->isTargetWindows()) {
254     static const struct {
255       const RTLIB::Libcall Op;
256       const char * const Name;
257       const CallingConv::ID CC;
258       const ISD::CondCode Cond;
259     } LibraryCalls[] = {
260       // Double-precision floating-point arithmetic helper functions
261       // RTABI chapter 4.1.2, Table 2
262       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266
267       // Double-precision floating-point comparison helper functions
268       // RTABI chapter 4.1.2, Table 3
269       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277
278       // Single-precision floating-point arithmetic helper functions
279       // RTABI chapter 4.1.2, Table 4
280       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284
285       // Single-precision floating-point comparison helper functions
286       // RTABI chapter 4.1.2, Table 5
287       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295
296       // Floating-point to integer conversions.
297       // RTABI chapter 4.1.2, Table 6
298       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306
307       // Conversions between floating types.
308       // RTABI chapter 4.1.2, Table 7
309       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Integer to floating-point conversions.
314       // RTABI chapter 4.1.2, Table 8
315       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Long long helper functions
325       // RTABI chapter 4.2, Table 9
326       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Integer division functions
332       // RTABI chapter 4.3.1
333       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Memory operations
343       // RTABI chapter 4.3.4
344       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347     };
348
349     for (const auto &LC : LibraryCalls) {
350       setLibcallName(LC.Op, LC.Name);
351       setLibcallCallingConv(LC.Op, LC.CC);
352       if (LC.Cond != ISD::SETCC_INVALID)
353         setCmpLibcallCC(LC.Op, LC.Cond);
354     }
355   }
356
357   if (Subtarget->isTargetWindows()) {
358     static const struct {
359       const RTLIB::Libcall Op;
360       const char * const Name;
361       const CallingConv::ID CC;
362     } LibraryCalls[] = {
363       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371
372       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   // The half <-> float conversion functions are always soft-float, but are
392   // needed for some targets which use a hard-float calling convention by
393   // default.
394   if (Subtarget->isAAPCS_ABI()) {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
398   } else {
399     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
402   }
403
404   if (Subtarget->isThumb1Only())
405     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
406   else
407     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
409       !Subtarget->isThumb1Only()) {
410     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
412   }
413
414   for (MVT VT : MVT::vector_valuetypes()) {
415     for (MVT InnerVT : MVT::vector_valuetypes()) {
416       setTruncStoreAction(VT, InnerVT, Expand);
417       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
418       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
419       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
420     }
421
422     setOperationAction(ISD::MULHS, VT, Expand);
423     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
426
427     setOperationAction(ISD::BSWAP, VT, Expand);
428   }
429
430   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
431   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
432
433   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
434   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON does not have single instruction CTTZ for vectors.
556     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
560
561     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
562     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
563     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
564     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
570
571     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
572     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
573     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
574     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
575
576     // NEON only has FMA instructions as of VFP4.
577     if (!Subtarget->hasVFP4()) {
578       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
579       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
580     }
581
582     setTargetDAGCombine(ISD::INTRINSIC_VOID);
583     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
584     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
585     setTargetDAGCombine(ISD::SHL);
586     setTargetDAGCombine(ISD::SRL);
587     setTargetDAGCombine(ISD::SRA);
588     setTargetDAGCombine(ISD::SIGN_EXTEND);
589     setTargetDAGCombine(ISD::ZERO_EXTEND);
590     setTargetDAGCombine(ISD::ANY_EXTEND);
591     setTargetDAGCombine(ISD::BUILD_VECTOR);
592     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
593     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
594     setTargetDAGCombine(ISD::STORE);
595     setTargetDAGCombine(ISD::FP_TO_SINT);
596     setTargetDAGCombine(ISD::FP_TO_UINT);
597     setTargetDAGCombine(ISD::FDIV);
598     setTargetDAGCombine(ISD::LOAD);
599
600     // It is legal to extload from v4i8 to v4i16 or v4i32.
601     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
602                    MVT::v2i32}) {
603       for (MVT VT : MVT::integer_vector_valuetypes()) {
604         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
605         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
606         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
607       }
608     }
609   }
610
611   // ARM and Thumb2 support UMLAL/SMLAL.
612   if (!Subtarget->isThumb1Only())
613     setTargetDAGCombine(ISD::ADDC);
614
615   if (Subtarget->isFPOnlySP()) {
616     // When targeting a floating-point unit with only single-precision
617     // operations, f64 is legal for the few double-precision instructions which
618     // are present However, no double-precision operations other than moves,
619     // loads and stores are provided by the hardware.
620     setOperationAction(ISD::FADD,       MVT::f64, Expand);
621     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
622     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
623     setOperationAction(ISD::FMA,        MVT::f64, Expand);
624     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
625     setOperationAction(ISD::FREM,       MVT::f64, Expand);
626     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
627     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
628     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
629     setOperationAction(ISD::FABS,       MVT::f64, Expand);
630     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
631     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
632     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
633     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
634     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
635     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
636     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
637     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
638     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
639     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
640     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
641     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
642     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
643     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
644     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
645     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
646     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
647     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
648     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
649     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
650     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
651     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
652     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
653   }
654
655   computeRegisterProperties(Subtarget->getRegisterInfo());
656
657   // ARM does not have floating-point extending loads.
658   for (MVT VT : MVT::fp_valuetypes()) {
659     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
660     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
661   }
662
663   // ... or truncating stores
664   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
665   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
666   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
667
668   // ARM does not have i1 sign extending load.
669   for (MVT VT : MVT::integer_valuetypes())
670     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
671
672   // ARM supports all 4 flavors of integer indexed load / store.
673   if (!Subtarget->isThumb1Only()) {
674     for (unsigned im = (unsigned)ISD::PRE_INC;
675          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
676       setIndexedLoadAction(im,  MVT::i1,  Legal);
677       setIndexedLoadAction(im,  MVT::i8,  Legal);
678       setIndexedLoadAction(im,  MVT::i16, Legal);
679       setIndexedLoadAction(im,  MVT::i32, Legal);
680       setIndexedStoreAction(im, MVT::i1,  Legal);
681       setIndexedStoreAction(im, MVT::i8,  Legal);
682       setIndexedStoreAction(im, MVT::i16, Legal);
683       setIndexedStoreAction(im, MVT::i32, Legal);
684     }
685   }
686
687   setOperationAction(ISD::SADDO, MVT::i32, Custom);
688   setOperationAction(ISD::UADDO, MVT::i32, Custom);
689   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
690   setOperationAction(ISD::USUBO, MVT::i32, Custom);
691
692   // i64 operation support.
693   setOperationAction(ISD::MUL,     MVT::i64, Expand);
694   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
695   if (Subtarget->isThumb1Only()) {
696     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
697     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
698   }
699   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
700       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
701     setOperationAction(ISD::MULHS, MVT::i32, Expand);
702
703   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
704   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
705   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
706   setOperationAction(ISD::SRL,       MVT::i64, Custom);
707   setOperationAction(ISD::SRA,       MVT::i64, Custom);
708
709   if (!Subtarget->isThumb1Only()) {
710     // FIXME: We should do this for Thumb1 as well.
711     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
712     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
713     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
714     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
715   }
716
717   // ARM does not have ROTL.
718   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
719   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
720   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
721   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
722     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
723
724   // These just redirect to CTTZ and CTLZ on ARM.
725   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
726   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
727
728   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
729
730   // Only ARMv6 has BSWAP.
731   if (!Subtarget->hasV6Ops())
732     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
733
734   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
735       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
736     // These are expanded into libcalls if the cpu doesn't have HW divider.
737     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
738     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
739   }
740
741   // FIXME: Also set divmod for SREM on EABI/androideabi
742   setOperationAction(ISD::SREM,  MVT::i32, Expand);
743   setOperationAction(ISD::UREM,  MVT::i32, Expand);
744   // Register based DivRem for AEABI (RTABI 4.2)
745   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
746     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
747     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
748     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
749     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
750     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
751     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
752     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
753     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
754
755     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
758     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
759     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
760     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
761     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
762     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
763
764     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
765     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
766   } else {
767     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
768     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
769   }
770
771   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
772   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
773   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
774   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
775   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
776
777   setOperationAction(ISD::TRAP, MVT::Other, Legal);
778
779   // Use the default implementation.
780   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
781   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
782   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
783   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
784   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
785   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
786
787   if (!Subtarget->isTargetMachO()) {
788     // Non-MachO platforms may return values in these registers via the
789     // personality function.
790     setExceptionPointerRegister(ARM::R0);
791     setExceptionSelectorRegister(ARM::R1);
792   }
793
794   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
795     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
796   else
797     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
798
799   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
800   // the default expansion. If we are targeting a single threaded system,
801   // then set them all for expand so we can lower them later into their
802   // non-atomic form.
803   if (TM.Options.ThreadModel == ThreadModel::Single)
804     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
805   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
806     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
807     // to ldrex/strex loops already.
808     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
809
810     // On v8, we have particularly efficient implementations of atomic fences
811     // if they can be combined with nearby atomic loads and stores.
812     if (!Subtarget->hasV8Ops()) {
813       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
814       setInsertFencesForAtomic(true);
815     }
816   } else {
817     // If there's anything we can use as a barrier, go through custom lowering
818     // for ATOMIC_FENCE.
819     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
820                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
821
822     // Set them all for expansion, which will force libcalls.
823     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
830     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
831     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
832     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
833     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
834     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
835     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
836     // Unordered/Monotonic case.
837     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
838     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
839   }
840
841   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
842
843   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
844   if (!Subtarget->hasV6Ops()) {
845     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
846     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
847   }
848   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
849
850   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
851       !Subtarget->isThumb1Only()) {
852     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
853     // iff target supports vfp2.
854     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
855     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
856   }
857
858   // We want to custom lower some of our intrinsics.
859   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
860   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
861   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
862   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
863   if (Subtarget->isTargetDarwin())
864     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
865
866   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
867   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
868   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
869   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
870   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
871   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
872   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
873   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
874   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
875
876   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
877   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
878   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
879   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
880   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
881
882   // We don't support sin/cos/fmod/copysign/pow
883   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
884   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
885   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
886   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
887   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
888   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
889   setOperationAction(ISD::FREM,      MVT::f64, Expand);
890   setOperationAction(ISD::FREM,      MVT::f32, Expand);
891   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
892       !Subtarget->isThumb1Only()) {
893     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
894     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
895   }
896   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
897   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
898
899   if (!Subtarget->hasVFP4()) {
900     setOperationAction(ISD::FMA, MVT::f64, Expand);
901     setOperationAction(ISD::FMA, MVT::f32, Expand);
902   }
903
904   // Various VFP goodness
905   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
906     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
907     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
908       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
909       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
910     }
911
912     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
913     if (!Subtarget->hasFP16()) {
914       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
915       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
916     }
917   }
918
919   // Combine sin / cos into one node or libcall if possible.
920   if (Subtarget->hasSinCos()) {
921     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
922     setLibcallName(RTLIB::SINCOS_F64, "sincos");
923     if (Subtarget->getTargetTriple().isiOS()) {
924       // For iOS, we don't want to the normal expansion of a libcall to
925       // sincos. We want to issue a libcall to __sincos_stret.
926       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
927       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
928     }
929   }
930
931   // FP-ARMv8 implements a lot of rounding-like FP operations.
932   if (Subtarget->hasFPARMv8()) {
933     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
934     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
935     setOperationAction(ISD::FROUND, MVT::f32, Legal);
936     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
937     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
938     setOperationAction(ISD::FRINT, MVT::f32, Legal);
939     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
940     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
941     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
942     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
943     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
944     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
945
946     if (!Subtarget->isFPOnlySP()) {
947       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
948       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
949       setOperationAction(ISD::FROUND, MVT::f64, Legal);
950       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
951       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
952       setOperationAction(ISD::FRINT, MVT::f64, Legal);
953       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
954       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
955     }
956   }
957
958   if (Subtarget->hasNEON()) {
959     // vmin and vmax aren't available in a scalar form, so we use
960     // a NEON instruction with an undef lane instead.
961     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
962     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
963     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
964     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
965     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
966     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
967   }
968
969   // We have target-specific dag combine patterns for the following nodes:
970   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
971   setTargetDAGCombine(ISD::ADD);
972   setTargetDAGCombine(ISD::SUB);
973   setTargetDAGCombine(ISD::MUL);
974   setTargetDAGCombine(ISD::AND);
975   setTargetDAGCombine(ISD::OR);
976   setTargetDAGCombine(ISD::XOR);
977
978   if (Subtarget->hasV6Ops())
979     setTargetDAGCombine(ISD::SRL);
980
981   setStackPointerRegisterToSaveRestore(ARM::SP);
982
983   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
984       !Subtarget->hasVFP2())
985     setSchedulingPreference(Sched::RegPressure);
986   else
987     setSchedulingPreference(Sched::Hybrid);
988
989   //// temporary - rewrite interface to use type
990   MaxStoresPerMemset = 8;
991   MaxStoresPerMemsetOptSize = 4;
992   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
993   MaxStoresPerMemcpyOptSize = 2;
994   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
995   MaxStoresPerMemmoveOptSize = 2;
996
997   // On ARM arguments smaller than 4 bytes are extended, so all arguments
998   // are at least 4 bytes aligned.
999   setMinStackArgumentAlignment(4);
1000
1001   // Prefer likely predicted branches to selects on out-of-order cores.
1002   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1003
1004   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1005 }
1006
1007 bool ARMTargetLowering::useSoftFloat() const {
1008   return Subtarget->useSoftFloat();
1009 }
1010
1011 // FIXME: It might make sense to define the representative register class as the
1012 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1013 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1014 // SPR's representative would be DPR_VFP2. This should work well if register
1015 // pressure tracking were modified such that a register use would increment the
1016 // pressure of the register class's representative and all of it's super
1017 // classes' representatives transitively. We have not implemented this because
1018 // of the difficulty prior to coalescing of modeling operand register classes
1019 // due to the common occurrence of cross class copies and subregister insertions
1020 // and extractions.
1021 std::pair<const TargetRegisterClass *, uint8_t>
1022 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1023                                            MVT VT) const {
1024   const TargetRegisterClass *RRC = nullptr;
1025   uint8_t Cost = 1;
1026   switch (VT.SimpleTy) {
1027   default:
1028     return TargetLowering::findRepresentativeClass(TRI, VT);
1029   // Use DPR as representative register class for all floating point
1030   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1031   // the cost is 1 for both f32 and f64.
1032   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1033   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1034     RRC = &ARM::DPRRegClass;
1035     // When NEON is used for SP, only half of the register file is available
1036     // because operations that define both SP and DP results will be constrained
1037     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1038     // coalescing by double-counting the SP regs. See the FIXME above.
1039     if (Subtarget->useNEONForSinglePrecisionFP())
1040       Cost = 2;
1041     break;
1042   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1043   case MVT::v4f32: case MVT::v2f64:
1044     RRC = &ARM::DPRRegClass;
1045     Cost = 2;
1046     break;
1047   case MVT::v4i64:
1048     RRC = &ARM::DPRRegClass;
1049     Cost = 4;
1050     break;
1051   case MVT::v8i64:
1052     RRC = &ARM::DPRRegClass;
1053     Cost = 8;
1054     break;
1055   }
1056   return std::make_pair(RRC, Cost);
1057 }
1058
1059 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1060   switch ((ARMISD::NodeType)Opcode) {
1061   case ARMISD::FIRST_NUMBER:  break;
1062   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1063   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1064   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1065   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1066   case ARMISD::CALL:          return "ARMISD::CALL";
1067   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1068   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1069   case ARMISD::tCALL:         return "ARMISD::tCALL";
1070   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1071   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1072   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1073   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1074   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1075   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1076   case ARMISD::CMP:           return "ARMISD::CMP";
1077   case ARMISD::CMN:           return "ARMISD::CMN";
1078   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1079   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1080   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1081   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1082   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1083
1084   case ARMISD::CMOV:          return "ARMISD::CMOV";
1085
1086   case ARMISD::RBIT:          return "ARMISD::RBIT";
1087
1088   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1089   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1090   case ARMISD::RRX:           return "ARMISD::RRX";
1091
1092   case ARMISD::ADDC:          return "ARMISD::ADDC";
1093   case ARMISD::ADDE:          return "ARMISD::ADDE";
1094   case ARMISD::SUBC:          return "ARMISD::SUBC";
1095   case ARMISD::SUBE:          return "ARMISD::SUBE";
1096
1097   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1098   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1099
1100   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1101   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1102   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1103
1104   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1105
1106   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1107
1108   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1109
1110   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1111
1112   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1113
1114   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1115
1116   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1117   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1118   case ARMISD::VCGE:          return "ARMISD::VCGE";
1119   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1120   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1121   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1122   case ARMISD::VCGT:          return "ARMISD::VCGT";
1123   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1124   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1125   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1126   case ARMISD::VTST:          return "ARMISD::VTST";
1127
1128   case ARMISD::VSHL:          return "ARMISD::VSHL";
1129   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1130   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1131   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1132   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1133   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1134   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1135   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1136   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1137   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1138   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1139   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1140   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1141   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1142   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1143   case ARMISD::VSLI:          return "ARMISD::VSLI";
1144   case ARMISD::VSRI:          return "ARMISD::VSRI";
1145   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1146   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1147   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1148   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1149   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1150   case ARMISD::VDUP:          return "ARMISD::VDUP";
1151   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1152   case ARMISD::VEXT:          return "ARMISD::VEXT";
1153   case ARMISD::VREV64:        return "ARMISD::VREV64";
1154   case ARMISD::VREV32:        return "ARMISD::VREV32";
1155   case ARMISD::VREV16:        return "ARMISD::VREV16";
1156   case ARMISD::VZIP:          return "ARMISD::VZIP";
1157   case ARMISD::VUZP:          return "ARMISD::VUZP";
1158   case ARMISD::VTRN:          return "ARMISD::VTRN";
1159   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1160   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1161   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1162   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1163   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1164   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1165   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1166   case ARMISD::BFI:           return "ARMISD::BFI";
1167   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1168   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1169   case ARMISD::VBSL:          return "ARMISD::VBSL";
1170   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1171   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1172   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1173   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1174   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1175   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1176   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1177   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1178   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1179   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1180   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1181   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1182   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1183   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1184   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1185   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1186   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1187   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1188   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1189   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1190   }
1191   return nullptr;
1192 }
1193
1194 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1195                                           EVT VT) const {
1196   if (!VT.isVector())
1197     return getPointerTy(DL);
1198   return VT.changeVectorElementTypeToInteger();
1199 }
1200
1201 /// getRegClassFor - Return the register class that should be used for the
1202 /// specified value type.
1203 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1204   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1205   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1206   // load / store 4 to 8 consecutive D registers.
1207   if (Subtarget->hasNEON()) {
1208     if (VT == MVT::v4i64)
1209       return &ARM::QQPRRegClass;
1210     if (VT == MVT::v8i64)
1211       return &ARM::QQQQPRRegClass;
1212   }
1213   return TargetLowering::getRegClassFor(VT);
1214 }
1215
1216 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1217 // source/dest is aligned and the copy size is large enough. We therefore want
1218 // to align such objects passed to memory intrinsics.
1219 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1220                                                unsigned &PrefAlign) const {
1221   if (!isa<MemIntrinsic>(CI))
1222     return false;
1223   MinSize = 8;
1224   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1225   // cycle faster than 4-byte aligned LDM.
1226   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1227   return true;
1228 }
1229
1230 // Create a fast isel object.
1231 FastISel *
1232 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1233                                   const TargetLibraryInfo *libInfo) const {
1234   return ARM::createFastISel(funcInfo, libInfo);
1235 }
1236
1237 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1238   unsigned NumVals = N->getNumValues();
1239   if (!NumVals)
1240     return Sched::RegPressure;
1241
1242   for (unsigned i = 0; i != NumVals; ++i) {
1243     EVT VT = N->getValueType(i);
1244     if (VT == MVT::Glue || VT == MVT::Other)
1245       continue;
1246     if (VT.isFloatingPoint() || VT.isVector())
1247       return Sched::ILP;
1248   }
1249
1250   if (!N->isMachineOpcode())
1251     return Sched::RegPressure;
1252
1253   // Load are scheduled for latency even if there instruction itinerary
1254   // is not available.
1255   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1256   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1257
1258   if (MCID.getNumDefs() == 0)
1259     return Sched::RegPressure;
1260   if (!Itins->isEmpty() &&
1261       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1262     return Sched::ILP;
1263
1264   return Sched::RegPressure;
1265 }
1266
1267 //===----------------------------------------------------------------------===//
1268 // Lowering Code
1269 //===----------------------------------------------------------------------===//
1270
1271 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1272 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1273   switch (CC) {
1274   default: llvm_unreachable("Unknown condition code!");
1275   case ISD::SETNE:  return ARMCC::NE;
1276   case ISD::SETEQ:  return ARMCC::EQ;
1277   case ISD::SETGT:  return ARMCC::GT;
1278   case ISD::SETGE:  return ARMCC::GE;
1279   case ISD::SETLT:  return ARMCC::LT;
1280   case ISD::SETLE:  return ARMCC::LE;
1281   case ISD::SETUGT: return ARMCC::HI;
1282   case ISD::SETUGE: return ARMCC::HS;
1283   case ISD::SETULT: return ARMCC::LO;
1284   case ISD::SETULE: return ARMCC::LS;
1285   }
1286 }
1287
1288 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1289 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1290                         ARMCC::CondCodes &CondCode2) {
1291   CondCode2 = ARMCC::AL;
1292   switch (CC) {
1293   default: llvm_unreachable("Unknown FP condition!");
1294   case ISD::SETEQ:
1295   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1296   case ISD::SETGT:
1297   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1298   case ISD::SETGE:
1299   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1300   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1301   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1302   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1303   case ISD::SETO:   CondCode = ARMCC::VC; break;
1304   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1305   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1306   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1307   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1308   case ISD::SETLT:
1309   case ISD::SETULT: CondCode = ARMCC::LT; break;
1310   case ISD::SETLE:
1311   case ISD::SETULE: CondCode = ARMCC::LE; break;
1312   case ISD::SETNE:
1313   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1314   }
1315 }
1316
1317 //===----------------------------------------------------------------------===//
1318 //                      Calling Convention Implementation
1319 //===----------------------------------------------------------------------===//
1320
1321 #include "ARMGenCallingConv.inc"
1322
1323 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1324 /// account presence of floating point hardware and calling convention
1325 /// limitations, such as support for variadic functions.
1326 CallingConv::ID
1327 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1328                                            bool isVarArg) const {
1329   switch (CC) {
1330   default:
1331     llvm_unreachable("Unsupported calling convention");
1332   case CallingConv::ARM_AAPCS:
1333   case CallingConv::ARM_APCS:
1334   case CallingConv::GHC:
1335     return CC;
1336   case CallingConv::ARM_AAPCS_VFP:
1337     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1338   case CallingConv::C:
1339     if (!Subtarget->isAAPCS_ABI())
1340       return CallingConv::ARM_APCS;
1341     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1342              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1343              !isVarArg)
1344       return CallingConv::ARM_AAPCS_VFP;
1345     else
1346       return CallingConv::ARM_AAPCS;
1347   case CallingConv::Fast:
1348     if (!Subtarget->isAAPCS_ABI()) {
1349       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1350         return CallingConv::Fast;
1351       return CallingConv::ARM_APCS;
1352     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1353       return CallingConv::ARM_AAPCS_VFP;
1354     else
1355       return CallingConv::ARM_AAPCS;
1356   }
1357 }
1358
1359 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1360 /// CallingConvention.
1361 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1362                                                  bool Return,
1363                                                  bool isVarArg) const {
1364   switch (getEffectiveCallingConv(CC, isVarArg)) {
1365   default:
1366     llvm_unreachable("Unsupported calling convention");
1367   case CallingConv::ARM_APCS:
1368     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1369   case CallingConv::ARM_AAPCS:
1370     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1371   case CallingConv::ARM_AAPCS_VFP:
1372     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1373   case CallingConv::Fast:
1374     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1375   case CallingConv::GHC:
1376     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1377   }
1378 }
1379
1380 /// LowerCallResult - Lower the result values of a call into the
1381 /// appropriate copies out of appropriate physical registers.
1382 SDValue
1383 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1384                                    CallingConv::ID CallConv, bool isVarArg,
1385                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1386                                    SDLoc dl, SelectionDAG &DAG,
1387                                    SmallVectorImpl<SDValue> &InVals,
1388                                    bool isThisReturn, SDValue ThisVal) const {
1389
1390   // Assign locations to each value returned by this call.
1391   SmallVector<CCValAssign, 16> RVLocs;
1392   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1393                     *DAG.getContext(), Call);
1394   CCInfo.AnalyzeCallResult(Ins,
1395                            CCAssignFnForNode(CallConv, /* Return*/ true,
1396                                              isVarArg));
1397
1398   // Copy all of the result registers out of their specified physreg.
1399   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1400     CCValAssign VA = RVLocs[i];
1401
1402     // Pass 'this' value directly from the argument to return value, to avoid
1403     // reg unit interference
1404     if (i == 0 && isThisReturn) {
1405       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1406              "unexpected return calling convention register assignment");
1407       InVals.push_back(ThisVal);
1408       continue;
1409     }
1410
1411     SDValue Val;
1412     if (VA.needsCustom()) {
1413       // Handle f64 or half of a v2f64.
1414       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1415                                       InFlag);
1416       Chain = Lo.getValue(1);
1417       InFlag = Lo.getValue(2);
1418       VA = RVLocs[++i]; // skip ahead to next loc
1419       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1420                                       InFlag);
1421       Chain = Hi.getValue(1);
1422       InFlag = Hi.getValue(2);
1423       if (!Subtarget->isLittle())
1424         std::swap (Lo, Hi);
1425       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1426
1427       if (VA.getLocVT() == MVT::v2f64) {
1428         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1429         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1430                           DAG.getConstant(0, dl, MVT::i32));
1431
1432         VA = RVLocs[++i]; // skip ahead to next loc
1433         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1434         Chain = Lo.getValue(1);
1435         InFlag = Lo.getValue(2);
1436         VA = RVLocs[++i]; // skip ahead to next loc
1437         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1438         Chain = Hi.getValue(1);
1439         InFlag = Hi.getValue(2);
1440         if (!Subtarget->isLittle())
1441           std::swap (Lo, Hi);
1442         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1443         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1444                           DAG.getConstant(1, dl, MVT::i32));
1445       }
1446     } else {
1447       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1448                                InFlag);
1449       Chain = Val.getValue(1);
1450       InFlag = Val.getValue(2);
1451     }
1452
1453     switch (VA.getLocInfo()) {
1454     default: llvm_unreachable("Unknown loc info!");
1455     case CCValAssign::Full: break;
1456     case CCValAssign::BCvt:
1457       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1458       break;
1459     }
1460
1461     InVals.push_back(Val);
1462   }
1463
1464   return Chain;
1465 }
1466
1467 /// LowerMemOpCallTo - Store the argument to the stack.
1468 SDValue
1469 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1470                                     SDValue StackPtr, SDValue Arg,
1471                                     SDLoc dl, SelectionDAG &DAG,
1472                                     const CCValAssign &VA,
1473                                     ISD::ArgFlagsTy Flags) const {
1474   unsigned LocMemOffset = VA.getLocMemOffset();
1475   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1476   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1477                        StackPtr, PtrOff);
1478   return DAG.getStore(
1479       Chain, dl, Arg, PtrOff,
1480       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1481       false, false, 0);
1482 }
1483
1484 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1485                                          SDValue Chain, SDValue &Arg,
1486                                          RegsToPassVector &RegsToPass,
1487                                          CCValAssign &VA, CCValAssign &NextVA,
1488                                          SDValue &StackPtr,
1489                                          SmallVectorImpl<SDValue> &MemOpChains,
1490                                          ISD::ArgFlagsTy Flags) const {
1491
1492   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1493                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1494   unsigned id = Subtarget->isLittle() ? 0 : 1;
1495   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1496
1497   if (NextVA.isRegLoc())
1498     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1499   else {
1500     assert(NextVA.isMemLoc());
1501     if (!StackPtr.getNode())
1502       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1503                                     getPointerTy(DAG.getDataLayout()));
1504
1505     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1506                                            dl, DAG, NextVA,
1507                                            Flags));
1508   }
1509 }
1510
1511 /// LowerCall - Lowering a call into a callseq_start <-
1512 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1513 /// nodes.
1514 SDValue
1515 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1516                              SmallVectorImpl<SDValue> &InVals) const {
1517   SelectionDAG &DAG                     = CLI.DAG;
1518   SDLoc &dl                             = CLI.DL;
1519   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1520   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1521   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1522   SDValue Chain                         = CLI.Chain;
1523   SDValue Callee                        = CLI.Callee;
1524   bool &isTailCall                      = CLI.IsTailCall;
1525   CallingConv::ID CallConv              = CLI.CallConv;
1526   bool doesNotRet                       = CLI.DoesNotReturn;
1527   bool isVarArg                         = CLI.IsVarArg;
1528
1529   MachineFunction &MF = DAG.getMachineFunction();
1530   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1531   bool isThisReturn   = false;
1532   bool isSibCall      = false;
1533   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1534
1535   // Disable tail calls if they're not supported.
1536   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1537     isTailCall = false;
1538
1539   if (isTailCall) {
1540     // Check if it's really possible to do a tail call.
1541     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1542                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1543                                                    Outs, OutVals, Ins, DAG);
1544     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1545       report_fatal_error("failed to perform tail call elimination on a call "
1546                          "site marked musttail");
1547     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1548     // detected sibcalls.
1549     if (isTailCall) {
1550       ++NumTailCalls;
1551       isSibCall = true;
1552     }
1553   }
1554
1555   // Analyze operands of the call, assigning locations to each operand.
1556   SmallVector<CCValAssign, 16> ArgLocs;
1557   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1558                     *DAG.getContext(), Call);
1559   CCInfo.AnalyzeCallOperands(Outs,
1560                              CCAssignFnForNode(CallConv, /* Return*/ false,
1561                                                isVarArg));
1562
1563   // Get a count of how many bytes are to be pushed on the stack.
1564   unsigned NumBytes = CCInfo.getNextStackOffset();
1565
1566   // For tail calls, memory operands are available in our caller's stack.
1567   if (isSibCall)
1568     NumBytes = 0;
1569
1570   // Adjust the stack pointer for the new arguments...
1571   // These operations are automatically eliminated by the prolog/epilog pass
1572   if (!isSibCall)
1573     Chain = DAG.getCALLSEQ_START(Chain,
1574                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1575
1576   SDValue StackPtr =
1577       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1578
1579   RegsToPassVector RegsToPass;
1580   SmallVector<SDValue, 8> MemOpChains;
1581
1582   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1583   // of tail call optimization, arguments are handled later.
1584   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1585        i != e;
1586        ++i, ++realArgIdx) {
1587     CCValAssign &VA = ArgLocs[i];
1588     SDValue Arg = OutVals[realArgIdx];
1589     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1590     bool isByVal = Flags.isByVal();
1591
1592     // Promote the value if needed.
1593     switch (VA.getLocInfo()) {
1594     default: llvm_unreachable("Unknown loc info!");
1595     case CCValAssign::Full: break;
1596     case CCValAssign::SExt:
1597       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1598       break;
1599     case CCValAssign::ZExt:
1600       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1601       break;
1602     case CCValAssign::AExt:
1603       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1604       break;
1605     case CCValAssign::BCvt:
1606       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1607       break;
1608     }
1609
1610     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1611     if (VA.needsCustom()) {
1612       if (VA.getLocVT() == MVT::v2f64) {
1613         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1614                                   DAG.getConstant(0, dl, MVT::i32));
1615         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1616                                   DAG.getConstant(1, dl, MVT::i32));
1617
1618         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1619                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1620
1621         VA = ArgLocs[++i]; // skip ahead to next loc
1622         if (VA.isRegLoc()) {
1623           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1624                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1625         } else {
1626           assert(VA.isMemLoc());
1627
1628           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1629                                                  dl, DAG, VA, Flags));
1630         }
1631       } else {
1632         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1633                          StackPtr, MemOpChains, Flags);
1634       }
1635     } else if (VA.isRegLoc()) {
1636       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1637         assert(VA.getLocVT() == MVT::i32 &&
1638                "unexpected calling convention register assignment");
1639         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1640                "unexpected use of 'returned'");
1641         isThisReturn = true;
1642       }
1643       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1644     } else if (isByVal) {
1645       assert(VA.isMemLoc());
1646       unsigned offset = 0;
1647
1648       // True if this byval aggregate will be split between registers
1649       // and memory.
1650       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1651       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1652
1653       if (CurByValIdx < ByValArgsCount) {
1654
1655         unsigned RegBegin, RegEnd;
1656         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1657
1658         EVT PtrVT =
1659             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1660         unsigned int i, j;
1661         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1662           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1663           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1664           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1665                                      MachinePointerInfo(),
1666                                      false, false, false,
1667                                      DAG.InferPtrAlignment(AddArg));
1668           MemOpChains.push_back(Load.getValue(1));
1669           RegsToPass.push_back(std::make_pair(j, Load));
1670         }
1671
1672         // If parameter size outsides register area, "offset" value
1673         // helps us to calculate stack slot for remained part properly.
1674         offset = RegEnd - RegBegin;
1675
1676         CCInfo.nextInRegsParam();
1677       }
1678
1679       if (Flags.getByValSize() > 4*offset) {
1680         auto PtrVT = getPointerTy(DAG.getDataLayout());
1681         unsigned LocMemOffset = VA.getLocMemOffset();
1682         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1683         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1684         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1685         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1686         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1687                                            MVT::i32);
1688         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1689                                             MVT::i32);
1690
1691         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1692         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1693         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1694                                           Ops));
1695       }
1696     } else if (!isSibCall) {
1697       assert(VA.isMemLoc());
1698
1699       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1700                                              dl, DAG, VA, Flags));
1701     }
1702   }
1703
1704   if (!MemOpChains.empty())
1705     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1706
1707   // Build a sequence of copy-to-reg nodes chained together with token chain
1708   // and flag operands which copy the outgoing args into the appropriate regs.
1709   SDValue InFlag;
1710   // Tail call byval lowering might overwrite argument registers so in case of
1711   // tail call optimization the copies to registers are lowered later.
1712   if (!isTailCall)
1713     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1714       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1715                                RegsToPass[i].second, InFlag);
1716       InFlag = Chain.getValue(1);
1717     }
1718
1719   // For tail calls lower the arguments to the 'real' stack slot.
1720   if (isTailCall) {
1721     // Force all the incoming stack arguments to be loaded from the stack
1722     // before any new outgoing arguments are stored to the stack, because the
1723     // outgoing stack slots may alias the incoming argument stack slots, and
1724     // the alias isn't otherwise explicit. This is slightly more conservative
1725     // than necessary, because it means that each store effectively depends
1726     // on every argument instead of just those arguments it would clobber.
1727
1728     // Do not flag preceding copytoreg stuff together with the following stuff.
1729     InFlag = SDValue();
1730     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1731       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1732                                RegsToPass[i].second, InFlag);
1733       InFlag = Chain.getValue(1);
1734     }
1735     InFlag = SDValue();
1736   }
1737
1738   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1739   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1740   // node so that legalize doesn't hack it.
1741   bool isDirect = false;
1742   bool isARMFunc = false;
1743   bool isLocalARMFunc = false;
1744   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1745   auto PtrVt = getPointerTy(DAG.getDataLayout());
1746
1747   if (Subtarget->genLongCalls()) {
1748     assert((Subtarget->isTargetWindows() ||
1749             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1750            "long-calls with non-static relocation model!");
1751     // Handle a global address or an external symbol. If it's not one of
1752     // those, the target's already in a register, so we don't need to do
1753     // anything extra.
1754     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1755       const GlobalValue *GV = G->getGlobal();
1756       // Create a constant pool entry for the callee address
1757       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1758       ARMConstantPoolValue *CPV =
1759         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1760
1761       // Get the address of the callee into a register
1762       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1763       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1764       Callee = DAG.getLoad(
1765           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1766           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1767           false, false, 0);
1768     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1769       const char *Sym = S->getSymbol();
1770
1771       // Create a constant pool entry for the callee address
1772       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1773       ARMConstantPoolValue *CPV =
1774         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1775                                       ARMPCLabelIndex, 0);
1776       // Get the address of the callee into a register
1777       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1778       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1779       Callee = DAG.getLoad(
1780           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1781           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1782           false, false, 0);
1783     }
1784   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1785     const GlobalValue *GV = G->getGlobal();
1786     isDirect = true;
1787     bool isDef = GV->isStrongDefinitionForLinker();
1788     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1789                    getTargetMachine().getRelocationModel() != Reloc::Static;
1790     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1791     // ARM call to a local ARM function is predicable.
1792     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1793     // tBX takes a register source operand.
1794     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1795       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1796       Callee = DAG.getNode(
1797           ARMISD::WrapperPIC, dl, PtrVt,
1798           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1799       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1800                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1801                            false, false, true, 0);
1802     } else if (Subtarget->isTargetCOFF()) {
1803       assert(Subtarget->isTargetWindows() &&
1804              "Windows is the only supported COFF target");
1805       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1806                                  ? ARMII::MO_DLLIMPORT
1807                                  : ARMII::MO_NO_FLAG;
1808       Callee =
1809           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1810       if (GV->hasDLLImportStorageClass())
1811         Callee =
1812             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1813                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1814                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1815                         false, false, false, 0);
1816     } else {
1817       // On ELF targets for PIC code, direct calls should go through the PLT
1818       unsigned OpFlags = 0;
1819       if (Subtarget->isTargetELF() &&
1820           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1821         OpFlags = ARMII::MO_PLT;
1822       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1823     }
1824   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1825     isDirect = true;
1826     bool isStub = Subtarget->isTargetMachO() &&
1827                   getTargetMachine().getRelocationModel() != Reloc::Static;
1828     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1829     // tBX takes a register source operand.
1830     const char *Sym = S->getSymbol();
1831     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1832       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1833       ARMConstantPoolValue *CPV =
1834         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1835                                       ARMPCLabelIndex, 4);
1836       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1837       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1838       Callee = DAG.getLoad(
1839           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1840           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1841           false, false, 0);
1842       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1843       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1844     } else {
1845       unsigned OpFlags = 0;
1846       // On ELF targets for PIC code, direct calls should go through the PLT
1847       if (Subtarget->isTargetELF() &&
1848                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1849         OpFlags = ARMII::MO_PLT;
1850       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1851     }
1852   }
1853
1854   // FIXME: handle tail calls differently.
1855   unsigned CallOpc;
1856   if (Subtarget->isThumb()) {
1857     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1858       CallOpc = ARMISD::CALL_NOLINK;
1859     else
1860       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1861   } else {
1862     if (!isDirect && !Subtarget->hasV5TOps())
1863       CallOpc = ARMISD::CALL_NOLINK;
1864     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1865              // Emit regular call when code size is the priority
1866              !MF.getFunction()->optForMinSize())
1867       // "mov lr, pc; b _foo" to avoid confusing the RSP
1868       CallOpc = ARMISD::CALL_NOLINK;
1869     else
1870       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1871   }
1872
1873   std::vector<SDValue> Ops;
1874   Ops.push_back(Chain);
1875   Ops.push_back(Callee);
1876
1877   // Add argument registers to the end of the list so that they are known live
1878   // into the call.
1879   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1880     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1881                                   RegsToPass[i].second.getValueType()));
1882
1883   // Add a register mask operand representing the call-preserved registers.
1884   if (!isTailCall) {
1885     const uint32_t *Mask;
1886     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1887     if (isThisReturn) {
1888       // For 'this' returns, use the R0-preserving mask if applicable
1889       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1890       if (!Mask) {
1891         // Set isThisReturn to false if the calling convention is not one that
1892         // allows 'returned' to be modeled in this way, so LowerCallResult does
1893         // not try to pass 'this' straight through
1894         isThisReturn = false;
1895         Mask = ARI->getCallPreservedMask(MF, CallConv);
1896       }
1897     } else
1898       Mask = ARI->getCallPreservedMask(MF, CallConv);
1899
1900     assert(Mask && "Missing call preserved mask for calling convention");
1901     Ops.push_back(DAG.getRegisterMask(Mask));
1902   }
1903
1904   if (InFlag.getNode())
1905     Ops.push_back(InFlag);
1906
1907   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1908   if (isTailCall) {
1909     MF.getFrameInfo()->setHasTailCall();
1910     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1911   }
1912
1913   // Returns a chain and a flag for retval copy to use.
1914   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1915   InFlag = Chain.getValue(1);
1916
1917   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1918                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1919   if (!Ins.empty())
1920     InFlag = Chain.getValue(1);
1921
1922   // Handle result values, copying them out of physregs into vregs that we
1923   // return.
1924   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1925                          InVals, isThisReturn,
1926                          isThisReturn ? OutVals[0] : SDValue());
1927 }
1928
1929 /// HandleByVal - Every parameter *after* a byval parameter is passed
1930 /// on the stack.  Remember the next parameter register to allocate,
1931 /// and then confiscate the rest of the parameter registers to insure
1932 /// this.
1933 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1934                                     unsigned Align) const {
1935   assert((State->getCallOrPrologue() == Prologue ||
1936           State->getCallOrPrologue() == Call) &&
1937          "unhandled ParmContext");
1938
1939   // Byval (as with any stack) slots are always at least 4 byte aligned.
1940   Align = std::max(Align, 4U);
1941
1942   unsigned Reg = State->AllocateReg(GPRArgRegs);
1943   if (!Reg)
1944     return;
1945
1946   unsigned AlignInRegs = Align / 4;
1947   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1948   for (unsigned i = 0; i < Waste; ++i)
1949     Reg = State->AllocateReg(GPRArgRegs);
1950
1951   if (!Reg)
1952     return;
1953
1954   unsigned Excess = 4 * (ARM::R4 - Reg);
1955
1956   // Special case when NSAA != SP and parameter size greater than size of
1957   // all remained GPR regs. In that case we can't split parameter, we must
1958   // send it to stack. We also must set NCRN to R4, so waste all
1959   // remained registers.
1960   const unsigned NSAAOffset = State->getNextStackOffset();
1961   if (NSAAOffset != 0 && Size > Excess) {
1962     while (State->AllocateReg(GPRArgRegs))
1963       ;
1964     return;
1965   }
1966
1967   // First register for byval parameter is the first register that wasn't
1968   // allocated before this method call, so it would be "reg".
1969   // If parameter is small enough to be saved in range [reg, r4), then
1970   // the end (first after last) register would be reg + param-size-in-regs,
1971   // else parameter would be splitted between registers and stack,
1972   // end register would be r4 in this case.
1973   unsigned ByValRegBegin = Reg;
1974   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1975   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1976   // Note, first register is allocated in the beginning of function already,
1977   // allocate remained amount of registers we need.
1978   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1979     State->AllocateReg(GPRArgRegs);
1980   // A byval parameter that is split between registers and memory needs its
1981   // size truncated here.
1982   // In the case where the entire structure fits in registers, we set the
1983   // size in memory to zero.
1984   Size = std::max<int>(Size - Excess, 0);
1985 }
1986
1987 /// MatchingStackOffset - Return true if the given stack call argument is
1988 /// already available in the same position (relatively) of the caller's
1989 /// incoming argument stack.
1990 static
1991 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1992                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1993                          const TargetInstrInfo *TII) {
1994   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1995   int FI = INT_MAX;
1996   if (Arg.getOpcode() == ISD::CopyFromReg) {
1997     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1998     if (!TargetRegisterInfo::isVirtualRegister(VR))
1999       return false;
2000     MachineInstr *Def = MRI->getVRegDef(VR);
2001     if (!Def)
2002       return false;
2003     if (!Flags.isByVal()) {
2004       if (!TII->isLoadFromStackSlot(Def, FI))
2005         return false;
2006     } else {
2007       return false;
2008     }
2009   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2010     if (Flags.isByVal())
2011       // ByVal argument is passed in as a pointer but it's now being
2012       // dereferenced. e.g.
2013       // define @foo(%struct.X* %A) {
2014       //   tail call @bar(%struct.X* byval %A)
2015       // }
2016       return false;
2017     SDValue Ptr = Ld->getBasePtr();
2018     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2019     if (!FINode)
2020       return false;
2021     FI = FINode->getIndex();
2022   } else
2023     return false;
2024
2025   assert(FI != INT_MAX);
2026   if (!MFI->isFixedObjectIndex(FI))
2027     return false;
2028   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2029 }
2030
2031 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2032 /// for tail call optimization. Targets which want to do tail call
2033 /// optimization should implement this function.
2034 bool
2035 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2036                                                      CallingConv::ID CalleeCC,
2037                                                      bool isVarArg,
2038                                                      bool isCalleeStructRet,
2039                                                      bool isCallerStructRet,
2040                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2041                                     const SmallVectorImpl<SDValue> &OutVals,
2042                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2043                                                      SelectionDAG& DAG) const {
2044   const Function *CallerF = DAG.getMachineFunction().getFunction();
2045   CallingConv::ID CallerCC = CallerF->getCallingConv();
2046   bool CCMatch = CallerCC == CalleeCC;
2047
2048   // Look for obvious safe cases to perform tail call optimization that do not
2049   // require ABI changes. This is what gcc calls sibcall.
2050
2051   // Do not sibcall optimize vararg calls unless the call site is not passing
2052   // any arguments.
2053   if (isVarArg && !Outs.empty())
2054     return false;
2055
2056   // Exception-handling functions need a special set of instructions to indicate
2057   // a return to the hardware. Tail-calling another function would probably
2058   // break this.
2059   if (CallerF->hasFnAttribute("interrupt"))
2060     return false;
2061
2062   // Also avoid sibcall optimization if either caller or callee uses struct
2063   // return semantics.
2064   if (isCalleeStructRet || isCallerStructRet)
2065     return false;
2066
2067   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2068   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2069   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2070   // support in the assembler and linker to be used. This would need to be
2071   // fixed to fully support tail calls in Thumb1.
2072   //
2073   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2074   // LR.  This means if we need to reload LR, it takes an extra instructions,
2075   // which outweighs the value of the tail call; but here we don't know yet
2076   // whether LR is going to be used.  Probably the right approach is to
2077   // generate the tail call here and turn it back into CALL/RET in
2078   // emitEpilogue if LR is used.
2079
2080   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2081   // but we need to make sure there are enough registers; the only valid
2082   // registers are the 4 used for parameters.  We don't currently do this
2083   // case.
2084   if (Subtarget->isThumb1Only())
2085     return false;
2086
2087   // Externally-defined functions with weak linkage should not be
2088   // tail-called on ARM when the OS does not support dynamic
2089   // pre-emption of symbols, as the AAELF spec requires normal calls
2090   // to undefined weak functions to be replaced with a NOP or jump to the
2091   // next instruction. The behaviour of branch instructions in this
2092   // situation (as used for tail calls) is implementation-defined, so we
2093   // cannot rely on the linker replacing the tail call with a return.
2094   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2095     const GlobalValue *GV = G->getGlobal();
2096     const Triple &TT = getTargetMachine().getTargetTriple();
2097     if (GV->hasExternalWeakLinkage() &&
2098         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2099       return false;
2100   }
2101
2102   // If the calling conventions do not match, then we'd better make sure the
2103   // results are returned in the same way as what the caller expects.
2104   if (!CCMatch) {
2105     SmallVector<CCValAssign, 16> RVLocs1;
2106     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2107                        *DAG.getContext(), Call);
2108     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2109
2110     SmallVector<CCValAssign, 16> RVLocs2;
2111     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2112                        *DAG.getContext(), Call);
2113     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2114
2115     if (RVLocs1.size() != RVLocs2.size())
2116       return false;
2117     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2118       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2119         return false;
2120       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2121         return false;
2122       if (RVLocs1[i].isRegLoc()) {
2123         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2124           return false;
2125       } else {
2126         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2127           return false;
2128       }
2129     }
2130   }
2131
2132   // If Caller's vararg or byval argument has been split between registers and
2133   // stack, do not perform tail call, since part of the argument is in caller's
2134   // local frame.
2135   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2136                                       getInfo<ARMFunctionInfo>();
2137   if (AFI_Caller->getArgRegsSaveSize())
2138     return false;
2139
2140   // If the callee takes no arguments then go on to check the results of the
2141   // call.
2142   if (!Outs.empty()) {
2143     // Check if stack adjustment is needed. For now, do not do this if any
2144     // argument is passed on the stack.
2145     SmallVector<CCValAssign, 16> ArgLocs;
2146     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2147                       *DAG.getContext(), Call);
2148     CCInfo.AnalyzeCallOperands(Outs,
2149                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2150     if (CCInfo.getNextStackOffset()) {
2151       MachineFunction &MF = DAG.getMachineFunction();
2152
2153       // Check if the arguments are already laid out in the right way as
2154       // the caller's fixed stack objects.
2155       MachineFrameInfo *MFI = MF.getFrameInfo();
2156       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2157       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2158       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2159            i != e;
2160            ++i, ++realArgIdx) {
2161         CCValAssign &VA = ArgLocs[i];
2162         EVT RegVT = VA.getLocVT();
2163         SDValue Arg = OutVals[realArgIdx];
2164         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2165         if (VA.getLocInfo() == CCValAssign::Indirect)
2166           return false;
2167         if (VA.needsCustom()) {
2168           // f64 and vector types are split into multiple registers or
2169           // register/stack-slot combinations.  The types will not match
2170           // the registers; give up on memory f64 refs until we figure
2171           // out what to do about this.
2172           if (!VA.isRegLoc())
2173             return false;
2174           if (!ArgLocs[++i].isRegLoc())
2175             return false;
2176           if (RegVT == MVT::v2f64) {
2177             if (!ArgLocs[++i].isRegLoc())
2178               return false;
2179             if (!ArgLocs[++i].isRegLoc())
2180               return false;
2181           }
2182         } else if (!VA.isRegLoc()) {
2183           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2184                                    MFI, MRI, TII))
2185             return false;
2186         }
2187       }
2188     }
2189   }
2190
2191   return true;
2192 }
2193
2194 bool
2195 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2196                                   MachineFunction &MF, bool isVarArg,
2197                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2198                                   LLVMContext &Context) const {
2199   SmallVector<CCValAssign, 16> RVLocs;
2200   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2201   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2202                                                     isVarArg));
2203 }
2204
2205 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2206                                     SDLoc DL, SelectionDAG &DAG) {
2207   const MachineFunction &MF = DAG.getMachineFunction();
2208   const Function *F = MF.getFunction();
2209
2210   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2211
2212   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2213   // version of the "preferred return address". These offsets affect the return
2214   // instruction if this is a return from PL1 without hypervisor extensions.
2215   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2216   //    SWI:     0      "subs pc, lr, #0"
2217   //    ABORT:   +4     "subs pc, lr, #4"
2218   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2219   // UNDEF varies depending on where the exception came from ARM or Thumb
2220   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2221
2222   int64_t LROffset;
2223   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2224       IntKind == "ABORT")
2225     LROffset = 4;
2226   else if (IntKind == "SWI" || IntKind == "UNDEF")
2227     LROffset = 0;
2228   else
2229     report_fatal_error("Unsupported interrupt attribute. If present, value "
2230                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2231
2232   RetOps.insert(RetOps.begin() + 1,
2233                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2234
2235   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2236 }
2237
2238 SDValue
2239 ARMTargetLowering::LowerReturn(SDValue Chain,
2240                                CallingConv::ID CallConv, bool isVarArg,
2241                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2242                                const SmallVectorImpl<SDValue> &OutVals,
2243                                SDLoc dl, SelectionDAG &DAG) const {
2244
2245   // CCValAssign - represent the assignment of the return value to a location.
2246   SmallVector<CCValAssign, 16> RVLocs;
2247
2248   // CCState - Info about the registers and stack slots.
2249   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2250                     *DAG.getContext(), Call);
2251
2252   // Analyze outgoing return values.
2253   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2254                                                isVarArg));
2255
2256   SDValue Flag;
2257   SmallVector<SDValue, 4> RetOps;
2258   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2259   bool isLittleEndian = Subtarget->isLittle();
2260
2261   MachineFunction &MF = DAG.getMachineFunction();
2262   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2263   AFI->setReturnRegsCount(RVLocs.size());
2264
2265   // Copy the result values into the output registers.
2266   for (unsigned i = 0, realRVLocIdx = 0;
2267        i != RVLocs.size();
2268        ++i, ++realRVLocIdx) {
2269     CCValAssign &VA = RVLocs[i];
2270     assert(VA.isRegLoc() && "Can only return in registers!");
2271
2272     SDValue Arg = OutVals[realRVLocIdx];
2273
2274     switch (VA.getLocInfo()) {
2275     default: llvm_unreachable("Unknown loc info!");
2276     case CCValAssign::Full: break;
2277     case CCValAssign::BCvt:
2278       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2279       break;
2280     }
2281
2282     if (VA.needsCustom()) {
2283       if (VA.getLocVT() == MVT::v2f64) {
2284         // Extract the first half and return it in two registers.
2285         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2286                                    DAG.getConstant(0, dl, MVT::i32));
2287         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2288                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2289
2290         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2292                                  Flag);
2293         Flag = Chain.getValue(1);
2294         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2295         VA = RVLocs[++i]; // skip ahead to next loc
2296         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2297                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2298                                  Flag);
2299         Flag = Chain.getValue(1);
2300         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2301         VA = RVLocs[++i]; // skip ahead to next loc
2302
2303         // Extract the 2nd half and fall through to handle it as an f64 value.
2304         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2305                           DAG.getConstant(1, dl, MVT::i32));
2306       }
2307       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2308       // available.
2309       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2310                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2311       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2312                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2313                                Flag);
2314       Flag = Chain.getValue(1);
2315       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2316       VA = RVLocs[++i]; // skip ahead to next loc
2317       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2318                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2319                                Flag);
2320     } else
2321       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2322
2323     // Guarantee that all emitted copies are
2324     // stuck together, avoiding something bad.
2325     Flag = Chain.getValue(1);
2326     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2327   }
2328
2329   // Update chain and glue.
2330   RetOps[0] = Chain;
2331   if (Flag.getNode())
2332     RetOps.push_back(Flag);
2333
2334   // CPUs which aren't M-class use a special sequence to return from
2335   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2336   // though we use "subs pc, lr, #N").
2337   //
2338   // M-class CPUs actually use a normal return sequence with a special
2339   // (hardware-provided) value in LR, so the normal code path works.
2340   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2341       !Subtarget->isMClass()) {
2342     if (Subtarget->isThumb1Only())
2343       report_fatal_error("interrupt attribute is not supported in Thumb1");
2344     return LowerInterruptReturn(RetOps, dl, DAG);
2345   }
2346
2347   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2348 }
2349
2350 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2351   if (N->getNumValues() != 1)
2352     return false;
2353   if (!N->hasNUsesOfValue(1, 0))
2354     return false;
2355
2356   SDValue TCChain = Chain;
2357   SDNode *Copy = *N->use_begin();
2358   if (Copy->getOpcode() == ISD::CopyToReg) {
2359     // If the copy has a glue operand, we conservatively assume it isn't safe to
2360     // perform a tail call.
2361     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2362       return false;
2363     TCChain = Copy->getOperand(0);
2364   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2365     SDNode *VMov = Copy;
2366     // f64 returned in a pair of GPRs.
2367     SmallPtrSet<SDNode*, 2> Copies;
2368     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2369          UI != UE; ++UI) {
2370       if (UI->getOpcode() != ISD::CopyToReg)
2371         return false;
2372       Copies.insert(*UI);
2373     }
2374     if (Copies.size() > 2)
2375       return false;
2376
2377     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2378          UI != UE; ++UI) {
2379       SDValue UseChain = UI->getOperand(0);
2380       if (Copies.count(UseChain.getNode()))
2381         // Second CopyToReg
2382         Copy = *UI;
2383       else {
2384         // We are at the top of this chain.
2385         // If the copy has a glue operand, we conservatively assume it
2386         // isn't safe to perform a tail call.
2387         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2388           return false;
2389         // First CopyToReg
2390         TCChain = UseChain;
2391       }
2392     }
2393   } else if (Copy->getOpcode() == ISD::BITCAST) {
2394     // f32 returned in a single GPR.
2395     if (!Copy->hasOneUse())
2396       return false;
2397     Copy = *Copy->use_begin();
2398     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2399       return false;
2400     // If the copy has a glue operand, we conservatively assume it isn't safe to
2401     // perform a tail call.
2402     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2403       return false;
2404     TCChain = Copy->getOperand(0);
2405   } else {
2406     return false;
2407   }
2408
2409   bool HasRet = false;
2410   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2411        UI != UE; ++UI) {
2412     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2413         UI->getOpcode() != ARMISD::INTRET_FLAG)
2414       return false;
2415     HasRet = true;
2416   }
2417
2418   if (!HasRet)
2419     return false;
2420
2421   Chain = TCChain;
2422   return true;
2423 }
2424
2425 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2426   if (!Subtarget->supportsTailCall())
2427     return false;
2428
2429   auto Attr =
2430       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2431   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2432     return false;
2433
2434   return !Subtarget->isThumb1Only();
2435 }
2436
2437 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2438 // and pass the lower and high parts through.
2439 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2440   SDLoc DL(Op);
2441   SDValue WriteValue = Op->getOperand(2);
2442
2443   // This function is only supposed to be called for i64 type argument.
2444   assert(WriteValue.getValueType() == MVT::i64
2445           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2446
2447   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2448                            DAG.getConstant(0, DL, MVT::i32));
2449   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2450                            DAG.getConstant(1, DL, MVT::i32));
2451   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2452   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2453 }
2454
2455 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2456 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2457 // one of the above mentioned nodes. It has to be wrapped because otherwise
2458 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2459 // be used to form addressing mode. These wrapped nodes will be selected
2460 // into MOVi.
2461 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2462   EVT PtrVT = Op.getValueType();
2463   // FIXME there is no actual debug info here
2464   SDLoc dl(Op);
2465   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2466   SDValue Res;
2467   if (CP->isMachineConstantPoolEntry())
2468     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2469                                     CP->getAlignment());
2470   else
2471     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2472                                     CP->getAlignment());
2473   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2474 }
2475
2476 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2477   return MachineJumpTableInfo::EK_Inline;
2478 }
2479
2480 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2481                                              SelectionDAG &DAG) const {
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484   unsigned ARMPCLabelIndex = 0;
2485   SDLoc DL(Op);
2486   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2487   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2488   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2489   SDValue CPAddr;
2490   if (RelocM == Reloc::Static) {
2491     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2492   } else {
2493     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2494     ARMPCLabelIndex = AFI->createPICLabelUId();
2495     ARMConstantPoolValue *CPV =
2496       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2497                                       ARMCP::CPBlockAddress, PCAdj);
2498     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2499   }
2500   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2501   SDValue Result =
2502       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2503                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2504                   false, false, false, 0);
2505   if (RelocM == Reloc::Static)
2506     return Result;
2507   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2508   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2509 }
2510
2511 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2512 SDValue
2513 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2514                                                  SelectionDAG &DAG) const {
2515   SDLoc dl(GA);
2516   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2517   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2518   MachineFunction &MF = DAG.getMachineFunction();
2519   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2520   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2521   ARMConstantPoolValue *CPV =
2522     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2523                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2524   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2525   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2526   Argument =
2527       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2528                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2529                   false, false, false, 0);
2530   SDValue Chain = Argument.getValue(1);
2531
2532   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2533   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2534
2535   // call __tls_get_addr.
2536   ArgListTy Args;
2537   ArgListEntry Entry;
2538   Entry.Node = Argument;
2539   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2540   Args.push_back(Entry);
2541
2542   // FIXME: is there useful debug info available here?
2543   TargetLowering::CallLoweringInfo CLI(DAG);
2544   CLI.setDebugLoc(dl).setChain(Chain)
2545     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2546                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2547                0);
2548
2549   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2550   return CallResult.first;
2551 }
2552
2553 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2554 // "local exec" model.
2555 SDValue
2556 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2557                                         SelectionDAG &DAG,
2558                                         TLSModel::Model model) const {
2559   const GlobalValue *GV = GA->getGlobal();
2560   SDLoc dl(GA);
2561   SDValue Offset;
2562   SDValue Chain = DAG.getEntryNode();
2563   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2564   // Get the Thread Pointer
2565   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2566
2567   if (model == TLSModel::InitialExec) {
2568     MachineFunction &MF = DAG.getMachineFunction();
2569     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2571     // Initial exec model.
2572     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2573     ARMConstantPoolValue *CPV =
2574       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2575                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2576                                       true);
2577     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2578     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2579     Offset = DAG.getLoad(
2580         PtrVT, dl, Chain, Offset,
2581         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2582         false, false, 0);
2583     Chain = Offset.getValue(1);
2584
2585     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2586     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2587
2588     Offset = DAG.getLoad(
2589         PtrVT, dl, Chain, Offset,
2590         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2591         false, false, 0);
2592   } else {
2593     // local exec model
2594     assert(model == TLSModel::LocalExec);
2595     ARMConstantPoolValue *CPV =
2596       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2597     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2598     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2599     Offset = DAG.getLoad(
2600         PtrVT, dl, Chain, Offset,
2601         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2602         false, false, 0);
2603   }
2604
2605   // The address of the thread local variable is the add of the thread
2606   // pointer with the offset of the variable.
2607   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2608 }
2609
2610 SDValue
2611 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2612   // TODO: implement the "local dynamic" model
2613   assert(Subtarget->isTargetELF() &&
2614          "TLS not implemented for non-ELF targets");
2615   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2616   if (DAG.getTarget().Options.EmulatedTLS)
2617     return LowerToTLSEmulatedModel(GA, DAG);
2618
2619   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2620
2621   switch (model) {
2622     case TLSModel::GeneralDynamic:
2623     case TLSModel::LocalDynamic:
2624       return LowerToTLSGeneralDynamicModel(GA, DAG);
2625     case TLSModel::InitialExec:
2626     case TLSModel::LocalExec:
2627       return LowerToTLSExecModels(GA, DAG, model);
2628   }
2629   llvm_unreachable("bogus TLS model");
2630 }
2631
2632 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2633                                                  SelectionDAG &DAG) const {
2634   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2635   SDLoc dl(Op);
2636   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2637   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2638     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2639     ARMConstantPoolValue *CPV =
2640       ARMConstantPoolConstant::Create(GV,
2641                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2642     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2643     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2644     SDValue Result = DAG.getLoad(
2645         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2646         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2647         false, false, 0);
2648     SDValue Chain = Result.getValue(1);
2649     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2650     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2651     if (!UseGOTOFF)
2652       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2653                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2654                            false, false, false, 0);
2655     return Result;
2656   }
2657
2658   // If we have T2 ops, we can materialize the address directly via movt/movw
2659   // pair. This is always cheaper.
2660   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2661     ++NumMovwMovt;
2662     // FIXME: Once remat is capable of dealing with instructions with register
2663     // operands, expand this into two nodes.
2664     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2665                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2666   } else {
2667     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2668     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2669     return DAG.getLoad(
2670         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2671         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2672         false, false, 0);
2673   }
2674 }
2675
2676 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2677                                                     SelectionDAG &DAG) const {
2678   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2679   SDLoc dl(Op);
2680   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2681   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2682
2683   if (Subtarget->useMovt(DAG.getMachineFunction()))
2684     ++NumMovwMovt;
2685
2686   // FIXME: Once remat is capable of dealing with instructions with register
2687   // operands, expand this into multiple nodes
2688   unsigned Wrapper =
2689       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2690
2691   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2692   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2693
2694   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2695     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2696                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2697                          false, false, false, 0);
2698   return Result;
2699 }
2700
2701 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2702                                                      SelectionDAG &DAG) const {
2703   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2704   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2705          "Windows on ARM expects to use movw/movt");
2706
2707   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2708   const ARMII::TOF TargetFlags =
2709     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2710   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2711   SDValue Result;
2712   SDLoc DL(Op);
2713
2714   ++NumMovwMovt;
2715
2716   // FIXME: Once remat is capable of dealing with instructions with register
2717   // operands, expand this into two nodes.
2718   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2719                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2720                                                   TargetFlags));
2721   if (GV->hasDLLImportStorageClass())
2722     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2723                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2724                          false, false, false, 0);
2725   return Result;
2726 }
2727
2728 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2729                                                     SelectionDAG &DAG) const {
2730   assert(Subtarget->isTargetELF() &&
2731          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2732   MachineFunction &MF = DAG.getMachineFunction();
2733   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2734   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2735   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2736   SDLoc dl(Op);
2737   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2738   ARMConstantPoolValue *CPV =
2739     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2740                                   ARMPCLabelIndex, PCAdj);
2741   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2742   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2743   SDValue Result =
2744       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2745                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2746                   false, false, false, 0);
2747   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2748   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2749 }
2750
2751 SDValue
2752 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2753   SDLoc dl(Op);
2754   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2755   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2756                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2757                      Op.getOperand(1), Val);
2758 }
2759
2760 SDValue
2761 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2762   SDLoc dl(Op);
2763   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2764                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2765 }
2766
2767 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2768                                                       SelectionDAG &DAG) const {
2769   SDLoc dl(Op);
2770   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2771                      Op.getOperand(0));
2772 }
2773
2774 SDValue
2775 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2776                                           const ARMSubtarget *Subtarget) const {
2777   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2778   SDLoc dl(Op);
2779   switch (IntNo) {
2780   default: return SDValue();    // Don't custom lower most intrinsics.
2781   case Intrinsic::arm_rbit: {
2782     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2783            "RBIT intrinsic must have i32 type!");
2784     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2785   }
2786   case Intrinsic::arm_thread_pointer: {
2787     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2788     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2789   }
2790   case Intrinsic::eh_sjlj_lsda: {
2791     MachineFunction &MF = DAG.getMachineFunction();
2792     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2793     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2794     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2795     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2796     SDValue CPAddr;
2797     unsigned PCAdj = (RelocM != Reloc::PIC_)
2798       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2799     ARMConstantPoolValue *CPV =
2800       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2801                                       ARMCP::CPLSDA, PCAdj);
2802     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2803     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2804     SDValue Result = DAG.getLoad(
2805         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2806         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2807         false, false, 0);
2808
2809     if (RelocM == Reloc::PIC_) {
2810       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2811       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2812     }
2813     return Result;
2814   }
2815   case Intrinsic::arm_neon_vmulls:
2816   case Intrinsic::arm_neon_vmullu: {
2817     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2818       ? ARMISD::VMULLs : ARMISD::VMULLu;
2819     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2820                        Op.getOperand(1), Op.getOperand(2));
2821   }
2822   case Intrinsic::arm_neon_vminnm:
2823   case Intrinsic::arm_neon_vmaxnm: {
2824     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2825       ? ISD::FMINNUM : ISD::FMAXNUM;
2826     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2827                        Op.getOperand(1), Op.getOperand(2));
2828   }
2829   case Intrinsic::arm_neon_vminu:
2830   case Intrinsic::arm_neon_vmaxu: {
2831     if (Op.getValueType().isFloatingPoint())
2832       return SDValue();
2833     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2834       ? ISD::UMIN : ISD::UMAX;
2835     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2836                          Op.getOperand(1), Op.getOperand(2));
2837   }
2838   case Intrinsic::arm_neon_vmins:
2839   case Intrinsic::arm_neon_vmaxs: {
2840     // v{min,max}s is overloaded between signed integers and floats.
2841     if (!Op.getValueType().isFloatingPoint()) {
2842       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2843         ? ISD::SMIN : ISD::SMAX;
2844       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2845                          Op.getOperand(1), Op.getOperand(2));
2846     }
2847     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2848       ? ISD::FMINNAN : ISD::FMAXNAN;
2849     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2850                        Op.getOperand(1), Op.getOperand(2));
2851   }
2852   }
2853 }
2854
2855 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2856                                  const ARMSubtarget *Subtarget) {
2857   // FIXME: handle "fence singlethread" more efficiently.
2858   SDLoc dl(Op);
2859   if (!Subtarget->hasDataBarrier()) {
2860     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2861     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2862     // here.
2863     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2864            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2865     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2866                        DAG.getConstant(0, dl, MVT::i32));
2867   }
2868
2869   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2870   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2871   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2872   if (Subtarget->isMClass()) {
2873     // Only a full system barrier exists in the M-class architectures.
2874     Domain = ARM_MB::SY;
2875   } else if (Subtarget->isSwift() && Ord == Release) {
2876     // Swift happens to implement ISHST barriers in a way that's compatible with
2877     // Release semantics but weaker than ISH so we'd be fools not to use
2878     // it. Beware: other processors probably don't!
2879     Domain = ARM_MB::ISHST;
2880   }
2881
2882   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2883                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2884                      DAG.getConstant(Domain, dl, MVT::i32));
2885 }
2886
2887 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2888                              const ARMSubtarget *Subtarget) {
2889   // ARM pre v5TE and Thumb1 does not have preload instructions.
2890   if (!(Subtarget->isThumb2() ||
2891         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2892     // Just preserve the chain.
2893     return Op.getOperand(0);
2894
2895   SDLoc dl(Op);
2896   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2897   if (!isRead &&
2898       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2899     // ARMv7 with MP extension has PLDW.
2900     return Op.getOperand(0);
2901
2902   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2903   if (Subtarget->isThumb()) {
2904     // Invert the bits.
2905     isRead = ~isRead & 1;
2906     isData = ~isData & 1;
2907   }
2908
2909   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2910                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2911                      DAG.getConstant(isData, dl, MVT::i32));
2912 }
2913
2914 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2915   MachineFunction &MF = DAG.getMachineFunction();
2916   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2917
2918   // vastart just stores the address of the VarArgsFrameIndex slot into the
2919   // memory location argument.
2920   SDLoc dl(Op);
2921   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2922   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2923   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2924   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2925                       MachinePointerInfo(SV), false, false, 0);
2926 }
2927
2928 SDValue
2929 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2930                                         SDValue &Root, SelectionDAG &DAG,
2931                                         SDLoc dl) const {
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2934
2935   const TargetRegisterClass *RC;
2936   if (AFI->isThumb1OnlyFunction())
2937     RC = &ARM::tGPRRegClass;
2938   else
2939     RC = &ARM::GPRRegClass;
2940
2941   // Transform the arguments stored in physical registers into virtual ones.
2942   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2943   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2944
2945   SDValue ArgValue2;
2946   if (NextVA.isMemLoc()) {
2947     MachineFrameInfo *MFI = MF.getFrameInfo();
2948     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2949
2950     // Create load node to retrieve arguments from the stack.
2951     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2952     ArgValue2 = DAG.getLoad(
2953         MVT::i32, dl, Root, FIN,
2954         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2955         false, false, 0);
2956   } else {
2957     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2958     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2959   }
2960   if (!Subtarget->isLittle())
2961     std::swap (ArgValue, ArgValue2);
2962   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2963 }
2964
2965 // The remaining GPRs hold either the beginning of variable-argument
2966 // data, or the beginning of an aggregate passed by value (usually
2967 // byval).  Either way, we allocate stack slots adjacent to the data
2968 // provided by our caller, and store the unallocated registers there.
2969 // If this is a variadic function, the va_list pointer will begin with
2970 // these values; otherwise, this reassembles a (byval) structure that
2971 // was split between registers and memory.
2972 // Return: The frame index registers were stored into.
2973 int
2974 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2975                                   SDLoc dl, SDValue &Chain,
2976                                   const Value *OrigArg,
2977                                   unsigned InRegsParamRecordIdx,
2978                                   int ArgOffset,
2979                                   unsigned ArgSize) const {
2980   // Currently, two use-cases possible:
2981   // Case #1. Non-var-args function, and we meet first byval parameter.
2982   //          Setup first unallocated register as first byval register;
2983   //          eat all remained registers
2984   //          (these two actions are performed by HandleByVal method).
2985   //          Then, here, we initialize stack frame with
2986   //          "store-reg" instructions.
2987   // Case #2. Var-args function, that doesn't contain byval parameters.
2988   //          The same: eat all remained unallocated registers,
2989   //          initialize stack frame.
2990
2991   MachineFunction &MF = DAG.getMachineFunction();
2992   MachineFrameInfo *MFI = MF.getFrameInfo();
2993   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994   unsigned RBegin, REnd;
2995   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2996     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2997   } else {
2998     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2999     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3000     REnd = ARM::R4;
3001   }
3002
3003   if (REnd != RBegin)
3004     ArgOffset = -4 * (ARM::R4 - RBegin);
3005
3006   auto PtrVT = getPointerTy(DAG.getDataLayout());
3007   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3008   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3009
3010   SmallVector<SDValue, 4> MemOps;
3011   const TargetRegisterClass *RC =
3012       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3013
3014   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3015     unsigned VReg = MF.addLiveIn(Reg, RC);
3016     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3017     SDValue Store =
3018         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3019                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3020     MemOps.push_back(Store);
3021     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3022   }
3023
3024   if (!MemOps.empty())
3025     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3026   return FrameIndex;
3027 }
3028
3029 // Setup stack frame, the va_list pointer will start from.
3030 void
3031 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3032                                         SDLoc dl, SDValue &Chain,
3033                                         unsigned ArgOffset,
3034                                         unsigned TotalArgRegsSaveSize,
3035                                         bool ForceMutable) const {
3036   MachineFunction &MF = DAG.getMachineFunction();
3037   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3038
3039   // Try to store any remaining integer argument regs
3040   // to their spots on the stack so that they may be loaded by deferencing
3041   // the result of va_next.
3042   // If there is no regs to be stored, just point address after last
3043   // argument passed via stack.
3044   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3045                                   CCInfo.getInRegsParamsCount(),
3046                                   CCInfo.getNextStackOffset(), 4);
3047   AFI->setVarArgsFrameIndex(FrameIndex);
3048 }
3049
3050 SDValue
3051 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3052                                         CallingConv::ID CallConv, bool isVarArg,
3053                                         const SmallVectorImpl<ISD::InputArg>
3054                                           &Ins,
3055                                         SDLoc dl, SelectionDAG &DAG,
3056                                         SmallVectorImpl<SDValue> &InVals)
3057                                           const {
3058   MachineFunction &MF = DAG.getMachineFunction();
3059   MachineFrameInfo *MFI = MF.getFrameInfo();
3060
3061   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3062
3063   // Assign locations to all of the incoming arguments.
3064   SmallVector<CCValAssign, 16> ArgLocs;
3065   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3066                     *DAG.getContext(), Prologue);
3067   CCInfo.AnalyzeFormalArguments(Ins,
3068                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3069                                                   isVarArg));
3070
3071   SmallVector<SDValue, 16> ArgValues;
3072   SDValue ArgValue;
3073   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3074   unsigned CurArgIdx = 0;
3075
3076   // Initially ArgRegsSaveSize is zero.
3077   // Then we increase this value each time we meet byval parameter.
3078   // We also increase this value in case of varargs function.
3079   AFI->setArgRegsSaveSize(0);
3080
3081   // Calculate the amount of stack space that we need to allocate to store
3082   // byval and variadic arguments that are passed in registers.
3083   // We need to know this before we allocate the first byval or variadic
3084   // argument, as they will be allocated a stack slot below the CFA (Canonical
3085   // Frame Address, the stack pointer at entry to the function).
3086   unsigned ArgRegBegin = ARM::R4;
3087   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3088     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3089       break;
3090
3091     CCValAssign &VA = ArgLocs[i];
3092     unsigned Index = VA.getValNo();
3093     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3094     if (!Flags.isByVal())
3095       continue;
3096
3097     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3098     unsigned RBegin, REnd;
3099     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3100     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3101
3102     CCInfo.nextInRegsParam();
3103   }
3104   CCInfo.rewindByValRegsInfo();
3105
3106   int lastInsIndex = -1;
3107   if (isVarArg && MFI->hasVAStart()) {
3108     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3109     if (RegIdx != array_lengthof(GPRArgRegs))
3110       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3111   }
3112
3113   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3114   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3115   auto PtrVT = getPointerTy(DAG.getDataLayout());
3116
3117   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3118     CCValAssign &VA = ArgLocs[i];
3119     if (Ins[VA.getValNo()].isOrigArg()) {
3120       std::advance(CurOrigArg,
3121                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3122       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3123     }
3124     // Arguments stored in registers.
3125     if (VA.isRegLoc()) {
3126       EVT RegVT = VA.getLocVT();
3127
3128       if (VA.needsCustom()) {
3129         // f64 and vector types are split up into multiple registers or
3130         // combinations of registers and stack slots.
3131         if (VA.getLocVT() == MVT::v2f64) {
3132           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3133                                                    Chain, DAG, dl);
3134           VA = ArgLocs[++i]; // skip ahead to next loc
3135           SDValue ArgValue2;
3136           if (VA.isMemLoc()) {
3137             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3138             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3139             ArgValue2 = DAG.getLoad(
3140                 MVT::f64, dl, Chain, FIN,
3141                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3142                 false, false, false, 0);
3143           } else {
3144             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3145                                              Chain, DAG, dl);
3146           }
3147           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3148           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3149                                  ArgValue, ArgValue1,
3150                                  DAG.getIntPtrConstant(0, dl));
3151           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3152                                  ArgValue, ArgValue2,
3153                                  DAG.getIntPtrConstant(1, dl));
3154         } else
3155           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3156
3157       } else {
3158         const TargetRegisterClass *RC;
3159
3160         if (RegVT == MVT::f32)
3161           RC = &ARM::SPRRegClass;
3162         else if (RegVT == MVT::f64)
3163           RC = &ARM::DPRRegClass;
3164         else if (RegVT == MVT::v2f64)
3165           RC = &ARM::QPRRegClass;
3166         else if (RegVT == MVT::i32)
3167           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3168                                            : &ARM::GPRRegClass;
3169         else
3170           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3171
3172         // Transform the arguments in physical registers into virtual ones.
3173         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3174         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3175       }
3176
3177       // If this is an 8 or 16-bit value, it is really passed promoted
3178       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3179       // truncate to the right size.
3180       switch (VA.getLocInfo()) {
3181       default: llvm_unreachable("Unknown loc info!");
3182       case CCValAssign::Full: break;
3183       case CCValAssign::BCvt:
3184         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3185         break;
3186       case CCValAssign::SExt:
3187         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3188                                DAG.getValueType(VA.getValVT()));
3189         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3190         break;
3191       case CCValAssign::ZExt:
3192         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3193                                DAG.getValueType(VA.getValVT()));
3194         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3195         break;
3196       }
3197
3198       InVals.push_back(ArgValue);
3199
3200     } else { // VA.isRegLoc()
3201
3202       // sanity check
3203       assert(VA.isMemLoc());
3204       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3205
3206       int index = VA.getValNo();
3207
3208       // Some Ins[] entries become multiple ArgLoc[] entries.
3209       // Process them only once.
3210       if (index != lastInsIndex)
3211         {
3212           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3213           // FIXME: For now, all byval parameter objects are marked mutable.
3214           // This can be changed with more analysis.
3215           // In case of tail call optimization mark all arguments mutable.
3216           // Since they could be overwritten by lowering of arguments in case of
3217           // a tail call.
3218           if (Flags.isByVal()) {
3219             assert(Ins[index].isOrigArg() &&
3220                    "Byval arguments cannot be implicit");
3221             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3222
3223             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3224                                             CurByValIndex, VA.getLocMemOffset(),
3225                                             Flags.getByValSize());
3226             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3227             CCInfo.nextInRegsParam();
3228           } else {
3229             unsigned FIOffset = VA.getLocMemOffset();
3230             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3231                                             FIOffset, true);
3232
3233             // Create load nodes to retrieve arguments from the stack.
3234             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3235             InVals.push_back(DAG.getLoad(
3236                 VA.getValVT(), dl, Chain, FIN,
3237                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3238                 false, false, false, 0));
3239           }
3240           lastInsIndex = index;
3241         }
3242     }
3243   }
3244
3245   // varargs
3246   if (isVarArg && MFI->hasVAStart())
3247     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3248                          CCInfo.getNextStackOffset(),
3249                          TotalArgRegsSaveSize);
3250
3251   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3252
3253   return Chain;
3254 }
3255
3256 /// isFloatingPointZero - Return true if this is +0.0.
3257 static bool isFloatingPointZero(SDValue Op) {
3258   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3259     return CFP->getValueAPF().isPosZero();
3260   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3261     // Maybe this has already been legalized into the constant pool?
3262     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3263       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3264       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3265         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3266           return CFP->getValueAPF().isPosZero();
3267     }
3268   } else if (Op->getOpcode() == ISD::BITCAST &&
3269              Op->getValueType(0) == MVT::f64) {
3270     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3271     // created by LowerConstantFP().
3272     SDValue BitcastOp = Op->getOperand(0);
3273     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3274       SDValue MoveOp = BitcastOp->getOperand(0);
3275       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3276           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3277         return true;
3278       }
3279     }
3280   }
3281   return false;
3282 }
3283
3284 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3285 /// the given operands.
3286 SDValue
3287 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3288                              SDValue &ARMcc, SelectionDAG &DAG,
3289                              SDLoc dl) const {
3290   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3291     unsigned C = RHSC->getZExtValue();
3292     if (!isLegalICmpImmediate(C)) {
3293       // Constant does not fit, try adjusting it by one?
3294       switch (CC) {
3295       default: break;
3296       case ISD::SETLT:
3297       case ISD::SETGE:
3298         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3299           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3300           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3301         }
3302         break;
3303       case ISD::SETULT:
3304       case ISD::SETUGE:
3305         if (C != 0 && isLegalICmpImmediate(C-1)) {
3306           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3307           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3308         }
3309         break;
3310       case ISD::SETLE:
3311       case ISD::SETGT:
3312         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3313           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3314           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3315         }
3316         break;
3317       case ISD::SETULE:
3318       case ISD::SETUGT:
3319         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3320           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3321           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3322         }
3323         break;
3324       }
3325     }
3326   }
3327
3328   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3329   ARMISD::NodeType CompareType;
3330   switch (CondCode) {
3331   default:
3332     CompareType = ARMISD::CMP;
3333     break;
3334   case ARMCC::EQ:
3335   case ARMCC::NE:
3336     // Uses only Z Flag
3337     CompareType = ARMISD::CMPZ;
3338     break;
3339   }
3340   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3341   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3342 }
3343
3344 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3345 SDValue
3346 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3347                              SDLoc dl) const {
3348   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3349   SDValue Cmp;
3350   if (!isFloatingPointZero(RHS))
3351     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3352   else
3353     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3354   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3355 }
3356
3357 /// duplicateCmp - Glue values can have only one use, so this function
3358 /// duplicates a comparison node.
3359 SDValue
3360 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3361   unsigned Opc = Cmp.getOpcode();
3362   SDLoc DL(Cmp);
3363   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3364     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3365
3366   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3367   Cmp = Cmp.getOperand(0);
3368   Opc = Cmp.getOpcode();
3369   if (Opc == ARMISD::CMPFP)
3370     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3371   else {
3372     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3373     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3374   }
3375   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3376 }
3377
3378 std::pair<SDValue, SDValue>
3379 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3380                                  SDValue &ARMcc) const {
3381   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3382
3383   SDValue Value, OverflowCmp;
3384   SDValue LHS = Op.getOperand(0);
3385   SDValue RHS = Op.getOperand(1);
3386   SDLoc dl(Op);
3387
3388   // FIXME: We are currently always generating CMPs because we don't support
3389   // generating CMN through the backend. This is not as good as the natural
3390   // CMP case because it causes a register dependency and cannot be folded
3391   // later.
3392
3393   switch (Op.getOpcode()) {
3394   default:
3395     llvm_unreachable("Unknown overflow instruction!");
3396   case ISD::SADDO:
3397     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3398     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3399     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3400     break;
3401   case ISD::UADDO:
3402     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3403     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3404     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3405     break;
3406   case ISD::SSUBO:
3407     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3408     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3409     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3410     break;
3411   case ISD::USUBO:
3412     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3413     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3414     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3415     break;
3416   } // switch (...)
3417
3418   return std::make_pair(Value, OverflowCmp);
3419 }
3420
3421
3422 SDValue
3423 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3424   // Let legalize expand this if it isn't a legal type yet.
3425   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3426     return SDValue();
3427
3428   SDValue Value, OverflowCmp;
3429   SDValue ARMcc;
3430   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3431   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3432   SDLoc dl(Op);
3433   // We use 0 and 1 as false and true values.
3434   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3435   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3436   EVT VT = Op.getValueType();
3437
3438   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3439                                  ARMcc, CCR, OverflowCmp);
3440
3441   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3442   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3443 }
3444
3445
3446 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3447   SDValue Cond = Op.getOperand(0);
3448   SDValue SelectTrue = Op.getOperand(1);
3449   SDValue SelectFalse = Op.getOperand(2);
3450   SDLoc dl(Op);
3451   unsigned Opc = Cond.getOpcode();
3452
3453   if (Cond.getResNo() == 1 &&
3454       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3455        Opc == ISD::USUBO)) {
3456     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3457       return SDValue();
3458
3459     SDValue Value, OverflowCmp;
3460     SDValue ARMcc;
3461     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3462     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3463     EVT VT = Op.getValueType();
3464
3465     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3466                    OverflowCmp, DAG);
3467   }
3468
3469   // Convert:
3470   //
3471   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3472   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3473   //
3474   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3475     const ConstantSDNode *CMOVTrue =
3476       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3477     const ConstantSDNode *CMOVFalse =
3478       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3479
3480     if (CMOVTrue && CMOVFalse) {
3481       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3482       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3483
3484       SDValue True;
3485       SDValue False;
3486       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3487         True = SelectTrue;
3488         False = SelectFalse;
3489       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3490         True = SelectFalse;
3491         False = SelectTrue;
3492       }
3493
3494       if (True.getNode() && False.getNode()) {
3495         EVT VT = Op.getValueType();
3496         SDValue ARMcc = Cond.getOperand(2);
3497         SDValue CCR = Cond.getOperand(3);
3498         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3499         assert(True.getValueType() == VT);
3500         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3501       }
3502     }
3503   }
3504
3505   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3506   // undefined bits before doing a full-word comparison with zero.
3507   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3508                      DAG.getConstant(1, dl, Cond.getValueType()));
3509
3510   return DAG.getSelectCC(dl, Cond,
3511                          DAG.getConstant(0, dl, Cond.getValueType()),
3512                          SelectTrue, SelectFalse, ISD::SETNE);
3513 }
3514
3515 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3516                                  bool &swpCmpOps, bool &swpVselOps) {
3517   // Start by selecting the GE condition code for opcodes that return true for
3518   // 'equality'
3519   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3520       CC == ISD::SETULE)
3521     CondCode = ARMCC::GE;
3522
3523   // and GT for opcodes that return false for 'equality'.
3524   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3525            CC == ISD::SETULT)
3526     CondCode = ARMCC::GT;
3527
3528   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3529   // to swap the compare operands.
3530   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3531       CC == ISD::SETULT)
3532     swpCmpOps = true;
3533
3534   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3535   // If we have an unordered opcode, we need to swap the operands to the VSEL
3536   // instruction (effectively negating the condition).
3537   //
3538   // This also has the effect of swapping which one of 'less' or 'greater'
3539   // returns true, so we also swap the compare operands. It also switches
3540   // whether we return true for 'equality', so we compensate by picking the
3541   // opposite condition code to our original choice.
3542   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3543       CC == ISD::SETUGT) {
3544     swpCmpOps = !swpCmpOps;
3545     swpVselOps = !swpVselOps;
3546     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3547   }
3548
3549   // 'ordered' is 'anything but unordered', so use the VS condition code and
3550   // swap the VSEL operands.
3551   if (CC == ISD::SETO) {
3552     CondCode = ARMCC::VS;
3553     swpVselOps = true;
3554   }
3555
3556   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3557   // code and swap the VSEL operands.
3558   if (CC == ISD::SETUNE) {
3559     CondCode = ARMCC::EQ;
3560     swpVselOps = true;
3561   }
3562 }
3563
3564 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3565                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3566                                    SDValue Cmp, SelectionDAG &DAG) const {
3567   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3568     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3569                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3570     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3571                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3572
3573     SDValue TrueLow = TrueVal.getValue(0);
3574     SDValue TrueHigh = TrueVal.getValue(1);
3575     SDValue FalseLow = FalseVal.getValue(0);
3576     SDValue FalseHigh = FalseVal.getValue(1);
3577
3578     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3579                               ARMcc, CCR, Cmp);
3580     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3581                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3582
3583     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3584   } else {
3585     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3586                        Cmp);
3587   }
3588 }
3589
3590 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3591   EVT VT = Op.getValueType();
3592   SDValue LHS = Op.getOperand(0);
3593   SDValue RHS = Op.getOperand(1);
3594   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3595   SDValue TrueVal = Op.getOperand(2);
3596   SDValue FalseVal = Op.getOperand(3);
3597   SDLoc dl(Op);
3598
3599   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3600     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3601                                                     dl);
3602
3603     // If softenSetCCOperands only returned one value, we should compare it to
3604     // zero.
3605     if (!RHS.getNode()) {
3606       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3607       CC = ISD::SETNE;
3608     }
3609   }
3610
3611   if (LHS.getValueType() == MVT::i32) {
3612     // Try to generate VSEL on ARMv8.
3613     // The VSEL instruction can't use all the usual ARM condition
3614     // codes: it only has two bits to select the condition code, so it's
3615     // constrained to use only GE, GT, VS and EQ.
3616     //
3617     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3618     // swap the operands of the previous compare instruction (effectively
3619     // inverting the compare condition, swapping 'less' and 'greater') and
3620     // sometimes need to swap the operands to the VSEL (which inverts the
3621     // condition in the sense of firing whenever the previous condition didn't)
3622     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3623                                     TrueVal.getValueType() == MVT::f64)) {
3624       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3625       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3626           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3627         CC = ISD::getSetCCInverse(CC, true);
3628         std::swap(TrueVal, FalseVal);
3629       }
3630     }
3631
3632     SDValue ARMcc;
3633     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3634     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3635     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3636   }
3637
3638   ARMCC::CondCodes CondCode, CondCode2;
3639   FPCCToARMCC(CC, CondCode, CondCode2);
3640
3641   // Try to generate VMAXNM/VMINNM on ARMv8.
3642   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3643                                   TrueVal.getValueType() == MVT::f64)) {
3644     bool swpCmpOps = false;
3645     bool swpVselOps = false;
3646     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3647
3648     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3649         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3650       if (swpCmpOps)
3651         std::swap(LHS, RHS);
3652       if (swpVselOps)
3653         std::swap(TrueVal, FalseVal);
3654     }
3655   }
3656
3657   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3658   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3659   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3660   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3661   if (CondCode2 != ARMCC::AL) {
3662     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3663     // FIXME: Needs another CMP because flag can have but one use.
3664     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3665     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3666   }
3667   return Result;
3668 }
3669
3670 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3671 /// to morph to an integer compare sequence.
3672 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3673                            const ARMSubtarget *Subtarget) {
3674   SDNode *N = Op.getNode();
3675   if (!N->hasOneUse())
3676     // Otherwise it requires moving the value from fp to integer registers.
3677     return false;
3678   if (!N->getNumValues())
3679     return false;
3680   EVT VT = Op.getValueType();
3681   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3682     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3683     // vmrs are very slow, e.g. cortex-a8.
3684     return false;
3685
3686   if (isFloatingPointZero(Op)) {
3687     SeenZero = true;
3688     return true;
3689   }
3690   return ISD::isNormalLoad(N);
3691 }
3692
3693 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3694   if (isFloatingPointZero(Op))
3695     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3696
3697   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3698     return DAG.getLoad(MVT::i32, SDLoc(Op),
3699                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3700                        Ld->isVolatile(), Ld->isNonTemporal(),
3701                        Ld->isInvariant(), Ld->getAlignment());
3702
3703   llvm_unreachable("Unknown VFP cmp argument!");
3704 }
3705
3706 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3707                            SDValue &RetVal1, SDValue &RetVal2) {
3708   SDLoc dl(Op);
3709
3710   if (isFloatingPointZero(Op)) {
3711     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3712     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3713     return;
3714   }
3715
3716   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3717     SDValue Ptr = Ld->getBasePtr();
3718     RetVal1 = DAG.getLoad(MVT::i32, dl,
3719                           Ld->getChain(), Ptr,
3720                           Ld->getPointerInfo(),
3721                           Ld->isVolatile(), Ld->isNonTemporal(),
3722                           Ld->isInvariant(), Ld->getAlignment());
3723
3724     EVT PtrType = Ptr.getValueType();
3725     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3726     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3727                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3728     RetVal2 = DAG.getLoad(MVT::i32, dl,
3729                           Ld->getChain(), NewPtr,
3730                           Ld->getPointerInfo().getWithOffset(4),
3731                           Ld->isVolatile(), Ld->isNonTemporal(),
3732                           Ld->isInvariant(), NewAlign);
3733     return;
3734   }
3735
3736   llvm_unreachable("Unknown VFP cmp argument!");
3737 }
3738
3739 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3740 /// f32 and even f64 comparisons to integer ones.
3741 SDValue
3742 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3743   SDValue Chain = Op.getOperand(0);
3744   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3745   SDValue LHS = Op.getOperand(2);
3746   SDValue RHS = Op.getOperand(3);
3747   SDValue Dest = Op.getOperand(4);
3748   SDLoc dl(Op);
3749
3750   bool LHSSeenZero = false;
3751   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3752   bool RHSSeenZero = false;
3753   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3754   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3755     // If unsafe fp math optimization is enabled and there are no other uses of
3756     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3757     // to an integer comparison.
3758     if (CC == ISD::SETOEQ)
3759       CC = ISD::SETEQ;
3760     else if (CC == ISD::SETUNE)
3761       CC = ISD::SETNE;
3762
3763     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3764     SDValue ARMcc;
3765     if (LHS.getValueType() == MVT::f32) {
3766       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3767                         bitcastf32Toi32(LHS, DAG), Mask);
3768       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3769                         bitcastf32Toi32(RHS, DAG), Mask);
3770       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3771       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3772       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3773                          Chain, Dest, ARMcc, CCR, Cmp);
3774     }
3775
3776     SDValue LHS1, LHS2;
3777     SDValue RHS1, RHS2;
3778     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3779     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3780     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3781     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3782     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3783     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3784     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3785     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3786     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3787   }
3788
3789   return SDValue();
3790 }
3791
3792 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3793   SDValue Chain = Op.getOperand(0);
3794   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3795   SDValue LHS = Op.getOperand(2);
3796   SDValue RHS = Op.getOperand(3);
3797   SDValue Dest = Op.getOperand(4);
3798   SDLoc dl(Op);
3799
3800   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3801     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3802                                                     dl);
3803
3804     // If softenSetCCOperands only returned one value, we should compare it to
3805     // zero.
3806     if (!RHS.getNode()) {
3807       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3808       CC = ISD::SETNE;
3809     }
3810   }
3811
3812   if (LHS.getValueType() == MVT::i32) {
3813     SDValue ARMcc;
3814     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3815     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3816     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3817                        Chain, Dest, ARMcc, CCR, Cmp);
3818   }
3819
3820   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3821
3822   if (getTargetMachine().Options.UnsafeFPMath &&
3823       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3824        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3825     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3826     if (Result.getNode())
3827       return Result;
3828   }
3829
3830   ARMCC::CondCodes CondCode, CondCode2;
3831   FPCCToARMCC(CC, CondCode, CondCode2);
3832
3833   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3834   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3835   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3836   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3837   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3838   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3839   if (CondCode2 != ARMCC::AL) {
3840     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3841     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3842     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3843   }
3844   return Res;
3845 }
3846
3847 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3848   SDValue Chain = Op.getOperand(0);
3849   SDValue Table = Op.getOperand(1);
3850   SDValue Index = Op.getOperand(2);
3851   SDLoc dl(Op);
3852
3853   EVT PTy = getPointerTy(DAG.getDataLayout());
3854   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3855   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3856   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3857   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3858   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3859   if (Subtarget->isThumb2()) {
3860     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3861     // which does another jump to the destination. This also makes it easier
3862     // to translate it to TBB / TBH later.
3863     // FIXME: This might not work if the function is extremely large.
3864     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3865                        Addr, Op.getOperand(2), JTI);
3866   }
3867   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3868     Addr =
3869         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3870                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3871                     false, false, false, 0);
3872     Chain = Addr.getValue(1);
3873     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3874     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3875   } else {
3876     Addr =
3877         DAG.getLoad(PTy, dl, Chain, Addr,
3878                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3879                     false, false, false, 0);
3880     Chain = Addr.getValue(1);
3881     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3882   }
3883 }
3884
3885 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3886   EVT VT = Op.getValueType();
3887   SDLoc dl(Op);
3888
3889   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3890     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3891       return Op;
3892     return DAG.UnrollVectorOp(Op.getNode());
3893   }
3894
3895   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3896          "Invalid type for custom lowering!");
3897   if (VT != MVT::v4i16)
3898     return DAG.UnrollVectorOp(Op.getNode());
3899
3900   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3901   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3902 }
3903
3904 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3905   EVT VT = Op.getValueType();
3906   if (VT.isVector())
3907     return LowerVectorFP_TO_INT(Op, DAG);
3908   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3909     RTLIB::Libcall LC;
3910     if (Op.getOpcode() == ISD::FP_TO_SINT)
3911       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3912                               Op.getValueType());
3913     else
3914       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3915                               Op.getValueType());
3916     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3917                        /*isSigned*/ false, SDLoc(Op)).first;
3918   }
3919
3920   return Op;
3921 }
3922
3923 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3924   EVT VT = Op.getValueType();
3925   SDLoc dl(Op);
3926
3927   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3928     if (VT.getVectorElementType() == MVT::f32)
3929       return Op;
3930     return DAG.UnrollVectorOp(Op.getNode());
3931   }
3932
3933   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3934          "Invalid type for custom lowering!");
3935   if (VT != MVT::v4f32)
3936     return DAG.UnrollVectorOp(Op.getNode());
3937
3938   unsigned CastOpc;
3939   unsigned Opc;
3940   switch (Op.getOpcode()) {
3941   default: llvm_unreachable("Invalid opcode!");
3942   case ISD::SINT_TO_FP:
3943     CastOpc = ISD::SIGN_EXTEND;
3944     Opc = ISD::SINT_TO_FP;
3945     break;
3946   case ISD::UINT_TO_FP:
3947     CastOpc = ISD::ZERO_EXTEND;
3948     Opc = ISD::UINT_TO_FP;
3949     break;
3950   }
3951
3952   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3953   return DAG.getNode(Opc, dl, VT, Op);
3954 }
3955
3956 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3957   EVT VT = Op.getValueType();
3958   if (VT.isVector())
3959     return LowerVectorINT_TO_FP(Op, DAG);
3960   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3961     RTLIB::Libcall LC;
3962     if (Op.getOpcode() == ISD::SINT_TO_FP)
3963       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3964                               Op.getValueType());
3965     else
3966       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3967                               Op.getValueType());
3968     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3969                        /*isSigned*/ false, SDLoc(Op)).first;
3970   }
3971
3972   return Op;
3973 }
3974
3975 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3976   // Implement fcopysign with a fabs and a conditional fneg.
3977   SDValue Tmp0 = Op.getOperand(0);
3978   SDValue Tmp1 = Op.getOperand(1);
3979   SDLoc dl(Op);
3980   EVT VT = Op.getValueType();
3981   EVT SrcVT = Tmp1.getValueType();
3982   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3983     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3984   bool UseNEON = !InGPR && Subtarget->hasNEON();
3985
3986   if (UseNEON) {
3987     // Use VBSL to copy the sign bit.
3988     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3989     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3990                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3991     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3992     if (VT == MVT::f64)
3993       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3994                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3995                          DAG.getConstant(32, dl, MVT::i32));
3996     else /*if (VT == MVT::f32)*/
3997       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3998     if (SrcVT == MVT::f32) {
3999       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4000       if (VT == MVT::f64)
4001         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4002                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4003                            DAG.getConstant(32, dl, MVT::i32));
4004     } else if (VT == MVT::f32)
4005       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4006                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4007                          DAG.getConstant(32, dl, MVT::i32));
4008     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4009     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4010
4011     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4012                                             dl, MVT::i32);
4013     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4014     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4015                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4016
4017     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4018                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4019                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4020     if (VT == MVT::f32) {
4021       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4022       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4023                         DAG.getConstant(0, dl, MVT::i32));
4024     } else {
4025       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4026     }
4027
4028     return Res;
4029   }
4030
4031   // Bitcast operand 1 to i32.
4032   if (SrcVT == MVT::f64)
4033     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4034                        Tmp1).getValue(1);
4035   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4036
4037   // Or in the signbit with integer operations.
4038   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4039   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4040   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4041   if (VT == MVT::f32) {
4042     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4043                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4044     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4045                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4046   }
4047
4048   // f64: Or the high part with signbit and then combine two parts.
4049   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4050                      Tmp0);
4051   SDValue Lo = Tmp0.getValue(0);
4052   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4053   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4054   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4055 }
4056
4057 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4058   MachineFunction &MF = DAG.getMachineFunction();
4059   MachineFrameInfo *MFI = MF.getFrameInfo();
4060   MFI->setReturnAddressIsTaken(true);
4061
4062   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4063     return SDValue();
4064
4065   EVT VT = Op.getValueType();
4066   SDLoc dl(Op);
4067   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4068   if (Depth) {
4069     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4070     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4071     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4072                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4073                        MachinePointerInfo(), false, false, false, 0);
4074   }
4075
4076   // Return LR, which contains the return address. Mark it an implicit live-in.
4077   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4078   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4079 }
4080
4081 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4082   const ARMBaseRegisterInfo &ARI =
4083     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4084   MachineFunction &MF = DAG.getMachineFunction();
4085   MachineFrameInfo *MFI = MF.getFrameInfo();
4086   MFI->setFrameAddressIsTaken(true);
4087
4088   EVT VT = Op.getValueType();
4089   SDLoc dl(Op);  // FIXME probably not meaningful
4090   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4091   unsigned FrameReg = ARI.getFrameRegister(MF);
4092   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4093   while (Depth--)
4094     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4095                             MachinePointerInfo(),
4096                             false, false, false, 0);
4097   return FrameAddr;
4098 }
4099
4100 // FIXME? Maybe this could be a TableGen attribute on some registers and
4101 // this table could be generated automatically from RegInfo.
4102 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4103                                               SelectionDAG &DAG) const {
4104   unsigned Reg = StringSwitch<unsigned>(RegName)
4105                        .Case("sp", ARM::SP)
4106                        .Default(0);
4107   if (Reg)
4108     return Reg;
4109   report_fatal_error(Twine("Invalid register name \""
4110                               + StringRef(RegName)  + "\"."));
4111 }
4112
4113 // Result is 64 bit value so split into two 32 bit values and return as a
4114 // pair of values.
4115 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4116                                 SelectionDAG &DAG) {
4117   SDLoc DL(N);
4118
4119   // This function is only supposed to be called for i64 type destination.
4120   assert(N->getValueType(0) == MVT::i64
4121           && "ExpandREAD_REGISTER called for non-i64 type result.");
4122
4123   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4124                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4125                              N->getOperand(0),
4126                              N->getOperand(1));
4127
4128   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4129                     Read.getValue(1)));
4130   Results.push_back(Read.getOperand(0));
4131 }
4132
4133 /// ExpandBITCAST - If the target supports VFP, this function is called to
4134 /// expand a bit convert where either the source or destination type is i64 to
4135 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4136 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4137 /// vectors), since the legalizer won't know what to do with that.
4138 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4140   SDLoc dl(N);
4141   SDValue Op = N->getOperand(0);
4142
4143   // This function is only supposed to be called for i64 types, either as the
4144   // source or destination of the bit convert.
4145   EVT SrcVT = Op.getValueType();
4146   EVT DstVT = N->getValueType(0);
4147   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4148          "ExpandBITCAST called for non-i64 type");
4149
4150   // Turn i64->f64 into VMOVDRR.
4151   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4152     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4153                              DAG.getConstant(0, dl, MVT::i32));
4154     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155                              DAG.getConstant(1, dl, MVT::i32));
4156     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4157                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4158   }
4159
4160   // Turn f64->i64 into VMOVRRD.
4161   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4162     SDValue Cvt;
4163     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4164         SrcVT.getVectorNumElements() > 1)
4165       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166                         DAG.getVTList(MVT::i32, MVT::i32),
4167                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4168     else
4169       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4170                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4171     // Merge the pieces into a single i64 value.
4172     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4173   }
4174
4175   return SDValue();
4176 }
4177
4178 /// getZeroVector - Returns a vector of specified type with all zero elements.
4179 /// Zero vectors are used to represent vector negation and in those cases
4180 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4181 /// not support i64 elements, so sometimes the zero vectors will need to be
4182 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4183 /// zero vector.
4184 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4185   assert(VT.isVector() && "Expected a vector type");
4186   // The canonical modified immediate encoding of a zero vector is....0!
4187   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4188   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4189   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4190   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4191 }
4192
4193 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4194 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4195 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4196                                                 SelectionDAG &DAG) const {
4197   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4198   EVT VT = Op.getValueType();
4199   unsigned VTBits = VT.getSizeInBits();
4200   SDLoc dl(Op);
4201   SDValue ShOpLo = Op.getOperand(0);
4202   SDValue ShOpHi = Op.getOperand(1);
4203   SDValue ShAmt  = Op.getOperand(2);
4204   SDValue ARMcc;
4205   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4206
4207   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4208
4209   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4210                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4211   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4212   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4213                                    DAG.getConstant(VTBits, dl, MVT::i32));
4214   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4215   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4216   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4217
4218   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4219   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4220                           ISD::SETGE, ARMcc, DAG, dl);
4221   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4222   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4223                            CCR, Cmp);
4224
4225   SDValue Ops[2] = { Lo, Hi };
4226   return DAG.getMergeValues(Ops, dl);
4227 }
4228
4229 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4232                                                SelectionDAG &DAG) const {
4233   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234   EVT VT = Op.getValueType();
4235   unsigned VTBits = VT.getSizeInBits();
4236   SDLoc dl(Op);
4237   SDValue ShOpLo = Op.getOperand(0);
4238   SDValue ShOpHi = Op.getOperand(1);
4239   SDValue ShAmt  = Op.getOperand(2);
4240   SDValue ARMcc;
4241
4242   assert(Op.getOpcode() == ISD::SHL_PARTS);
4243   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4244                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4245   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4246   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4247                                    DAG.getConstant(VTBits, dl, MVT::i32));
4248   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4249   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4250
4251   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4253   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4254                           ISD::SETGE, ARMcc, DAG, dl);
4255   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4256   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4257                            CCR, Cmp);
4258
4259   SDValue Ops[2] = { Lo, Hi };
4260   return DAG.getMergeValues(Ops, dl);
4261 }
4262
4263 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4264                                             SelectionDAG &DAG) const {
4265   // The rounding mode is in bits 23:22 of the FPSCR.
4266   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4267   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4268   // so that the shift + and get folded into a bitfield extract.
4269   SDLoc dl(Op);
4270   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4271                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4272                                               MVT::i32));
4273   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4274                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4275   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4276                               DAG.getConstant(22, dl, MVT::i32));
4277   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4278                      DAG.getConstant(3, dl, MVT::i32));
4279 }
4280
4281 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4282                          const ARMSubtarget *ST) {
4283   SDLoc dl(N);
4284   EVT VT = N->getValueType(0);
4285   if (VT.isVector()) {
4286     assert(ST->hasNEON());
4287
4288     // Compute the least significant set bit: LSB = X & -X
4289     SDValue X = N->getOperand(0);
4290     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4291     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4292
4293     EVT ElemTy = VT.getVectorElementType();
4294
4295     if (ElemTy == MVT::i8) {
4296       // Compute with: cttz(x) = ctpop(lsb - 1)
4297       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4298                                 DAG.getTargetConstant(1, dl, ElemTy));
4299       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4300       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4301     }
4302
4303     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4304         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4305       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4306       unsigned NumBits = ElemTy.getSizeInBits();
4307       SDValue WidthMinus1 =
4308           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4309                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4310       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4311       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4312     }
4313
4314     // Compute with: cttz(x) = ctpop(lsb - 1)
4315
4316     // Since we can only compute the number of bits in a byte with vcnt.8, we
4317     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4318     // and i64.
4319
4320     // Compute LSB - 1.
4321     SDValue Bits;
4322     if (ElemTy == MVT::i64) {
4323       // Load constant 0xffff'ffff'ffff'ffff to register.
4324       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4325                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4326       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4327     } else {
4328       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4329                                 DAG.getTargetConstant(1, dl, ElemTy));
4330       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4331     }
4332
4333     // Count #bits with vcnt.8.
4334     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4335     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4336     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4337
4338     // Gather the #bits with vpaddl (pairwise add.)
4339     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4340     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4341         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4342         Cnt8);
4343     if (ElemTy == MVT::i16)
4344       return Cnt16;
4345
4346     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4347     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4348         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4349         Cnt16);
4350     if (ElemTy == MVT::i32)
4351       return Cnt32;
4352
4353     assert(ElemTy == MVT::i64);
4354     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4355         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4356         Cnt32);
4357     return Cnt64;
4358   }
4359
4360   if (!ST->hasV6T2Ops())
4361     return SDValue();
4362
4363   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4364   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4365 }
4366
4367 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4368 /// for each 16-bit element from operand, repeated.  The basic idea is to
4369 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4370 ///
4371 /// Trace for v4i16:
4372 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4373 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4374 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4375 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4376 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4377 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4378 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4379 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4380 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4381   EVT VT = N->getValueType(0);
4382   SDLoc DL(N);
4383
4384   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4385   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4386   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4387   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4388   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4389   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4390 }
4391
4392 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4393 /// bit-count for each 16-bit element from the operand.  We need slightly
4394 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4395 /// 64/128-bit registers.
4396 ///
4397 /// Trace for v4i16:
4398 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4399 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4400 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4401 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4402 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4403   EVT VT = N->getValueType(0);
4404   SDLoc DL(N);
4405
4406   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4407   if (VT.is64BitVector()) {
4408     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4409     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4410                        DAG.getIntPtrConstant(0, DL));
4411   } else {
4412     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4413                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4414     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4415   }
4416 }
4417
4418 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4419 /// bit-count for each 32-bit element from the operand.  The idea here is
4420 /// to split the vector into 16-bit elements, leverage the 16-bit count
4421 /// routine, and then combine the results.
4422 ///
4423 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4424 /// input    = [v0    v1    ] (vi: 32-bit elements)
4425 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4426 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4427 /// vrev: N0 = [k1 k0 k3 k2 ]
4428 ///            [k0 k1 k2 k3 ]
4429 ///       N1 =+[k1 k0 k3 k2 ]
4430 ///            [k0 k2 k1 k3 ]
4431 ///       N2 =+[k1 k3 k0 k2 ]
4432 ///            [k0    k2    k1    k3    ]
4433 /// Extended =+[k1    k3    k0    k2    ]
4434 ///            [k0    k2    ]
4435 /// Extracted=+[k1    k3    ]
4436 ///
4437 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4438   EVT VT = N->getValueType(0);
4439   SDLoc DL(N);
4440
4441   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4442
4443   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4444   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4445   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4446   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4447   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4448
4449   if (VT.is64BitVector()) {
4450     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4451     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4452                        DAG.getIntPtrConstant(0, DL));
4453   } else {
4454     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4455                                     DAG.getIntPtrConstant(0, DL));
4456     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4457   }
4458 }
4459
4460 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4461                           const ARMSubtarget *ST) {
4462   EVT VT = N->getValueType(0);
4463
4464   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4465   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4466           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4467          "Unexpected type for custom ctpop lowering");
4468
4469   if (VT.getVectorElementType() == MVT::i32)
4470     return lowerCTPOP32BitElements(N, DAG);
4471   else
4472     return lowerCTPOP16BitElements(N, DAG);
4473 }
4474
4475 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4476                           const ARMSubtarget *ST) {
4477   EVT VT = N->getValueType(0);
4478   SDLoc dl(N);
4479
4480   if (!VT.isVector())
4481     return SDValue();
4482
4483   // Lower vector shifts on NEON to use VSHL.
4484   assert(ST->hasNEON() && "unexpected vector shift");
4485
4486   // Left shifts translate directly to the vshiftu intrinsic.
4487   if (N->getOpcode() == ISD::SHL)
4488     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4489                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4490                                        MVT::i32),
4491                        N->getOperand(0), N->getOperand(1));
4492
4493   assert((N->getOpcode() == ISD::SRA ||
4494           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4495
4496   // NEON uses the same intrinsics for both left and right shifts.  For
4497   // right shifts, the shift amounts are negative, so negate the vector of
4498   // shift amounts.
4499   EVT ShiftVT = N->getOperand(1).getValueType();
4500   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4501                                      getZeroVector(ShiftVT, DAG, dl),
4502                                      N->getOperand(1));
4503   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4504                              Intrinsic::arm_neon_vshifts :
4505                              Intrinsic::arm_neon_vshiftu);
4506   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4507                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4508                      N->getOperand(0), NegatedCount);
4509 }
4510
4511 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4512                                 const ARMSubtarget *ST) {
4513   EVT VT = N->getValueType(0);
4514   SDLoc dl(N);
4515
4516   // We can get here for a node like i32 = ISD::SHL i32, i64
4517   if (VT != MVT::i64)
4518     return SDValue();
4519
4520   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4521          "Unknown shift to lower!");
4522
4523   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4524   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4525       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4526     return SDValue();
4527
4528   // If we are in thumb mode, we don't have RRX.
4529   if (ST->isThumb1Only()) return SDValue();
4530
4531   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4532   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4533                            DAG.getConstant(0, dl, MVT::i32));
4534   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4535                            DAG.getConstant(1, dl, MVT::i32));
4536
4537   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4538   // captures the result into a carry flag.
4539   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4540   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4541
4542   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4543   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4544
4545   // Merge the pieces into a single i64 value.
4546  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4547 }
4548
4549 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4550   SDValue TmpOp0, TmpOp1;
4551   bool Invert = false;
4552   bool Swap = false;
4553   unsigned Opc = 0;
4554
4555   SDValue Op0 = Op.getOperand(0);
4556   SDValue Op1 = Op.getOperand(1);
4557   SDValue CC = Op.getOperand(2);
4558   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4559   EVT VT = Op.getValueType();
4560   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4561   SDLoc dl(Op);
4562
4563   if (CmpVT.getVectorElementType() == MVT::i64)
4564     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4565     // but it's possible that our operands are 64-bit but our result is 32-bit.
4566     // Bail in this case.
4567     return SDValue();
4568
4569   if (Op1.getValueType().isFloatingPoint()) {
4570     switch (SetCCOpcode) {
4571     default: llvm_unreachable("Illegal FP comparison");
4572     case ISD::SETUNE:
4573     case ISD::SETNE:  Invert = true; // Fallthrough
4574     case ISD::SETOEQ:
4575     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4576     case ISD::SETOLT:
4577     case ISD::SETLT: Swap = true; // Fallthrough
4578     case ISD::SETOGT:
4579     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4580     case ISD::SETOLE:
4581     case ISD::SETLE:  Swap = true; // Fallthrough
4582     case ISD::SETOGE:
4583     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4584     case ISD::SETUGE: Swap = true; // Fallthrough
4585     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4586     case ISD::SETUGT: Swap = true; // Fallthrough
4587     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4588     case ISD::SETUEQ: Invert = true; // Fallthrough
4589     case ISD::SETONE:
4590       // Expand this to (OLT | OGT).
4591       TmpOp0 = Op0;
4592       TmpOp1 = Op1;
4593       Opc = ISD::OR;
4594       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4595       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4596       break;
4597     case ISD::SETUO: Invert = true; // Fallthrough
4598     case ISD::SETO:
4599       // Expand this to (OLT | OGE).
4600       TmpOp0 = Op0;
4601       TmpOp1 = Op1;
4602       Opc = ISD::OR;
4603       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4604       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4605       break;
4606     }
4607   } else {
4608     // Integer comparisons.
4609     switch (SetCCOpcode) {
4610     default: llvm_unreachable("Illegal integer comparison");
4611     case ISD::SETNE:  Invert = true;
4612     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4613     case ISD::SETLT:  Swap = true;
4614     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4615     case ISD::SETLE:  Swap = true;
4616     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4617     case ISD::SETULT: Swap = true;
4618     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4619     case ISD::SETULE: Swap = true;
4620     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4621     }
4622
4623     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4624     if (Opc == ARMISD::VCEQ) {
4625
4626       SDValue AndOp;
4627       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4628         AndOp = Op0;
4629       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4630         AndOp = Op1;
4631
4632       // Ignore bitconvert.
4633       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4634         AndOp = AndOp.getOperand(0);
4635
4636       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4637         Opc = ARMISD::VTST;
4638         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4639         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4640         Invert = !Invert;
4641       }
4642     }
4643   }
4644
4645   if (Swap)
4646     std::swap(Op0, Op1);
4647
4648   // If one of the operands is a constant vector zero, attempt to fold the
4649   // comparison to a specialized compare-against-zero form.
4650   SDValue SingleOp;
4651   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4652     SingleOp = Op0;
4653   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4654     if (Opc == ARMISD::VCGE)
4655       Opc = ARMISD::VCLEZ;
4656     else if (Opc == ARMISD::VCGT)
4657       Opc = ARMISD::VCLTZ;
4658     SingleOp = Op1;
4659   }
4660
4661   SDValue Result;
4662   if (SingleOp.getNode()) {
4663     switch (Opc) {
4664     case ARMISD::VCEQ:
4665       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4666     case ARMISD::VCGE:
4667       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4668     case ARMISD::VCLEZ:
4669       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4670     case ARMISD::VCGT:
4671       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4672     case ARMISD::VCLTZ:
4673       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4674     default:
4675       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4676     }
4677   } else {
4678      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4679   }
4680
4681   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4682
4683   if (Invert)
4684     Result = DAG.getNOT(dl, Result, VT);
4685
4686   return Result;
4687 }
4688
4689 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4690 /// valid vector constant for a NEON instruction with a "modified immediate"
4691 /// operand (e.g., VMOV).  If so, return the encoded value.
4692 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4693                                  unsigned SplatBitSize, SelectionDAG &DAG,
4694                                  SDLoc dl, EVT &VT, bool is128Bits,
4695                                  NEONModImmType type) {
4696   unsigned OpCmode, Imm;
4697
4698   // SplatBitSize is set to the smallest size that splats the vector, so a
4699   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4700   // immediate instructions others than VMOV do not support the 8-bit encoding
4701   // of a zero vector, and the default encoding of zero is supposed to be the
4702   // 32-bit version.
4703   if (SplatBits == 0)
4704     SplatBitSize = 32;
4705
4706   switch (SplatBitSize) {
4707   case 8:
4708     if (type != VMOVModImm)
4709       return SDValue();
4710     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4711     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4712     OpCmode = 0xe;
4713     Imm = SplatBits;
4714     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4715     break;
4716
4717   case 16:
4718     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4719     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4720     if ((SplatBits & ~0xff) == 0) {
4721       // Value = 0x00nn: Op=x, Cmode=100x.
4722       OpCmode = 0x8;
4723       Imm = SplatBits;
4724       break;
4725     }
4726     if ((SplatBits & ~0xff00) == 0) {
4727       // Value = 0xnn00: Op=x, Cmode=101x.
4728       OpCmode = 0xa;
4729       Imm = SplatBits >> 8;
4730       break;
4731     }
4732     return SDValue();
4733
4734   case 32:
4735     // NEON's 32-bit VMOV supports splat values where:
4736     // * only one byte is nonzero, or
4737     // * the least significant byte is 0xff and the second byte is nonzero, or
4738     // * the least significant 2 bytes are 0xff and the third is nonzero.
4739     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4740     if ((SplatBits & ~0xff) == 0) {
4741       // Value = 0x000000nn: Op=x, Cmode=000x.
4742       OpCmode = 0;
4743       Imm = SplatBits;
4744       break;
4745     }
4746     if ((SplatBits & ~0xff00) == 0) {
4747       // Value = 0x0000nn00: Op=x, Cmode=001x.
4748       OpCmode = 0x2;
4749       Imm = SplatBits >> 8;
4750       break;
4751     }
4752     if ((SplatBits & ~0xff0000) == 0) {
4753       // Value = 0x00nn0000: Op=x, Cmode=010x.
4754       OpCmode = 0x4;
4755       Imm = SplatBits >> 16;
4756       break;
4757     }
4758     if ((SplatBits & ~0xff000000) == 0) {
4759       // Value = 0xnn000000: Op=x, Cmode=011x.
4760       OpCmode = 0x6;
4761       Imm = SplatBits >> 24;
4762       break;
4763     }
4764
4765     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4766     if (type == OtherModImm) return SDValue();
4767
4768     if ((SplatBits & ~0xffff) == 0 &&
4769         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4770       // Value = 0x0000nnff: Op=x, Cmode=1100.
4771       OpCmode = 0xc;
4772       Imm = SplatBits >> 8;
4773       break;
4774     }
4775
4776     if ((SplatBits & ~0xffffff) == 0 &&
4777         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4778       // Value = 0x00nnffff: Op=x, Cmode=1101.
4779       OpCmode = 0xd;
4780       Imm = SplatBits >> 16;
4781       break;
4782     }
4783
4784     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4785     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4786     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4787     // and fall through here to test for a valid 64-bit splat.  But, then the
4788     // caller would also need to check and handle the change in size.
4789     return SDValue();
4790
4791   case 64: {
4792     if (type != VMOVModImm)
4793       return SDValue();
4794     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4795     uint64_t BitMask = 0xff;
4796     uint64_t Val = 0;
4797     unsigned ImmMask = 1;
4798     Imm = 0;
4799     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4800       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4801         Val |= BitMask;
4802         Imm |= ImmMask;
4803       } else if ((SplatBits & BitMask) != 0) {
4804         return SDValue();
4805       }
4806       BitMask <<= 8;
4807       ImmMask <<= 1;
4808     }
4809
4810     if (DAG.getDataLayout().isBigEndian())
4811       // swap higher and lower 32 bit word
4812       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4813
4814     // Op=1, Cmode=1110.
4815     OpCmode = 0x1e;
4816     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4817     break;
4818   }
4819
4820   default:
4821     llvm_unreachable("unexpected size for isNEONModifiedImm");
4822   }
4823
4824   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4825   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4826 }
4827
4828 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4829                                            const ARMSubtarget *ST) const {
4830   if (!ST->hasVFP3())
4831     return SDValue();
4832
4833   bool IsDouble = Op.getValueType() == MVT::f64;
4834   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4835
4836   // Use the default (constant pool) lowering for double constants when we have
4837   // an SP-only FPU
4838   if (IsDouble && Subtarget->isFPOnlySP())
4839     return SDValue();
4840
4841   // Try splatting with a VMOV.f32...
4842   APFloat FPVal = CFP->getValueAPF();
4843   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4844
4845   if (ImmVal != -1) {
4846     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4847       // We have code in place to select a valid ConstantFP already, no need to
4848       // do any mangling.
4849       return Op;
4850     }
4851
4852     // It's a float and we are trying to use NEON operations where
4853     // possible. Lower it to a splat followed by an extract.
4854     SDLoc DL(Op);
4855     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4856     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4857                                       NewVal);
4858     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4859                        DAG.getConstant(0, DL, MVT::i32));
4860   }
4861
4862   // The rest of our options are NEON only, make sure that's allowed before
4863   // proceeding..
4864   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4865     return SDValue();
4866
4867   EVT VMovVT;
4868   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4869
4870   // It wouldn't really be worth bothering for doubles except for one very
4871   // important value, which does happen to match: 0.0. So make sure we don't do
4872   // anything stupid.
4873   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4874     return SDValue();
4875
4876   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4877   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4878                                      VMovVT, false, VMOVModImm);
4879   if (NewVal != SDValue()) {
4880     SDLoc DL(Op);
4881     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4882                                       NewVal);
4883     if (IsDouble)
4884       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4885
4886     // It's a float: cast and extract a vector element.
4887     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4888                                        VecConstant);
4889     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4890                        DAG.getConstant(0, DL, MVT::i32));
4891   }
4892
4893   // Finally, try a VMVN.i32
4894   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4895                              false, VMVNModImm);
4896   if (NewVal != SDValue()) {
4897     SDLoc DL(Op);
4898     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4899
4900     if (IsDouble)
4901       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4902
4903     // It's a float: cast and extract a vector element.
4904     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4905                                        VecConstant);
4906     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4907                        DAG.getConstant(0, DL, MVT::i32));
4908   }
4909
4910   return SDValue();
4911 }
4912
4913 // check if an VEXT instruction can handle the shuffle mask when the
4914 // vector sources of the shuffle are the same.
4915 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4916   unsigned NumElts = VT.getVectorNumElements();
4917
4918   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4919   if (M[0] < 0)
4920     return false;
4921
4922   Imm = M[0];
4923
4924   // If this is a VEXT shuffle, the immediate value is the index of the first
4925   // element.  The other shuffle indices must be the successive elements after
4926   // the first one.
4927   unsigned ExpectedElt = Imm;
4928   for (unsigned i = 1; i < NumElts; ++i) {
4929     // Increment the expected index.  If it wraps around, just follow it
4930     // back to index zero and keep going.
4931     ++ExpectedElt;
4932     if (ExpectedElt == NumElts)
4933       ExpectedElt = 0;
4934
4935     if (M[i] < 0) continue; // ignore UNDEF indices
4936     if (ExpectedElt != static_cast<unsigned>(M[i]))
4937       return false;
4938   }
4939
4940   return true;
4941 }
4942
4943
4944 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4945                        bool &ReverseVEXT, unsigned &Imm) {
4946   unsigned NumElts = VT.getVectorNumElements();
4947   ReverseVEXT = false;
4948
4949   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4950   if (M[0] < 0)
4951     return false;
4952
4953   Imm = M[0];
4954
4955   // If this is a VEXT shuffle, the immediate value is the index of the first
4956   // element.  The other shuffle indices must be the successive elements after
4957   // the first one.
4958   unsigned ExpectedElt = Imm;
4959   for (unsigned i = 1; i < NumElts; ++i) {
4960     // Increment the expected index.  If it wraps around, it may still be
4961     // a VEXT but the source vectors must be swapped.
4962     ExpectedElt += 1;
4963     if (ExpectedElt == NumElts * 2) {
4964       ExpectedElt = 0;
4965       ReverseVEXT = true;
4966     }
4967
4968     if (M[i] < 0) continue; // ignore UNDEF indices
4969     if (ExpectedElt != static_cast<unsigned>(M[i]))
4970       return false;
4971   }
4972
4973   // Adjust the index value if the source operands will be swapped.
4974   if (ReverseVEXT)
4975     Imm -= NumElts;
4976
4977   return true;
4978 }
4979
4980 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4981 /// instruction with the specified blocksize.  (The order of the elements
4982 /// within each block of the vector is reversed.)
4983 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4984   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4985          "Only possible block sizes for VREV are: 16, 32, 64");
4986
4987   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4988   if (EltSz == 64)
4989     return false;
4990
4991   unsigned NumElts = VT.getVectorNumElements();
4992   unsigned BlockElts = M[0] + 1;
4993   // If the first shuffle index is UNDEF, be optimistic.
4994   if (M[0] < 0)
4995     BlockElts = BlockSize / EltSz;
4996
4997   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4998     return false;
4999
5000   for (unsigned i = 0; i < NumElts; ++i) {
5001     if (M[i] < 0) continue; // ignore UNDEF indices
5002     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5003       return false;
5004   }
5005
5006   return true;
5007 }
5008
5009 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5010   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5011   // range, then 0 is placed into the resulting vector. So pretty much any mask
5012   // of 8 elements can work here.
5013   return VT == MVT::v8i8 && M.size() == 8;
5014 }
5015
5016 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5017 // checking that pairs of elements in the shuffle mask represent the same index
5018 // in each vector, incrementing the expected index by 2 at each step.
5019 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5020 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5021 //  v2={e,f,g,h}
5022 // WhichResult gives the offset for each element in the mask based on which
5023 // of the two results it belongs to.
5024 //
5025 // The transpose can be represented either as:
5026 // result1 = shufflevector v1, v2, result1_shuffle_mask
5027 // result2 = shufflevector v1, v2, result2_shuffle_mask
5028 // where v1/v2 and the shuffle masks have the same number of elements
5029 // (here WhichResult (see below) indicates which result is being checked)
5030 //
5031 // or as:
5032 // results = shufflevector v1, v2, shuffle_mask
5033 // where both results are returned in one vector and the shuffle mask has twice
5034 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5035 // want to check the low half and high half of the shuffle mask as if it were
5036 // the other case
5037 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5038   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5039   if (EltSz == 64)
5040     return false;
5041
5042   unsigned NumElts = VT.getVectorNumElements();
5043   if (M.size() != NumElts && M.size() != NumElts*2)
5044     return false;
5045
5046   // If the mask is twice as long as the result then we need to check the upper
5047   // and lower parts of the mask
5048   for (unsigned i = 0; i < M.size(); i += NumElts) {
5049     WhichResult = M[i] == 0 ? 0 : 1;
5050     for (unsigned j = 0; j < NumElts; j += 2) {
5051       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5052           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5053         return false;
5054     }
5055   }
5056
5057   if (M.size() == NumElts*2)
5058     WhichResult = 0;
5059
5060   return true;
5061 }
5062
5063 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5064 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5065 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5066 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5067   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5068   if (EltSz == 64)
5069     return false;
5070
5071   unsigned NumElts = VT.getVectorNumElements();
5072   if (M.size() != NumElts && M.size() != NumElts*2)
5073     return false;
5074
5075   for (unsigned i = 0; i < M.size(); i += NumElts) {
5076     WhichResult = M[i] == 0 ? 0 : 1;
5077     for (unsigned j = 0; j < NumElts; j += 2) {
5078       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5079           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5080         return false;
5081     }
5082   }
5083
5084   if (M.size() == NumElts*2)
5085     WhichResult = 0;
5086
5087   return true;
5088 }
5089
5090 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5091 // that the mask elements are either all even and in steps of size 2 or all odd
5092 // and in steps of size 2.
5093 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5094 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5095 //  v2={e,f,g,h}
5096 // Requires similar checks to that of isVTRNMask with
5097 // respect the how results are returned.
5098 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5099   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5100   if (EltSz == 64)
5101     return false;
5102
5103   unsigned NumElts = VT.getVectorNumElements();
5104   if (M.size() != NumElts && M.size() != NumElts*2)
5105     return false;
5106
5107   for (unsigned i = 0; i < M.size(); i += NumElts) {
5108     WhichResult = M[i] == 0 ? 0 : 1;
5109     for (unsigned j = 0; j < NumElts; ++j) {
5110       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5111         return false;
5112     }
5113   }
5114
5115   if (M.size() == NumElts*2)
5116     WhichResult = 0;
5117
5118   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5119   if (VT.is64BitVector() && EltSz == 32)
5120     return false;
5121
5122   return true;
5123 }
5124
5125 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5126 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5127 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5128 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5129   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5130   if (EltSz == 64)
5131     return false;
5132
5133   unsigned NumElts = VT.getVectorNumElements();
5134   if (M.size() != NumElts && M.size() != NumElts*2)
5135     return false;
5136
5137   unsigned Half = NumElts / 2;
5138   for (unsigned i = 0; i < M.size(); i += NumElts) {
5139     WhichResult = M[i] == 0 ? 0 : 1;
5140     for (unsigned j = 0; j < NumElts; j += Half) {
5141       unsigned Idx = WhichResult;
5142       for (unsigned k = 0; k < Half; ++k) {
5143         int MIdx = M[i + j + k];
5144         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5145           return false;
5146         Idx += 2;
5147       }
5148     }
5149   }
5150
5151   if (M.size() == NumElts*2)
5152     WhichResult = 0;
5153
5154   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5155   if (VT.is64BitVector() && EltSz == 32)
5156     return false;
5157
5158   return true;
5159 }
5160
5161 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5162 // that pairs of elements of the shufflemask represent the same index in each
5163 // vector incrementing sequentially through the vectors.
5164 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5165 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5166 //  v2={e,f,g,h}
5167 // Requires similar checks to that of isVTRNMask with respect the how results
5168 // are returned.
5169 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5170   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5171   if (EltSz == 64)
5172     return false;
5173
5174   unsigned NumElts = VT.getVectorNumElements();
5175   if (M.size() != NumElts && M.size() != NumElts*2)
5176     return false;
5177
5178   for (unsigned i = 0; i < M.size(); i += NumElts) {
5179     WhichResult = M[i] == 0 ? 0 : 1;
5180     unsigned Idx = WhichResult * NumElts / 2;
5181     for (unsigned j = 0; j < NumElts; j += 2) {
5182       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5183           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5184         return false;
5185       Idx += 1;
5186     }
5187   }
5188
5189   if (M.size() == NumElts*2)
5190     WhichResult = 0;
5191
5192   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5193   if (VT.is64BitVector() && EltSz == 32)
5194     return false;
5195
5196   return true;
5197 }
5198
5199 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5200 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5201 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5202 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5203   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5204   if (EltSz == 64)
5205     return false;
5206
5207   unsigned NumElts = VT.getVectorNumElements();
5208   if (M.size() != NumElts && M.size() != NumElts*2)
5209     return false;
5210
5211   for (unsigned i = 0; i < M.size(); i += NumElts) {
5212     WhichResult = M[i] == 0 ? 0 : 1;
5213     unsigned Idx = WhichResult * NumElts / 2;
5214     for (unsigned j = 0; j < NumElts; j += 2) {
5215       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5216           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5217         return false;
5218       Idx += 1;
5219     }
5220   }
5221
5222   if (M.size() == NumElts*2)
5223     WhichResult = 0;
5224
5225   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5226   if (VT.is64BitVector() && EltSz == 32)
5227     return false;
5228
5229   return true;
5230 }
5231
5232 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5233 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5234 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5235                                            unsigned &WhichResult,
5236                                            bool &isV_UNDEF) {
5237   isV_UNDEF = false;
5238   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5239     return ARMISD::VTRN;
5240   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5241     return ARMISD::VUZP;
5242   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5243     return ARMISD::VZIP;
5244
5245   isV_UNDEF = true;
5246   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5247     return ARMISD::VTRN;
5248   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5249     return ARMISD::VUZP;
5250   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5251     return ARMISD::VZIP;
5252
5253   return 0;
5254 }
5255
5256 /// \return true if this is a reverse operation on an vector.
5257 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5258   unsigned NumElts = VT.getVectorNumElements();
5259   // Make sure the mask has the right size.
5260   if (NumElts != M.size())
5261       return false;
5262
5263   // Look for <15, ..., 3, -1, 1, 0>.
5264   for (unsigned i = 0; i != NumElts; ++i)
5265     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5266       return false;
5267
5268   return true;
5269 }
5270
5271 // If N is an integer constant that can be moved into a register in one
5272 // instruction, return an SDValue of such a constant (will become a MOV
5273 // instruction).  Otherwise return null.
5274 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5275                                      const ARMSubtarget *ST, SDLoc dl) {
5276   uint64_t Val;
5277   if (!isa<ConstantSDNode>(N))
5278     return SDValue();
5279   Val = cast<ConstantSDNode>(N)->getZExtValue();
5280
5281   if (ST->isThumb1Only()) {
5282     if (Val <= 255 || ~Val <= 255)
5283       return DAG.getConstant(Val, dl, MVT::i32);
5284   } else {
5285     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5286       return DAG.getConstant(Val, dl, MVT::i32);
5287   }
5288   return SDValue();
5289 }
5290
5291 // If this is a case we can't handle, return null and let the default
5292 // expansion code take care of it.
5293 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5294                                              const ARMSubtarget *ST) const {
5295   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5296   SDLoc dl(Op);
5297   EVT VT = Op.getValueType();
5298
5299   APInt SplatBits, SplatUndef;
5300   unsigned SplatBitSize;
5301   bool HasAnyUndefs;
5302   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5303     if (SplatBitSize <= 64) {
5304       // Check if an immediate VMOV works.
5305       EVT VmovVT;
5306       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5307                                       SplatUndef.getZExtValue(), SplatBitSize,
5308                                       DAG, dl, VmovVT, VT.is128BitVector(),
5309                                       VMOVModImm);
5310       if (Val.getNode()) {
5311         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5312         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5313       }
5314
5315       // Try an immediate VMVN.
5316       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5317       Val = isNEONModifiedImm(NegatedImm,
5318                                       SplatUndef.getZExtValue(), SplatBitSize,
5319                                       DAG, dl, VmovVT, VT.is128BitVector(),
5320                                       VMVNModImm);
5321       if (Val.getNode()) {
5322         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5323         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5324       }
5325
5326       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5327       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5328         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5329         if (ImmVal != -1) {
5330           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5331           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5332         }
5333       }
5334     }
5335   }
5336
5337   // Scan through the operands to see if only one value is used.
5338   //
5339   // As an optimisation, even if more than one value is used it may be more
5340   // profitable to splat with one value then change some lanes.
5341   //
5342   // Heuristically we decide to do this if the vector has a "dominant" value,
5343   // defined as splatted to more than half of the lanes.
5344   unsigned NumElts = VT.getVectorNumElements();
5345   bool isOnlyLowElement = true;
5346   bool usesOnlyOneValue = true;
5347   bool hasDominantValue = false;
5348   bool isConstant = true;
5349
5350   // Map of the number of times a particular SDValue appears in the
5351   // element list.
5352   DenseMap<SDValue, unsigned> ValueCounts;
5353   SDValue Value;
5354   for (unsigned i = 0; i < NumElts; ++i) {
5355     SDValue V = Op.getOperand(i);
5356     if (V.getOpcode() == ISD::UNDEF)
5357       continue;
5358     if (i > 0)
5359       isOnlyLowElement = false;
5360     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5361       isConstant = false;
5362
5363     ValueCounts.insert(std::make_pair(V, 0));
5364     unsigned &Count = ValueCounts[V];
5365
5366     // Is this value dominant? (takes up more than half of the lanes)
5367     if (++Count > (NumElts / 2)) {
5368       hasDominantValue = true;
5369       Value = V;
5370     }
5371   }
5372   if (ValueCounts.size() != 1)
5373     usesOnlyOneValue = false;
5374   if (!Value.getNode() && ValueCounts.size() > 0)
5375     Value = ValueCounts.begin()->first;
5376
5377   if (ValueCounts.size() == 0)
5378     return DAG.getUNDEF(VT);
5379
5380   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5381   // Keep going if we are hitting this case.
5382   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5383     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5384
5385   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5386
5387   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5388   // i32 and try again.
5389   if (hasDominantValue && EltSize <= 32) {
5390     if (!isConstant) {
5391       SDValue N;
5392
5393       // If we are VDUPing a value that comes directly from a vector, that will
5394       // cause an unnecessary move to and from a GPR, where instead we could
5395       // just use VDUPLANE. We can only do this if the lane being extracted
5396       // is at a constant index, as the VDUP from lane instructions only have
5397       // constant-index forms.
5398       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5399           isa<ConstantSDNode>(Value->getOperand(1))) {
5400         // We need to create a new undef vector to use for the VDUPLANE if the
5401         // size of the vector from which we get the value is different than the
5402         // size of the vector that we need to create. We will insert the element
5403         // such that the register coalescer will remove unnecessary copies.
5404         if (VT != Value->getOperand(0).getValueType()) {
5405           ConstantSDNode *constIndex;
5406           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5407           assert(constIndex && "The index is not a constant!");
5408           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5409                              VT.getVectorNumElements();
5410           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5411                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5412                         Value, DAG.getConstant(index, dl, MVT::i32)),
5413                            DAG.getConstant(index, dl, MVT::i32));
5414         } else
5415           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5416                         Value->getOperand(0), Value->getOperand(1));
5417       } else
5418         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5419
5420       if (!usesOnlyOneValue) {
5421         // The dominant value was splatted as 'N', but we now have to insert
5422         // all differing elements.
5423         for (unsigned I = 0; I < NumElts; ++I) {
5424           if (Op.getOperand(I) == Value)
5425             continue;
5426           SmallVector<SDValue, 3> Ops;
5427           Ops.push_back(N);
5428           Ops.push_back(Op.getOperand(I));
5429           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5430           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5431         }
5432       }
5433       return N;
5434     }
5435     if (VT.getVectorElementType().isFloatingPoint()) {
5436       SmallVector<SDValue, 8> Ops;
5437       for (unsigned i = 0; i < NumElts; ++i)
5438         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5439                                   Op.getOperand(i)));
5440       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5441       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5442       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5443       if (Val.getNode())
5444         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5445     }
5446     if (usesOnlyOneValue) {
5447       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5448       if (isConstant && Val.getNode())
5449         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5450     }
5451   }
5452
5453   // If all elements are constants and the case above didn't get hit, fall back
5454   // to the default expansion, which will generate a load from the constant
5455   // pool.
5456   if (isConstant)
5457     return SDValue();
5458
5459   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5460   if (NumElts >= 4) {
5461     SDValue shuffle = ReconstructShuffle(Op, DAG);
5462     if (shuffle != SDValue())
5463       return shuffle;
5464   }
5465
5466   // Vectors with 32- or 64-bit elements can be built by directly assigning
5467   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5468   // will be legalized.
5469   if (EltSize >= 32) {
5470     // Do the expansion with floating-point types, since that is what the VFP
5471     // registers are defined to use, and since i64 is not legal.
5472     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5473     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5474     SmallVector<SDValue, 8> Ops;
5475     for (unsigned i = 0; i < NumElts; ++i)
5476       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5477     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5478     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5479   }
5480
5481   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5482   // know the default expansion would otherwise fall back on something even
5483   // worse. For a vector with one or two non-undef values, that's
5484   // scalar_to_vector for the elements followed by a shuffle (provided the
5485   // shuffle is valid for the target) and materialization element by element
5486   // on the stack followed by a load for everything else.
5487   if (!isConstant && !usesOnlyOneValue) {
5488     SDValue Vec = DAG.getUNDEF(VT);
5489     for (unsigned i = 0 ; i < NumElts; ++i) {
5490       SDValue V = Op.getOperand(i);
5491       if (V.getOpcode() == ISD::UNDEF)
5492         continue;
5493       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5494       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5495     }
5496     return Vec;
5497   }
5498
5499   return SDValue();
5500 }
5501
5502 /// getExtFactor - Determine the adjustment factor for the position when
5503 /// generating an "extract from vector registers" instruction.
5504 static unsigned getExtFactor(SDValue &V) {
5505   EVT EltType = V.getValueType().getVectorElementType();
5506   return EltType.getSizeInBits() / 8;
5507 }
5508
5509 // Gather data to see if the operation can be modelled as a
5510 // shuffle in combination with VEXTs.
5511 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5512                                               SelectionDAG &DAG) const {
5513   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5514   SDLoc dl(Op);
5515   EVT VT = Op.getValueType();
5516   unsigned NumElts = VT.getVectorNumElements();
5517
5518   struct ShuffleSourceInfo {
5519     SDValue Vec;
5520     unsigned MinElt;
5521     unsigned MaxElt;
5522
5523     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5524     // be compatible with the shuffle we intend to construct. As a result
5525     // ShuffleVec will be some sliding window into the original Vec.
5526     SDValue ShuffleVec;
5527
5528     // Code should guarantee that element i in Vec starts at element "WindowBase
5529     // + i * WindowScale in ShuffleVec".
5530     int WindowBase;
5531     int WindowScale;
5532
5533     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5534     ShuffleSourceInfo(SDValue Vec)
5535         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5536           WindowScale(1) {}
5537   };
5538
5539   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5540   // node.
5541   SmallVector<ShuffleSourceInfo, 2> Sources;
5542   for (unsigned i = 0; i < NumElts; ++i) {
5543     SDValue V = Op.getOperand(i);
5544     if (V.getOpcode() == ISD::UNDEF)
5545       continue;
5546     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5547       // A shuffle can only come from building a vector from various
5548       // elements of other vectors.
5549       return SDValue();
5550     }
5551
5552     // Add this element source to the list if it's not already there.
5553     SDValue SourceVec = V.getOperand(0);
5554     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5555     if (Source == Sources.end())
5556       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5557
5558     // Update the minimum and maximum lane number seen.
5559     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5560     Source->MinElt = std::min(Source->MinElt, EltNo);
5561     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5562   }
5563
5564   // Currently only do something sane when at most two source vectors
5565   // are involved.
5566   if (Sources.size() > 2)
5567     return SDValue();
5568
5569   // Find out the smallest element size among result and two sources, and use
5570   // it as element size to build the shuffle_vector.
5571   EVT SmallestEltTy = VT.getVectorElementType();
5572   for (auto &Source : Sources) {
5573     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5574     if (SrcEltTy.bitsLT(SmallestEltTy))
5575       SmallestEltTy = SrcEltTy;
5576   }
5577   unsigned ResMultiplier =
5578       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5579   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5580   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5581
5582   // If the source vector is too wide or too narrow, we may nevertheless be able
5583   // to construct a compatible shuffle either by concatenating it with UNDEF or
5584   // extracting a suitable range of elements.
5585   for (auto &Src : Sources) {
5586     EVT SrcVT = Src.ShuffleVec.getValueType();
5587
5588     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5589       continue;
5590
5591     // This stage of the search produces a source with the same element type as
5592     // the original, but with a total width matching the BUILD_VECTOR output.
5593     EVT EltVT = SrcVT.getVectorElementType();
5594     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5595     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5596
5597     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5598       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5599         return SDValue();
5600       // We can pad out the smaller vector for free, so if it's part of a
5601       // shuffle...
5602       Src.ShuffleVec =
5603           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5604                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5605       continue;
5606     }
5607
5608     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5609       return SDValue();
5610
5611     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5612       // Span too large for a VEXT to cope
5613       return SDValue();
5614     }
5615
5616     if (Src.MinElt >= NumSrcElts) {
5617       // The extraction can just take the second half
5618       Src.ShuffleVec =
5619           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5620                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5621       Src.WindowBase = -NumSrcElts;
5622     } else if (Src.MaxElt < NumSrcElts) {
5623       // The extraction can just take the first half
5624       Src.ShuffleVec =
5625           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5626                       DAG.getConstant(0, dl, MVT::i32));
5627     } else {
5628       // An actual VEXT is needed
5629       SDValue VEXTSrc1 =
5630           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5631                       DAG.getConstant(0, dl, MVT::i32));
5632       SDValue VEXTSrc2 =
5633           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5634                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5635       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5636
5637       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5638                                    VEXTSrc2,
5639                                    DAG.getConstant(Imm, dl, MVT::i32));
5640       Src.WindowBase = -Src.MinElt;
5641     }
5642   }
5643
5644   // Another possible incompatibility occurs from the vector element types. We
5645   // can fix this by bitcasting the source vectors to the same type we intend
5646   // for the shuffle.
5647   for (auto &Src : Sources) {
5648     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5649     if (SrcEltTy == SmallestEltTy)
5650       continue;
5651     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5652     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5653     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5654     Src.WindowBase *= Src.WindowScale;
5655   }
5656
5657   // Final sanity check before we try to actually produce a shuffle.
5658   DEBUG(
5659     for (auto Src : Sources)
5660       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5661   );
5662
5663   // The stars all align, our next step is to produce the mask for the shuffle.
5664   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5665   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5666   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5667     SDValue Entry = Op.getOperand(i);
5668     if (Entry.getOpcode() == ISD::UNDEF)
5669       continue;
5670
5671     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5672     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5673
5674     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5675     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5676     // segment.
5677     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5678     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5679                                VT.getVectorElementType().getSizeInBits());
5680     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5681
5682     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5683     // starting at the appropriate offset.
5684     int *LaneMask = &Mask[i * ResMultiplier];
5685
5686     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5687     ExtractBase += NumElts * (Src - Sources.begin());
5688     for (int j = 0; j < LanesDefined; ++j)
5689       LaneMask[j] = ExtractBase + j;
5690   }
5691
5692   // Final check before we try to produce nonsense...
5693   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5694     return SDValue();
5695
5696   // We can't handle more than two sources. This should have already
5697   // been checked before this point.
5698   assert(Sources.size() <= 2 && "Too many sources!");
5699
5700   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5701   for (unsigned i = 0; i < Sources.size(); ++i)
5702     ShuffleOps[i] = Sources[i].ShuffleVec;
5703
5704   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5705                                          ShuffleOps[1], &Mask[0]);
5706   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5707 }
5708
5709 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5710 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5711 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5712 /// are assumed to be legal.
5713 bool
5714 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5715                                       EVT VT) const {
5716   if (VT.getVectorNumElements() == 4 &&
5717       (VT.is128BitVector() || VT.is64BitVector())) {
5718     unsigned PFIndexes[4];
5719     for (unsigned i = 0; i != 4; ++i) {
5720       if (M[i] < 0)
5721         PFIndexes[i] = 8;
5722       else
5723         PFIndexes[i] = M[i];
5724     }
5725
5726     // Compute the index in the perfect shuffle table.
5727     unsigned PFTableIndex =
5728       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5729     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5730     unsigned Cost = (PFEntry >> 30);
5731
5732     if (Cost <= 4)
5733       return true;
5734   }
5735
5736   bool ReverseVEXT, isV_UNDEF;
5737   unsigned Imm, WhichResult;
5738
5739   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5740   return (EltSize >= 32 ||
5741           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5742           isVREVMask(M, VT, 64) ||
5743           isVREVMask(M, VT, 32) ||
5744           isVREVMask(M, VT, 16) ||
5745           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5746           isVTBLMask(M, VT) ||
5747           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5748           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5749 }
5750
5751 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5752 /// the specified operations to build the shuffle.
5753 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5754                                       SDValue RHS, SelectionDAG &DAG,
5755                                       SDLoc dl) {
5756   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5757   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5758   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5759
5760   enum {
5761     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5762     OP_VREV,
5763     OP_VDUP0,
5764     OP_VDUP1,
5765     OP_VDUP2,
5766     OP_VDUP3,
5767     OP_VEXT1,
5768     OP_VEXT2,
5769     OP_VEXT3,
5770     OP_VUZPL, // VUZP, left result
5771     OP_VUZPR, // VUZP, right result
5772     OP_VZIPL, // VZIP, left result
5773     OP_VZIPR, // VZIP, right result
5774     OP_VTRNL, // VTRN, left result
5775     OP_VTRNR  // VTRN, right result
5776   };
5777
5778   if (OpNum == OP_COPY) {
5779     if (LHSID == (1*9+2)*9+3) return LHS;
5780     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5781     return RHS;
5782   }
5783
5784   SDValue OpLHS, OpRHS;
5785   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5786   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5787   EVT VT = OpLHS.getValueType();
5788
5789   switch (OpNum) {
5790   default: llvm_unreachable("Unknown shuffle opcode!");
5791   case OP_VREV:
5792     // VREV divides the vector in half and swaps within the half.
5793     if (VT.getVectorElementType() == MVT::i32 ||
5794         VT.getVectorElementType() == MVT::f32)
5795       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5796     // vrev <4 x i16> -> VREV32
5797     if (VT.getVectorElementType() == MVT::i16)
5798       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5799     // vrev <4 x i8> -> VREV16
5800     assert(VT.getVectorElementType() == MVT::i8);
5801     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5802   case OP_VDUP0:
5803   case OP_VDUP1:
5804   case OP_VDUP2:
5805   case OP_VDUP3:
5806     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5807                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5808   case OP_VEXT1:
5809   case OP_VEXT2:
5810   case OP_VEXT3:
5811     return DAG.getNode(ARMISD::VEXT, dl, VT,
5812                        OpLHS, OpRHS,
5813                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5814   case OP_VUZPL:
5815   case OP_VUZPR:
5816     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5817                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5818   case OP_VZIPL:
5819   case OP_VZIPR:
5820     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5821                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5822   case OP_VTRNL:
5823   case OP_VTRNR:
5824     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5825                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5826   }
5827 }
5828
5829 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5830                                        ArrayRef<int> ShuffleMask,
5831                                        SelectionDAG &DAG) {
5832   // Check to see if we can use the VTBL instruction.
5833   SDValue V1 = Op.getOperand(0);
5834   SDValue V2 = Op.getOperand(1);
5835   SDLoc DL(Op);
5836
5837   SmallVector<SDValue, 8> VTBLMask;
5838   for (ArrayRef<int>::iterator
5839          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5840     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5841
5842   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5843     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5844                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5845
5846   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5847                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5848 }
5849
5850 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5851                                                       SelectionDAG &DAG) {
5852   SDLoc DL(Op);
5853   SDValue OpLHS = Op.getOperand(0);
5854   EVT VT = OpLHS.getValueType();
5855
5856   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5857          "Expect an v8i16/v16i8 type");
5858   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5859   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5860   // extract the first 8 bytes into the top double word and the last 8 bytes
5861   // into the bottom double word. The v8i16 case is similar.
5862   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5863   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5864                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5865 }
5866
5867 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5868   SDValue V1 = Op.getOperand(0);
5869   SDValue V2 = Op.getOperand(1);
5870   SDLoc dl(Op);
5871   EVT VT = Op.getValueType();
5872   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5873
5874   // Convert shuffles that are directly supported on NEON to target-specific
5875   // DAG nodes, instead of keeping them as shuffles and matching them again
5876   // during code selection.  This is more efficient and avoids the possibility
5877   // of inconsistencies between legalization and selection.
5878   // FIXME: floating-point vectors should be canonicalized to integer vectors
5879   // of the same time so that they get CSEd properly.
5880   ArrayRef<int> ShuffleMask = SVN->getMask();
5881
5882   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5883   if (EltSize <= 32) {
5884     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5885       int Lane = SVN->getSplatIndex();
5886       // If this is undef splat, generate it via "just" vdup, if possible.
5887       if (Lane == -1) Lane = 0;
5888
5889       // Test if V1 is a SCALAR_TO_VECTOR.
5890       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5891         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5892       }
5893       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5894       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5895       // reaches it).
5896       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5897           !isa<ConstantSDNode>(V1.getOperand(0))) {
5898         bool IsScalarToVector = true;
5899         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5900           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5901             IsScalarToVector = false;
5902             break;
5903           }
5904         if (IsScalarToVector)
5905           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5906       }
5907       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5908                          DAG.getConstant(Lane, dl, MVT::i32));
5909     }
5910
5911     bool ReverseVEXT;
5912     unsigned Imm;
5913     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5914       if (ReverseVEXT)
5915         std::swap(V1, V2);
5916       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5917                          DAG.getConstant(Imm, dl, MVT::i32));
5918     }
5919
5920     if (isVREVMask(ShuffleMask, VT, 64))
5921       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5922     if (isVREVMask(ShuffleMask, VT, 32))
5923       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5924     if (isVREVMask(ShuffleMask, VT, 16))
5925       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5926
5927     if (V2->getOpcode() == ISD::UNDEF &&
5928         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5929       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5930                          DAG.getConstant(Imm, dl, MVT::i32));
5931     }
5932
5933     // Check for Neon shuffles that modify both input vectors in place.
5934     // If both results are used, i.e., if there are two shuffles with the same
5935     // source operands and with masks corresponding to both results of one of
5936     // these operations, DAG memoization will ensure that a single node is
5937     // used for both shuffles.
5938     unsigned WhichResult;
5939     bool isV_UNDEF;
5940     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5941             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5942       if (isV_UNDEF)
5943         V2 = V1;
5944       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5945           .getValue(WhichResult);
5946     }
5947
5948     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5949     // shuffles that produce a result larger than their operands with:
5950     //   shuffle(concat(v1, undef), concat(v2, undef))
5951     // ->
5952     //   shuffle(concat(v1, v2), undef)
5953     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5954     //
5955     // This is useful in the general case, but there are special cases where
5956     // native shuffles produce larger results: the two-result ops.
5957     //
5958     // Look through the concat when lowering them:
5959     //   shuffle(concat(v1, v2), undef)
5960     // ->
5961     //   concat(VZIP(v1, v2):0, :1)
5962     //
5963     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5964         V2->getOpcode() == ISD::UNDEF) {
5965       SDValue SubV1 = V1->getOperand(0);
5966       SDValue SubV2 = V1->getOperand(1);
5967       EVT SubVT = SubV1.getValueType();
5968
5969       // We expect these to have been canonicalized to -1.
5970       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5971         return i < (int)VT.getVectorNumElements();
5972       }) && "Unexpected shuffle index into UNDEF operand!");
5973
5974       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5975               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5976         if (isV_UNDEF)
5977           SubV2 = SubV1;
5978         assert((WhichResult == 0) &&
5979                "In-place shuffle of concat can only have one result!");
5980         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5981                                   SubV1, SubV2);
5982         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5983                            Res.getValue(1));
5984       }
5985     }
5986   }
5987
5988   // If the shuffle is not directly supported and it has 4 elements, use
5989   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5990   unsigned NumElts = VT.getVectorNumElements();
5991   if (NumElts == 4) {
5992     unsigned PFIndexes[4];
5993     for (unsigned i = 0; i != 4; ++i) {
5994       if (ShuffleMask[i] < 0)
5995         PFIndexes[i] = 8;
5996       else
5997         PFIndexes[i] = ShuffleMask[i];
5998     }
5999
6000     // Compute the index in the perfect shuffle table.
6001     unsigned PFTableIndex =
6002       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6003     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6004     unsigned Cost = (PFEntry >> 30);
6005
6006     if (Cost <= 4)
6007       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6008   }
6009
6010   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6011   if (EltSize >= 32) {
6012     // Do the expansion with floating-point types, since that is what the VFP
6013     // registers are defined to use, and since i64 is not legal.
6014     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6015     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6016     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6017     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6018     SmallVector<SDValue, 8> Ops;
6019     for (unsigned i = 0; i < NumElts; ++i) {
6020       if (ShuffleMask[i] < 0)
6021         Ops.push_back(DAG.getUNDEF(EltVT));
6022       else
6023         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6024                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6025                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6026                                                   dl, MVT::i32)));
6027     }
6028     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6029     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6030   }
6031
6032   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6033     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6034
6035   if (VT == MVT::v8i8) {
6036     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6037     if (NewOp.getNode())
6038       return NewOp;
6039   }
6040
6041   return SDValue();
6042 }
6043
6044 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6045   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6046   SDValue Lane = Op.getOperand(2);
6047   if (!isa<ConstantSDNode>(Lane))
6048     return SDValue();
6049
6050   return Op;
6051 }
6052
6053 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6054   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6055   SDValue Lane = Op.getOperand(1);
6056   if (!isa<ConstantSDNode>(Lane))
6057     return SDValue();
6058
6059   SDValue Vec = Op.getOperand(0);
6060   if (Op.getValueType() == MVT::i32 &&
6061       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6062     SDLoc dl(Op);
6063     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6064   }
6065
6066   return Op;
6067 }
6068
6069 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6070   // The only time a CONCAT_VECTORS operation can have legal types is when
6071   // two 64-bit vectors are concatenated to a 128-bit vector.
6072   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6073          "unexpected CONCAT_VECTORS");
6074   SDLoc dl(Op);
6075   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6076   SDValue Op0 = Op.getOperand(0);
6077   SDValue Op1 = Op.getOperand(1);
6078   if (Op0.getOpcode() != ISD::UNDEF)
6079     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6080                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6081                       DAG.getIntPtrConstant(0, dl));
6082   if (Op1.getOpcode() != ISD::UNDEF)
6083     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6084                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6085                       DAG.getIntPtrConstant(1, dl));
6086   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6087 }
6088
6089 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6090 /// element has been zero/sign-extended, depending on the isSigned parameter,
6091 /// from an integer type half its size.
6092 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6093                                    bool isSigned) {
6094   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6095   EVT VT = N->getValueType(0);
6096   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6097     SDNode *BVN = N->getOperand(0).getNode();
6098     if (BVN->getValueType(0) != MVT::v4i32 ||
6099         BVN->getOpcode() != ISD::BUILD_VECTOR)
6100       return false;
6101     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6102     unsigned HiElt = 1 - LoElt;
6103     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6104     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6105     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6106     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6107     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6108       return false;
6109     if (isSigned) {
6110       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6111           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6112         return true;
6113     } else {
6114       if (Hi0->isNullValue() && Hi1->isNullValue())
6115         return true;
6116     }
6117     return false;
6118   }
6119
6120   if (N->getOpcode() != ISD::BUILD_VECTOR)
6121     return false;
6122
6123   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6124     SDNode *Elt = N->getOperand(i).getNode();
6125     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6126       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6127       unsigned HalfSize = EltSize / 2;
6128       if (isSigned) {
6129         if (!isIntN(HalfSize, C->getSExtValue()))
6130           return false;
6131       } else {
6132         if (!isUIntN(HalfSize, C->getZExtValue()))
6133           return false;
6134       }
6135       continue;
6136     }
6137     return false;
6138   }
6139
6140   return true;
6141 }
6142
6143 /// isSignExtended - Check if a node is a vector value that is sign-extended
6144 /// or a constant BUILD_VECTOR with sign-extended elements.
6145 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6146   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6147     return true;
6148   if (isExtendedBUILD_VECTOR(N, DAG, true))
6149     return true;
6150   return false;
6151 }
6152
6153 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6154 /// or a constant BUILD_VECTOR with zero-extended elements.
6155 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6156   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6157     return true;
6158   if (isExtendedBUILD_VECTOR(N, DAG, false))
6159     return true;
6160   return false;
6161 }
6162
6163 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6164   if (OrigVT.getSizeInBits() >= 64)
6165     return OrigVT;
6166
6167   assert(OrigVT.isSimple() && "Expecting a simple value type");
6168
6169   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6170   switch (OrigSimpleTy) {
6171   default: llvm_unreachable("Unexpected Vector Type");
6172   case MVT::v2i8:
6173   case MVT::v2i16:
6174      return MVT::v2i32;
6175   case MVT::v4i8:
6176     return  MVT::v4i16;
6177   }
6178 }
6179
6180 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6181 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6182 /// We insert the required extension here to get the vector to fill a D register.
6183 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6184                                             const EVT &OrigTy,
6185                                             const EVT &ExtTy,
6186                                             unsigned ExtOpcode) {
6187   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6188   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6189   // 64-bits we need to insert a new extension so that it will be 64-bits.
6190   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6191   if (OrigTy.getSizeInBits() >= 64)
6192     return N;
6193
6194   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6195   EVT NewVT = getExtensionTo64Bits(OrigTy);
6196
6197   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6198 }
6199
6200 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6201 /// does not do any sign/zero extension. If the original vector is less
6202 /// than 64 bits, an appropriate extension will be added after the load to
6203 /// reach a total size of 64 bits. We have to add the extension separately
6204 /// because ARM does not have a sign/zero extending load for vectors.
6205 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6206   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6207
6208   // The load already has the right type.
6209   if (ExtendedTy == LD->getMemoryVT())
6210     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6211                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6212                 LD->isNonTemporal(), LD->isInvariant(),
6213                 LD->getAlignment());
6214
6215   // We need to create a zextload/sextload. We cannot just create a load
6216   // followed by a zext/zext node because LowerMUL is also run during normal
6217   // operation legalization where we can't create illegal types.
6218   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6219                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6220                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6221                         LD->isNonTemporal(), LD->getAlignment());
6222 }
6223
6224 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6225 /// extending load, or BUILD_VECTOR with extended elements, return the
6226 /// unextended value. The unextended vector should be 64 bits so that it can
6227 /// be used as an operand to a VMULL instruction. If the original vector size
6228 /// before extension is less than 64 bits we add a an extension to resize
6229 /// the vector to 64 bits.
6230 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6231   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6232     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6233                                         N->getOperand(0)->getValueType(0),
6234                                         N->getValueType(0),
6235                                         N->getOpcode());
6236
6237   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6238     return SkipLoadExtensionForVMULL(LD, DAG);
6239
6240   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6241   // have been legalized as a BITCAST from v4i32.
6242   if (N->getOpcode() == ISD::BITCAST) {
6243     SDNode *BVN = N->getOperand(0).getNode();
6244     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6245            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6246     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6247     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6248                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6249   }
6250   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6251   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6252   EVT VT = N->getValueType(0);
6253   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6254   unsigned NumElts = VT.getVectorNumElements();
6255   MVT TruncVT = MVT::getIntegerVT(EltSize);
6256   SmallVector<SDValue, 8> Ops;
6257   SDLoc dl(N);
6258   for (unsigned i = 0; i != NumElts; ++i) {
6259     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6260     const APInt &CInt = C->getAPIntValue();
6261     // Element types smaller than 32 bits are not legal, so use i32 elements.
6262     // The values are implicitly truncated so sext vs. zext doesn't matter.
6263     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6264   }
6265   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6266                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6267 }
6268
6269 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6270   unsigned Opcode = N->getOpcode();
6271   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6272     SDNode *N0 = N->getOperand(0).getNode();
6273     SDNode *N1 = N->getOperand(1).getNode();
6274     return N0->hasOneUse() && N1->hasOneUse() &&
6275       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6276   }
6277   return false;
6278 }
6279
6280 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6281   unsigned Opcode = N->getOpcode();
6282   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6283     SDNode *N0 = N->getOperand(0).getNode();
6284     SDNode *N1 = N->getOperand(1).getNode();
6285     return N0->hasOneUse() && N1->hasOneUse() &&
6286       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6287   }
6288   return false;
6289 }
6290
6291 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6292   // Multiplications are only custom-lowered for 128-bit vectors so that
6293   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6294   EVT VT = Op.getValueType();
6295   assert(VT.is128BitVector() && VT.isInteger() &&
6296          "unexpected type for custom-lowering ISD::MUL");
6297   SDNode *N0 = Op.getOperand(0).getNode();
6298   SDNode *N1 = Op.getOperand(1).getNode();
6299   unsigned NewOpc = 0;
6300   bool isMLA = false;
6301   bool isN0SExt = isSignExtended(N0, DAG);
6302   bool isN1SExt = isSignExtended(N1, DAG);
6303   if (isN0SExt && isN1SExt)
6304     NewOpc = ARMISD::VMULLs;
6305   else {
6306     bool isN0ZExt = isZeroExtended(N0, DAG);
6307     bool isN1ZExt = isZeroExtended(N1, DAG);
6308     if (isN0ZExt && isN1ZExt)
6309       NewOpc = ARMISD::VMULLu;
6310     else if (isN1SExt || isN1ZExt) {
6311       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6312       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6313       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6314         NewOpc = ARMISD::VMULLs;
6315         isMLA = true;
6316       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6317         NewOpc = ARMISD::VMULLu;
6318         isMLA = true;
6319       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6320         std::swap(N0, N1);
6321         NewOpc = ARMISD::VMULLu;
6322         isMLA = true;
6323       }
6324     }
6325
6326     if (!NewOpc) {
6327       if (VT == MVT::v2i64)
6328         // Fall through to expand this.  It is not legal.
6329         return SDValue();
6330       else
6331         // Other vector multiplications are legal.
6332         return Op;
6333     }
6334   }
6335
6336   // Legalize to a VMULL instruction.
6337   SDLoc DL(Op);
6338   SDValue Op0;
6339   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6340   if (!isMLA) {
6341     Op0 = SkipExtensionForVMULL(N0, DAG);
6342     assert(Op0.getValueType().is64BitVector() &&
6343            Op1.getValueType().is64BitVector() &&
6344            "unexpected types for extended operands to VMULL");
6345     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6346   }
6347
6348   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6349   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6350   //   vmull q0, d4, d6
6351   //   vmlal q0, d5, d6
6352   // is faster than
6353   //   vaddl q0, d4, d5
6354   //   vmovl q1, d6
6355   //   vmul  q0, q0, q1
6356   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6357   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6358   EVT Op1VT = Op1.getValueType();
6359   return DAG.getNode(N0->getOpcode(), DL, VT,
6360                      DAG.getNode(NewOpc, DL, VT,
6361                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6362                      DAG.getNode(NewOpc, DL, VT,
6363                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6364 }
6365
6366 static SDValue
6367 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6368   // Convert to float
6369   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6370   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6371   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6372   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6373   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6374   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6375   // Get reciprocal estimate.
6376   // float4 recip = vrecpeq_f32(yf);
6377   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6378                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6379                    Y);
6380   // Because char has a smaller range than uchar, we can actually get away
6381   // without any newton steps.  This requires that we use a weird bias
6382   // of 0xb000, however (again, this has been exhaustively tested).
6383   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6384   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6385   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6386   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6387   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6388   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6389   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6390   // Convert back to short.
6391   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6392   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6393   return X;
6394 }
6395
6396 static SDValue
6397 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6398   SDValue N2;
6399   // Convert to float.
6400   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6401   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6402   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6403   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6404   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6405   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6406
6407   // Use reciprocal estimate and one refinement step.
6408   // float4 recip = vrecpeq_f32(yf);
6409   // recip *= vrecpsq_f32(yf, recip);
6410   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6411                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6412                    N1);
6413   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6414                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6415                    N1, N2);
6416   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6417   // Because short has a smaller range than ushort, we can actually get away
6418   // with only a single newton step.  This requires that we use a weird bias
6419   // of 89, however (again, this has been exhaustively tested).
6420   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6421   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6422   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6423   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6424   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6425   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6426   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6427   // Convert back to integer and return.
6428   // return vmovn_s32(vcvt_s32_f32(result));
6429   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6430   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6431   return N0;
6432 }
6433
6434 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6435   EVT VT = Op.getValueType();
6436   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6437          "unexpected type for custom-lowering ISD::SDIV");
6438
6439   SDLoc dl(Op);
6440   SDValue N0 = Op.getOperand(0);
6441   SDValue N1 = Op.getOperand(1);
6442   SDValue N2, N3;
6443
6444   if (VT == MVT::v8i8) {
6445     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6446     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6447
6448     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6449                      DAG.getIntPtrConstant(4, dl));
6450     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6451                      DAG.getIntPtrConstant(4, dl));
6452     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6453                      DAG.getIntPtrConstant(0, dl));
6454     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6455                      DAG.getIntPtrConstant(0, dl));
6456
6457     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6458     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6459
6460     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6461     N0 = LowerCONCAT_VECTORS(N0, DAG);
6462
6463     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6464     return N0;
6465   }
6466   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6467 }
6468
6469 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6470   EVT VT = Op.getValueType();
6471   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6472          "unexpected type for custom-lowering ISD::UDIV");
6473
6474   SDLoc dl(Op);
6475   SDValue N0 = Op.getOperand(0);
6476   SDValue N1 = Op.getOperand(1);
6477   SDValue N2, N3;
6478
6479   if (VT == MVT::v8i8) {
6480     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6481     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6482
6483     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6484                      DAG.getIntPtrConstant(4, dl));
6485     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6486                      DAG.getIntPtrConstant(4, dl));
6487     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6488                      DAG.getIntPtrConstant(0, dl));
6489     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6490                      DAG.getIntPtrConstant(0, dl));
6491
6492     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6493     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6494
6495     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6496     N0 = LowerCONCAT_VECTORS(N0, DAG);
6497
6498     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6499                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6500                                      MVT::i32),
6501                      N0);
6502     return N0;
6503   }
6504
6505   // v4i16 sdiv ... Convert to float.
6506   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6507   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6508   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6509   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6510   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6511   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6512
6513   // Use reciprocal estimate and two refinement steps.
6514   // float4 recip = vrecpeq_f32(yf);
6515   // recip *= vrecpsq_f32(yf, recip);
6516   // recip *= vrecpsq_f32(yf, recip);
6517   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6518                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6519                    BN1);
6520   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6521                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6522                    BN1, N2);
6523   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6524   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6525                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6526                    BN1, N2);
6527   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6528   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6529   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6530   // and that it will never cause us to return an answer too large).
6531   // float4 result = as_float4(as_int4(xf*recip) + 2);
6532   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6533   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6534   N1 = DAG.getConstant(2, dl, MVT::i32);
6535   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6536   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6537   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6538   // Convert back to integer and return.
6539   // return vmovn_u32(vcvt_s32_f32(result));
6540   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6541   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6542   return N0;
6543 }
6544
6545 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6546   EVT VT = Op.getNode()->getValueType(0);
6547   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6548
6549   unsigned Opc;
6550   bool ExtraOp = false;
6551   switch (Op.getOpcode()) {
6552   default: llvm_unreachable("Invalid code");
6553   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6554   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6555   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6556   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6557   }
6558
6559   if (!ExtraOp)
6560     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6561                        Op.getOperand(1));
6562   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6563                      Op.getOperand(1), Op.getOperand(2));
6564 }
6565
6566 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6567   assert(Subtarget->isTargetDarwin());
6568
6569   // For iOS, we want to call an alternative entry point: __sincos_stret,
6570   // return values are passed via sret.
6571   SDLoc dl(Op);
6572   SDValue Arg = Op.getOperand(0);
6573   EVT ArgVT = Arg.getValueType();
6574   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6575   auto PtrVT = getPointerTy(DAG.getDataLayout());
6576
6577   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6578
6579   // Pair of floats / doubles used to pass the result.
6580   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6581
6582   // Create stack object for sret.
6583   auto &DL = DAG.getDataLayout();
6584   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6585   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6586   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6587   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6588
6589   ArgListTy Args;
6590   ArgListEntry Entry;
6591
6592   Entry.Node = SRet;
6593   Entry.Ty = RetTy->getPointerTo();
6594   Entry.isSExt = false;
6595   Entry.isZExt = false;
6596   Entry.isSRet = true;
6597   Args.push_back(Entry);
6598
6599   Entry.Node = Arg;
6600   Entry.Ty = ArgTy;
6601   Entry.isSExt = false;
6602   Entry.isZExt = false;
6603   Args.push_back(Entry);
6604
6605   const char *LibcallName  = (ArgVT == MVT::f64)
6606   ? "__sincos_stret" : "__sincosf_stret";
6607   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6608
6609   TargetLowering::CallLoweringInfo CLI(DAG);
6610   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6611     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6612                std::move(Args), 0)
6613     .setDiscardResult();
6614
6615   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6616
6617   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6618                                 MachinePointerInfo(), false, false, false, 0);
6619
6620   // Address of cos field.
6621   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6622                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6623   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6624                                 MachinePointerInfo(), false, false, false, 0);
6625
6626   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6627   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6628                      LoadSin.getValue(0), LoadCos.getValue(0));
6629 }
6630
6631 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6632   // Monotonic load/store is legal for all targets
6633   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6634     return Op;
6635
6636   // Acquire/Release load/store is not legal for targets without a
6637   // dmb or equivalent available.
6638   return SDValue();
6639 }
6640
6641 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6642                                     SmallVectorImpl<SDValue> &Results,
6643                                     SelectionDAG &DAG,
6644                                     const ARMSubtarget *Subtarget) {
6645   SDLoc DL(N);
6646   SDValue Cycles32, OutChain;
6647
6648   if (Subtarget->hasPerfMon()) {
6649     // Under Power Management extensions, the cycle-count is:
6650     //    mrc p15, #0, <Rt>, c9, c13, #0
6651     SDValue Ops[] = { N->getOperand(0), // Chain
6652                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6653                       DAG.getConstant(15, DL, MVT::i32),
6654                       DAG.getConstant(0, DL, MVT::i32),
6655                       DAG.getConstant(9, DL, MVT::i32),
6656                       DAG.getConstant(13, DL, MVT::i32),
6657                       DAG.getConstant(0, DL, MVT::i32)
6658     };
6659
6660     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6661                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6662     OutChain = Cycles32.getValue(1);
6663   } else {
6664     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6665     // there are older ARM CPUs that have implementation-specific ways of
6666     // obtaining this information (FIXME!).
6667     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6668     OutChain = DAG.getEntryNode();
6669   }
6670
6671
6672   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6673                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6674   Results.push_back(Cycles64);
6675   Results.push_back(OutChain);
6676 }
6677
6678 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6679   switch (Op.getOpcode()) {
6680   default: llvm_unreachable("Don't know how to custom lower this!");
6681   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6682   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6683   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6684   case ISD::GlobalAddress:
6685     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6686     default: llvm_unreachable("unknown object format");
6687     case Triple::COFF:
6688       return LowerGlobalAddressWindows(Op, DAG);
6689     case Triple::ELF:
6690       return LowerGlobalAddressELF(Op, DAG);
6691     case Triple::MachO:
6692       return LowerGlobalAddressDarwin(Op, DAG);
6693     }
6694   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6695   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6696   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6697   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6698   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6699   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6700   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6701   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6702   case ISD::SINT_TO_FP:
6703   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6704   case ISD::FP_TO_SINT:
6705   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6706   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6707   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6708   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6709   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6710   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6711   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6712   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6713   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6714                                                                Subtarget);
6715   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6716   case ISD::SHL:
6717   case ISD::SRL:
6718   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6719   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6720   case ISD::SRL_PARTS:
6721   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6722   case ISD::CTTZ:
6723   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6724   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6725   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6726   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6727   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6728   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6729   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6730   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6731   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6732   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6733   case ISD::MUL:           return LowerMUL(Op, DAG);
6734   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6735   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6736   case ISD::ADDC:
6737   case ISD::ADDE:
6738   case ISD::SUBC:
6739   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6740   case ISD::SADDO:
6741   case ISD::UADDO:
6742   case ISD::SSUBO:
6743   case ISD::USUBO:
6744     return LowerXALUO(Op, DAG);
6745   case ISD::ATOMIC_LOAD:
6746   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6747   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6748   case ISD::SDIVREM:
6749   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6750   case ISD::DYNAMIC_STACKALLOC:
6751     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6752       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6753     llvm_unreachable("Don't know how to custom lower this!");
6754   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6755   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6756   }
6757 }
6758
6759 /// ReplaceNodeResults - Replace the results of node with an illegal result
6760 /// type with new values built out of custom code.
6761 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6762                                            SmallVectorImpl<SDValue>&Results,
6763                                            SelectionDAG &DAG) const {
6764   SDValue Res;
6765   switch (N->getOpcode()) {
6766   default:
6767     llvm_unreachable("Don't know how to custom expand this!");
6768   case ISD::READ_REGISTER:
6769     ExpandREAD_REGISTER(N, Results, DAG);
6770     break;
6771   case ISD::BITCAST:
6772     Res = ExpandBITCAST(N, DAG);
6773     break;
6774   case ISD::SRL:
6775   case ISD::SRA:
6776     Res = Expand64BitShift(N, DAG, Subtarget);
6777     break;
6778   case ISD::READCYCLECOUNTER:
6779     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6780     return;
6781   }
6782   if (Res.getNode())
6783     Results.push_back(Res);
6784 }
6785
6786 //===----------------------------------------------------------------------===//
6787 //                           ARM Scheduler Hooks
6788 //===----------------------------------------------------------------------===//
6789
6790 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6791 /// registers the function context.
6792 void ARMTargetLowering::
6793 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6794                        MachineBasicBlock *DispatchBB, int FI) const {
6795   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6796   DebugLoc dl = MI->getDebugLoc();
6797   MachineFunction *MF = MBB->getParent();
6798   MachineRegisterInfo *MRI = &MF->getRegInfo();
6799   MachineConstantPool *MCP = MF->getConstantPool();
6800   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6801   const Function *F = MF->getFunction();
6802
6803   bool isThumb = Subtarget->isThumb();
6804   bool isThumb2 = Subtarget->isThumb2();
6805
6806   unsigned PCLabelId = AFI->createPICLabelUId();
6807   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6808   ARMConstantPoolValue *CPV =
6809     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6810   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6811
6812   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6813                                            : &ARM::GPRRegClass;
6814
6815   // Grab constant pool and fixed stack memory operands.
6816   MachineMemOperand *CPMMO =
6817       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6818                                MachineMemOperand::MOLoad, 4, 4);
6819
6820   MachineMemOperand *FIMMOSt =
6821       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6822                                MachineMemOperand::MOStore, 4, 4);
6823
6824   // Load the address of the dispatch MBB into the jump buffer.
6825   if (isThumb2) {
6826     // Incoming value: jbuf
6827     //   ldr.n  r5, LCPI1_1
6828     //   orr    r5, r5, #1
6829     //   add    r5, pc
6830     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6831     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6832     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6833                    .addConstantPoolIndex(CPI)
6834                    .addMemOperand(CPMMO));
6835     // Set the low bit because of thumb mode.
6836     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6837     AddDefaultCC(
6838       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6839                      .addReg(NewVReg1, RegState::Kill)
6840                      .addImm(0x01)));
6841     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6842     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6843       .addReg(NewVReg2, RegState::Kill)
6844       .addImm(PCLabelId);
6845     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6846                    .addReg(NewVReg3, RegState::Kill)
6847                    .addFrameIndex(FI)
6848                    .addImm(36)  // &jbuf[1] :: pc
6849                    .addMemOperand(FIMMOSt));
6850   } else if (isThumb) {
6851     // Incoming value: jbuf
6852     //   ldr.n  r1, LCPI1_4
6853     //   add    r1, pc
6854     //   mov    r2, #1
6855     //   orrs   r1, r2
6856     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6857     //   str    r1, [r2]
6858     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6859     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6860                    .addConstantPoolIndex(CPI)
6861                    .addMemOperand(CPMMO));
6862     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6863     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6864       .addReg(NewVReg1, RegState::Kill)
6865       .addImm(PCLabelId);
6866     // Set the low bit because of thumb mode.
6867     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6868     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6869                    .addReg(ARM::CPSR, RegState::Define)
6870                    .addImm(1));
6871     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6872     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6873                    .addReg(ARM::CPSR, RegState::Define)
6874                    .addReg(NewVReg2, RegState::Kill)
6875                    .addReg(NewVReg3, RegState::Kill));
6876     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6877     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6878             .addFrameIndex(FI)
6879             .addImm(36); // &jbuf[1] :: pc
6880     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6881                    .addReg(NewVReg4, RegState::Kill)
6882                    .addReg(NewVReg5, RegState::Kill)
6883                    .addImm(0)
6884                    .addMemOperand(FIMMOSt));
6885   } else {
6886     // Incoming value: jbuf
6887     //   ldr  r1, LCPI1_1
6888     //   add  r1, pc, r1
6889     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6890     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6891     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6892                    .addConstantPoolIndex(CPI)
6893                    .addImm(0)
6894                    .addMemOperand(CPMMO));
6895     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6896     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6897                    .addReg(NewVReg1, RegState::Kill)
6898                    .addImm(PCLabelId));
6899     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6900                    .addReg(NewVReg2, RegState::Kill)
6901                    .addFrameIndex(FI)
6902                    .addImm(36)  // &jbuf[1] :: pc
6903                    .addMemOperand(FIMMOSt));
6904   }
6905 }
6906
6907 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6908                                               MachineBasicBlock *MBB) const {
6909   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6910   DebugLoc dl = MI->getDebugLoc();
6911   MachineFunction *MF = MBB->getParent();
6912   MachineRegisterInfo *MRI = &MF->getRegInfo();
6913   MachineFrameInfo *MFI = MF->getFrameInfo();
6914   int FI = MFI->getFunctionContextIndex();
6915
6916   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6917                                                         : &ARM::GPRnopcRegClass;
6918
6919   // Get a mapping of the call site numbers to all of the landing pads they're
6920   // associated with.
6921   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6922   unsigned MaxCSNum = 0;
6923   MachineModuleInfo &MMI = MF->getMMI();
6924   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6925        ++BB) {
6926     if (!BB->isLandingPad()) continue;
6927
6928     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6929     // pad.
6930     for (MachineBasicBlock::iterator
6931            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6932       if (!II->isEHLabel()) continue;
6933
6934       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6935       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6936
6937       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6938       for (SmallVectorImpl<unsigned>::iterator
6939              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6940            CSI != CSE; ++CSI) {
6941         CallSiteNumToLPad[*CSI].push_back(BB);
6942         MaxCSNum = std::max(MaxCSNum, *CSI);
6943       }
6944       break;
6945     }
6946   }
6947
6948   // Get an ordered list of the machine basic blocks for the jump table.
6949   std::vector<MachineBasicBlock*> LPadList;
6950   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6951   LPadList.reserve(CallSiteNumToLPad.size());
6952   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6953     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6954     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6955            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6956       LPadList.push_back(*II);
6957       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6958     }
6959   }
6960
6961   assert(!LPadList.empty() &&
6962          "No landing pad destinations for the dispatch jump table!");
6963
6964   // Create the jump table and associated information.
6965   MachineJumpTableInfo *JTI =
6966     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6967   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6968   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6969
6970   // Create the MBBs for the dispatch code.
6971
6972   // Shove the dispatch's address into the return slot in the function context.
6973   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6974   DispatchBB->setIsLandingPad();
6975
6976   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6977   unsigned trap_opcode;
6978   if (Subtarget->isThumb())
6979     trap_opcode = ARM::tTRAP;
6980   else
6981     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6982
6983   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6984   DispatchBB->addSuccessor(TrapBB);
6985
6986   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6987   DispatchBB->addSuccessor(DispContBB);
6988
6989   // Insert and MBBs.
6990   MF->insert(MF->end(), DispatchBB);
6991   MF->insert(MF->end(), DispContBB);
6992   MF->insert(MF->end(), TrapBB);
6993
6994   // Insert code into the entry block that creates and registers the function
6995   // context.
6996   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6997
6998   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
6999       MachinePointerInfo::getFixedStack(*MF, FI),
7000       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7001
7002   MachineInstrBuilder MIB;
7003   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7004
7005   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7006   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7007
7008   // Add a register mask with no preserved registers.  This results in all
7009   // registers being marked as clobbered.
7010   MIB.addRegMask(RI.getNoPreservedMask());
7011
7012   unsigned NumLPads = LPadList.size();
7013   if (Subtarget->isThumb2()) {
7014     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7015     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7016                    .addFrameIndex(FI)
7017                    .addImm(4)
7018                    .addMemOperand(FIMMOLd));
7019
7020     if (NumLPads < 256) {
7021       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7022                      .addReg(NewVReg1)
7023                      .addImm(LPadList.size()));
7024     } else {
7025       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7026       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7027                      .addImm(NumLPads & 0xFFFF));
7028
7029       unsigned VReg2 = VReg1;
7030       if ((NumLPads & 0xFFFF0000) != 0) {
7031         VReg2 = MRI->createVirtualRegister(TRC);
7032         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7033                        .addReg(VReg1)
7034                        .addImm(NumLPads >> 16));
7035       }
7036
7037       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7038                      .addReg(NewVReg1)
7039                      .addReg(VReg2));
7040     }
7041
7042     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7043       .addMBB(TrapBB)
7044       .addImm(ARMCC::HI)
7045       .addReg(ARM::CPSR);
7046
7047     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7048     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7049                    .addJumpTableIndex(MJTI));
7050
7051     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7052     AddDefaultCC(
7053       AddDefaultPred(
7054         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7055         .addReg(NewVReg3, RegState::Kill)
7056         .addReg(NewVReg1)
7057         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7058
7059     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7060       .addReg(NewVReg4, RegState::Kill)
7061       .addReg(NewVReg1)
7062       .addJumpTableIndex(MJTI);
7063   } else if (Subtarget->isThumb()) {
7064     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7065     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7066                    .addFrameIndex(FI)
7067                    .addImm(1)
7068                    .addMemOperand(FIMMOLd));
7069
7070     if (NumLPads < 256) {
7071       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7072                      .addReg(NewVReg1)
7073                      .addImm(NumLPads));
7074     } else {
7075       MachineConstantPool *ConstantPool = MF->getConstantPool();
7076       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7077       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7078
7079       // MachineConstantPool wants an explicit alignment.
7080       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7081       if (Align == 0)
7082         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7083       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7084
7085       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7086       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7087                      .addReg(VReg1, RegState::Define)
7088                      .addConstantPoolIndex(Idx));
7089       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7090                      .addReg(NewVReg1)
7091                      .addReg(VReg1));
7092     }
7093
7094     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7095       .addMBB(TrapBB)
7096       .addImm(ARMCC::HI)
7097       .addReg(ARM::CPSR);
7098
7099     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7100     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7101                    .addReg(ARM::CPSR, RegState::Define)
7102                    .addReg(NewVReg1)
7103                    .addImm(2));
7104
7105     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7106     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7107                    .addJumpTableIndex(MJTI));
7108
7109     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7110     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7111                    .addReg(ARM::CPSR, RegState::Define)
7112                    .addReg(NewVReg2, RegState::Kill)
7113                    .addReg(NewVReg3));
7114
7115     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7116         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7117
7118     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7119     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7120                    .addReg(NewVReg4, RegState::Kill)
7121                    .addImm(0)
7122                    .addMemOperand(JTMMOLd));
7123
7124     unsigned NewVReg6 = NewVReg5;
7125     if (RelocM == Reloc::PIC_) {
7126       NewVReg6 = MRI->createVirtualRegister(TRC);
7127       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7128                      .addReg(ARM::CPSR, RegState::Define)
7129                      .addReg(NewVReg5, RegState::Kill)
7130                      .addReg(NewVReg3));
7131     }
7132
7133     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7134       .addReg(NewVReg6, RegState::Kill)
7135       .addJumpTableIndex(MJTI);
7136   } else {
7137     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7138     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7139                    .addFrameIndex(FI)
7140                    .addImm(4)
7141                    .addMemOperand(FIMMOLd));
7142
7143     if (NumLPads < 256) {
7144       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7145                      .addReg(NewVReg1)
7146                      .addImm(NumLPads));
7147     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7148       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7149       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7150                      .addImm(NumLPads & 0xFFFF));
7151
7152       unsigned VReg2 = VReg1;
7153       if ((NumLPads & 0xFFFF0000) != 0) {
7154         VReg2 = MRI->createVirtualRegister(TRC);
7155         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7156                        .addReg(VReg1)
7157                        .addImm(NumLPads >> 16));
7158       }
7159
7160       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7161                      .addReg(NewVReg1)
7162                      .addReg(VReg2));
7163     } else {
7164       MachineConstantPool *ConstantPool = MF->getConstantPool();
7165       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7166       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7167
7168       // MachineConstantPool wants an explicit alignment.
7169       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7170       if (Align == 0)
7171         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7172       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7173
7174       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7175       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7176                      .addReg(VReg1, RegState::Define)
7177                      .addConstantPoolIndex(Idx)
7178                      .addImm(0));
7179       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7180                      .addReg(NewVReg1)
7181                      .addReg(VReg1, RegState::Kill));
7182     }
7183
7184     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7185       .addMBB(TrapBB)
7186       .addImm(ARMCC::HI)
7187       .addReg(ARM::CPSR);
7188
7189     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7190     AddDefaultCC(
7191       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7192                      .addReg(NewVReg1)
7193                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7194     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7195     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7196                    .addJumpTableIndex(MJTI));
7197
7198     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7199         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7200     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7201     AddDefaultPred(
7202       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7203       .addReg(NewVReg3, RegState::Kill)
7204       .addReg(NewVReg4)
7205       .addImm(0)
7206       .addMemOperand(JTMMOLd));
7207
7208     if (RelocM == Reloc::PIC_) {
7209       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7210         .addReg(NewVReg5, RegState::Kill)
7211         .addReg(NewVReg4)
7212         .addJumpTableIndex(MJTI);
7213     } else {
7214       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7215         .addReg(NewVReg5, RegState::Kill)
7216         .addJumpTableIndex(MJTI);
7217     }
7218   }
7219
7220   // Add the jump table entries as successors to the MBB.
7221   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7222   for (std::vector<MachineBasicBlock*>::iterator
7223          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7224     MachineBasicBlock *CurMBB = *I;
7225     if (SeenMBBs.insert(CurMBB).second)
7226       DispContBB->addSuccessor(CurMBB);
7227   }
7228
7229   // N.B. the order the invoke BBs are processed in doesn't matter here.
7230   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7231   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7232   for (MachineBasicBlock *BB : InvokeBBs) {
7233
7234     // Remove the landing pad successor from the invoke block and replace it
7235     // with the new dispatch block.
7236     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7237                                                   BB->succ_end());
7238     while (!Successors.empty()) {
7239       MachineBasicBlock *SMBB = Successors.pop_back_val();
7240       if (SMBB->isLandingPad()) {
7241         BB->removeSuccessor(SMBB);
7242         MBBLPads.push_back(SMBB);
7243       }
7244     }
7245
7246     BB->addSuccessor(DispatchBB);
7247
7248     // Find the invoke call and mark all of the callee-saved registers as
7249     // 'implicit defined' so that they're spilled. This prevents code from
7250     // moving instructions to before the EH block, where they will never be
7251     // executed.
7252     for (MachineBasicBlock::reverse_iterator
7253            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7254       if (!II->isCall()) continue;
7255
7256       DenseMap<unsigned, bool> DefRegs;
7257       for (MachineInstr::mop_iterator
7258              OI = II->operands_begin(), OE = II->operands_end();
7259            OI != OE; ++OI) {
7260         if (!OI->isReg()) continue;
7261         DefRegs[OI->getReg()] = true;
7262       }
7263
7264       MachineInstrBuilder MIB(*MF, &*II);
7265
7266       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7267         unsigned Reg = SavedRegs[i];
7268         if (Subtarget->isThumb2() &&
7269             !ARM::tGPRRegClass.contains(Reg) &&
7270             !ARM::hGPRRegClass.contains(Reg))
7271           continue;
7272         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7273           continue;
7274         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7275           continue;
7276         if (!DefRegs[Reg])
7277           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7278       }
7279
7280       break;
7281     }
7282   }
7283
7284   // Mark all former landing pads as non-landing pads. The dispatch is the only
7285   // landing pad now.
7286   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7287          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7288     (*I)->setIsLandingPad(false);
7289
7290   // The instruction is gone now.
7291   MI->eraseFromParent();
7292 }
7293
7294 static
7295 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7296   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7297        E = MBB->succ_end(); I != E; ++I)
7298     if (*I != Succ)
7299       return *I;
7300   llvm_unreachable("Expecting a BB with two successors!");
7301 }
7302
7303 /// Return the load opcode for a given load size. If load size >= 8,
7304 /// neon opcode will be returned.
7305 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7306   if (LdSize >= 8)
7307     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7308                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7309   if (IsThumb1)
7310     return LdSize == 4 ? ARM::tLDRi
7311                        : LdSize == 2 ? ARM::tLDRHi
7312                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7313   if (IsThumb2)
7314     return LdSize == 4 ? ARM::t2LDR_POST
7315                        : LdSize == 2 ? ARM::t2LDRH_POST
7316                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7317   return LdSize == 4 ? ARM::LDR_POST_IMM
7318                      : LdSize == 2 ? ARM::LDRH_POST
7319                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7320 }
7321
7322 /// Return the store opcode for a given store size. If store size >= 8,
7323 /// neon opcode will be returned.
7324 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7325   if (StSize >= 8)
7326     return StSize == 16 ? ARM::VST1q32wb_fixed
7327                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7328   if (IsThumb1)
7329     return StSize == 4 ? ARM::tSTRi
7330                        : StSize == 2 ? ARM::tSTRHi
7331                                      : StSize == 1 ? ARM::tSTRBi : 0;
7332   if (IsThumb2)
7333     return StSize == 4 ? ARM::t2STR_POST
7334                        : StSize == 2 ? ARM::t2STRH_POST
7335                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7336   return StSize == 4 ? ARM::STR_POST_IMM
7337                      : StSize == 2 ? ARM::STRH_POST
7338                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7339 }
7340
7341 /// Emit a post-increment load operation with given size. The instructions
7342 /// will be added to BB at Pos.
7343 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7344                        const TargetInstrInfo *TII, DebugLoc dl,
7345                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7346                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7347   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7348   assert(LdOpc != 0 && "Should have a load opcode");
7349   if (LdSize >= 8) {
7350     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7351                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7352                        .addImm(0));
7353   } else if (IsThumb1) {
7354     // load + update AddrIn
7355     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7356                        .addReg(AddrIn).addImm(0));
7357     MachineInstrBuilder MIB =
7358         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7359     MIB = AddDefaultT1CC(MIB);
7360     MIB.addReg(AddrIn).addImm(LdSize);
7361     AddDefaultPred(MIB);
7362   } else if (IsThumb2) {
7363     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7364                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7365                        .addImm(LdSize));
7366   } else { // arm
7367     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7368                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7369                        .addReg(0).addImm(LdSize));
7370   }
7371 }
7372
7373 /// Emit a post-increment store operation with given size. The instructions
7374 /// will be added to BB at Pos.
7375 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7376                        const TargetInstrInfo *TII, DebugLoc dl,
7377                        unsigned StSize, unsigned Data, unsigned AddrIn,
7378                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7379   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7380   assert(StOpc != 0 && "Should have a store opcode");
7381   if (StSize >= 8) {
7382     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7383                        .addReg(AddrIn).addImm(0).addReg(Data));
7384   } else if (IsThumb1) {
7385     // store + update AddrIn
7386     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7387                        .addReg(AddrIn).addImm(0));
7388     MachineInstrBuilder MIB =
7389         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7390     MIB = AddDefaultT1CC(MIB);
7391     MIB.addReg(AddrIn).addImm(StSize);
7392     AddDefaultPred(MIB);
7393   } else if (IsThumb2) {
7394     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7395                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7396   } else { // arm
7397     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7398                        .addReg(Data).addReg(AddrIn).addReg(0)
7399                        .addImm(StSize));
7400   }
7401 }
7402
7403 MachineBasicBlock *
7404 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7405                                    MachineBasicBlock *BB) const {
7406   // This pseudo instruction has 3 operands: dst, src, size
7407   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7408   // Otherwise, we will generate unrolled scalar copies.
7409   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7410   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7411   MachineFunction::iterator It = BB;
7412   ++It;
7413
7414   unsigned dest = MI->getOperand(0).getReg();
7415   unsigned src = MI->getOperand(1).getReg();
7416   unsigned SizeVal = MI->getOperand(2).getImm();
7417   unsigned Align = MI->getOperand(3).getImm();
7418   DebugLoc dl = MI->getDebugLoc();
7419
7420   MachineFunction *MF = BB->getParent();
7421   MachineRegisterInfo &MRI = MF->getRegInfo();
7422   unsigned UnitSize = 0;
7423   const TargetRegisterClass *TRC = nullptr;
7424   const TargetRegisterClass *VecTRC = nullptr;
7425
7426   bool IsThumb1 = Subtarget->isThumb1Only();
7427   bool IsThumb2 = Subtarget->isThumb2();
7428
7429   if (Align & 1) {
7430     UnitSize = 1;
7431   } else if (Align & 2) {
7432     UnitSize = 2;
7433   } else {
7434     // Check whether we can use NEON instructions.
7435     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7436         Subtarget->hasNEON()) {
7437       if ((Align % 16 == 0) && SizeVal >= 16)
7438         UnitSize = 16;
7439       else if ((Align % 8 == 0) && SizeVal >= 8)
7440         UnitSize = 8;
7441     }
7442     // Can't use NEON instructions.
7443     if (UnitSize == 0)
7444       UnitSize = 4;
7445   }
7446
7447   // Select the correct opcode and register class for unit size load/store
7448   bool IsNeon = UnitSize >= 8;
7449   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7450   if (IsNeon)
7451     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7452                             : UnitSize == 8 ? &ARM::DPRRegClass
7453                                             : nullptr;
7454
7455   unsigned BytesLeft = SizeVal % UnitSize;
7456   unsigned LoopSize = SizeVal - BytesLeft;
7457
7458   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7459     // Use LDR and STR to copy.
7460     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7461     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7462     unsigned srcIn = src;
7463     unsigned destIn = dest;
7464     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7465       unsigned srcOut = MRI.createVirtualRegister(TRC);
7466       unsigned destOut = MRI.createVirtualRegister(TRC);
7467       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7468       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7469                  IsThumb1, IsThumb2);
7470       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7471                  IsThumb1, IsThumb2);
7472       srcIn = srcOut;
7473       destIn = destOut;
7474     }
7475
7476     // Handle the leftover bytes with LDRB and STRB.
7477     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7478     // [destOut] = STRB_POST(scratch, destIn, 1)
7479     for (unsigned i = 0; i < BytesLeft; i++) {
7480       unsigned srcOut = MRI.createVirtualRegister(TRC);
7481       unsigned destOut = MRI.createVirtualRegister(TRC);
7482       unsigned scratch = MRI.createVirtualRegister(TRC);
7483       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7484                  IsThumb1, IsThumb2);
7485       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7486                  IsThumb1, IsThumb2);
7487       srcIn = srcOut;
7488       destIn = destOut;
7489     }
7490     MI->eraseFromParent();   // The instruction is gone now.
7491     return BB;
7492   }
7493
7494   // Expand the pseudo op to a loop.
7495   // thisMBB:
7496   //   ...
7497   //   movw varEnd, # --> with thumb2
7498   //   movt varEnd, #
7499   //   ldrcp varEnd, idx --> without thumb2
7500   //   fallthrough --> loopMBB
7501   // loopMBB:
7502   //   PHI varPhi, varEnd, varLoop
7503   //   PHI srcPhi, src, srcLoop
7504   //   PHI destPhi, dst, destLoop
7505   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7506   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7507   //   subs varLoop, varPhi, #UnitSize
7508   //   bne loopMBB
7509   //   fallthrough --> exitMBB
7510   // exitMBB:
7511   //   epilogue to handle left-over bytes
7512   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7513   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7514   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7515   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7516   MF->insert(It, loopMBB);
7517   MF->insert(It, exitMBB);
7518
7519   // Transfer the remainder of BB and its successor edges to exitMBB.
7520   exitMBB->splice(exitMBB->begin(), BB,
7521                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7522   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7523
7524   // Load an immediate to varEnd.
7525   unsigned varEnd = MRI.createVirtualRegister(TRC);
7526   if (Subtarget->useMovt(*MF)) {
7527     unsigned Vtmp = varEnd;
7528     if ((LoopSize & 0xFFFF0000) != 0)
7529       Vtmp = MRI.createVirtualRegister(TRC);
7530     AddDefaultPred(BuildMI(BB, dl,
7531                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7532                            Vtmp).addImm(LoopSize & 0xFFFF));
7533
7534     if ((LoopSize & 0xFFFF0000) != 0)
7535       AddDefaultPred(BuildMI(BB, dl,
7536                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7537                              varEnd)
7538                          .addReg(Vtmp)
7539                          .addImm(LoopSize >> 16));
7540   } else {
7541     MachineConstantPool *ConstantPool = MF->getConstantPool();
7542     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7543     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7544
7545     // MachineConstantPool wants an explicit alignment.
7546     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7547     if (Align == 0)
7548       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7549     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7550
7551     if (IsThumb1)
7552       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7553           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7554     else
7555       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7556           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7557   }
7558   BB->addSuccessor(loopMBB);
7559
7560   // Generate the loop body:
7561   //   varPhi = PHI(varLoop, varEnd)
7562   //   srcPhi = PHI(srcLoop, src)
7563   //   destPhi = PHI(destLoop, dst)
7564   MachineBasicBlock *entryBB = BB;
7565   BB = loopMBB;
7566   unsigned varLoop = MRI.createVirtualRegister(TRC);
7567   unsigned varPhi = MRI.createVirtualRegister(TRC);
7568   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7569   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7570   unsigned destLoop = MRI.createVirtualRegister(TRC);
7571   unsigned destPhi = MRI.createVirtualRegister(TRC);
7572
7573   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7574     .addReg(varLoop).addMBB(loopMBB)
7575     .addReg(varEnd).addMBB(entryBB);
7576   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7577     .addReg(srcLoop).addMBB(loopMBB)
7578     .addReg(src).addMBB(entryBB);
7579   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7580     .addReg(destLoop).addMBB(loopMBB)
7581     .addReg(dest).addMBB(entryBB);
7582
7583   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7584   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7585   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7586   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7587              IsThumb1, IsThumb2);
7588   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7589              IsThumb1, IsThumb2);
7590
7591   // Decrement loop variable by UnitSize.
7592   if (IsThumb1) {
7593     MachineInstrBuilder MIB =
7594         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7595     MIB = AddDefaultT1CC(MIB);
7596     MIB.addReg(varPhi).addImm(UnitSize);
7597     AddDefaultPred(MIB);
7598   } else {
7599     MachineInstrBuilder MIB =
7600         BuildMI(*BB, BB->end(), dl,
7601                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7602     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7603     MIB->getOperand(5).setReg(ARM::CPSR);
7604     MIB->getOperand(5).setIsDef(true);
7605   }
7606   BuildMI(*BB, BB->end(), dl,
7607           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7608       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7609
7610   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7611   BB->addSuccessor(loopMBB);
7612   BB->addSuccessor(exitMBB);
7613
7614   // Add epilogue to handle BytesLeft.
7615   BB = exitMBB;
7616   MachineInstr *StartOfExit = exitMBB->begin();
7617
7618   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7619   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7620   unsigned srcIn = srcLoop;
7621   unsigned destIn = destLoop;
7622   for (unsigned i = 0; i < BytesLeft; i++) {
7623     unsigned srcOut = MRI.createVirtualRegister(TRC);
7624     unsigned destOut = MRI.createVirtualRegister(TRC);
7625     unsigned scratch = MRI.createVirtualRegister(TRC);
7626     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7627                IsThumb1, IsThumb2);
7628     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7629                IsThumb1, IsThumb2);
7630     srcIn = srcOut;
7631     destIn = destOut;
7632   }
7633
7634   MI->eraseFromParent();   // The instruction is gone now.
7635   return BB;
7636 }
7637
7638 MachineBasicBlock *
7639 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7640                                        MachineBasicBlock *MBB) const {
7641   const TargetMachine &TM = getTargetMachine();
7642   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7643   DebugLoc DL = MI->getDebugLoc();
7644
7645   assert(Subtarget->isTargetWindows() &&
7646          "__chkstk is only supported on Windows");
7647   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7648
7649   // __chkstk takes the number of words to allocate on the stack in R4, and
7650   // returns the stack adjustment in number of bytes in R4.  This will not
7651   // clober any other registers (other than the obvious lr).
7652   //
7653   // Although, technically, IP should be considered a register which may be
7654   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7655   // thumb-2 environment, so there is no interworking required.  As a result, we
7656   // do not expect a veneer to be emitted by the linker, clobbering IP.
7657   //
7658   // Each module receives its own copy of __chkstk, so no import thunk is
7659   // required, again, ensuring that IP is not clobbered.
7660   //
7661   // Finally, although some linkers may theoretically provide a trampoline for
7662   // out of range calls (which is quite common due to a 32M range limitation of
7663   // branches for Thumb), we can generate the long-call version via
7664   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7665   // IP.
7666
7667   switch (TM.getCodeModel()) {
7668   case CodeModel::Small:
7669   case CodeModel::Medium:
7670   case CodeModel::Default:
7671   case CodeModel::Kernel:
7672     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7673       .addImm((unsigned)ARMCC::AL).addReg(0)
7674       .addExternalSymbol("__chkstk")
7675       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7676       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7677       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7678     break;
7679   case CodeModel::Large:
7680   case CodeModel::JITDefault: {
7681     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7682     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7683
7684     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7685       .addExternalSymbol("__chkstk");
7686     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7687       .addImm((unsigned)ARMCC::AL).addReg(0)
7688       .addReg(Reg, RegState::Kill)
7689       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7690       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7691       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7692     break;
7693   }
7694   }
7695
7696   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7697                                       ARM::SP)
7698                               .addReg(ARM::SP).addReg(ARM::R4)));
7699
7700   MI->eraseFromParent();
7701   return MBB;
7702 }
7703
7704 MachineBasicBlock *
7705 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7706                                                MachineBasicBlock *BB) const {
7707   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7708   DebugLoc dl = MI->getDebugLoc();
7709   bool isThumb2 = Subtarget->isThumb2();
7710   switch (MI->getOpcode()) {
7711   default: {
7712     MI->dump();
7713     llvm_unreachable("Unexpected instr type to insert");
7714   }
7715   // The Thumb2 pre-indexed stores have the same MI operands, they just
7716   // define them differently in the .td files from the isel patterns, so
7717   // they need pseudos.
7718   case ARM::t2STR_preidx:
7719     MI->setDesc(TII->get(ARM::t2STR_PRE));
7720     return BB;
7721   case ARM::t2STRB_preidx:
7722     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7723     return BB;
7724   case ARM::t2STRH_preidx:
7725     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7726     return BB;
7727
7728   case ARM::STRi_preidx:
7729   case ARM::STRBi_preidx: {
7730     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7731       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7732     // Decode the offset.
7733     unsigned Offset = MI->getOperand(4).getImm();
7734     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7735     Offset = ARM_AM::getAM2Offset(Offset);
7736     if (isSub)
7737       Offset = -Offset;
7738
7739     MachineMemOperand *MMO = *MI->memoperands_begin();
7740     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7741       .addOperand(MI->getOperand(0))  // Rn_wb
7742       .addOperand(MI->getOperand(1))  // Rt
7743       .addOperand(MI->getOperand(2))  // Rn
7744       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7745       .addOperand(MI->getOperand(5))  // pred
7746       .addOperand(MI->getOperand(6))
7747       .addMemOperand(MMO);
7748     MI->eraseFromParent();
7749     return BB;
7750   }
7751   case ARM::STRr_preidx:
7752   case ARM::STRBr_preidx:
7753   case ARM::STRH_preidx: {
7754     unsigned NewOpc;
7755     switch (MI->getOpcode()) {
7756     default: llvm_unreachable("unexpected opcode!");
7757     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7758     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7759     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7760     }
7761     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7762     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7763       MIB.addOperand(MI->getOperand(i));
7764     MI->eraseFromParent();
7765     return BB;
7766   }
7767
7768   case ARM::tMOVCCr_pseudo: {
7769     // To "insert" a SELECT_CC instruction, we actually have to insert the
7770     // diamond control-flow pattern.  The incoming instruction knows the
7771     // destination vreg to set, the condition code register to branch on, the
7772     // true/false values to select between, and a branch opcode to use.
7773     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7774     MachineFunction::iterator It = BB;
7775     ++It;
7776
7777     //  thisMBB:
7778     //  ...
7779     //   TrueVal = ...
7780     //   cmpTY ccX, r1, r2
7781     //   bCC copy1MBB
7782     //   fallthrough --> copy0MBB
7783     MachineBasicBlock *thisMBB  = BB;
7784     MachineFunction *F = BB->getParent();
7785     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7786     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7787     F->insert(It, copy0MBB);
7788     F->insert(It, sinkMBB);
7789
7790     // Transfer the remainder of BB and its successor edges to sinkMBB.
7791     sinkMBB->splice(sinkMBB->begin(), BB,
7792                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7793     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7794
7795     BB->addSuccessor(copy0MBB);
7796     BB->addSuccessor(sinkMBB);
7797
7798     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7799       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7800
7801     //  copy0MBB:
7802     //   %FalseValue = ...
7803     //   # fallthrough to sinkMBB
7804     BB = copy0MBB;
7805
7806     // Update machine-CFG edges
7807     BB->addSuccessor(sinkMBB);
7808
7809     //  sinkMBB:
7810     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7811     //  ...
7812     BB = sinkMBB;
7813     BuildMI(*BB, BB->begin(), dl,
7814             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7815       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7816       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7817
7818     MI->eraseFromParent();   // The pseudo instruction is gone now.
7819     return BB;
7820   }
7821
7822   case ARM::BCCi64:
7823   case ARM::BCCZi64: {
7824     // If there is an unconditional branch to the other successor, remove it.
7825     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7826
7827     // Compare both parts that make up the double comparison separately for
7828     // equality.
7829     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7830
7831     unsigned LHS1 = MI->getOperand(1).getReg();
7832     unsigned LHS2 = MI->getOperand(2).getReg();
7833     if (RHSisZero) {
7834       AddDefaultPred(BuildMI(BB, dl,
7835                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7836                      .addReg(LHS1).addImm(0));
7837       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7838         .addReg(LHS2).addImm(0)
7839         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7840     } else {
7841       unsigned RHS1 = MI->getOperand(3).getReg();
7842       unsigned RHS2 = MI->getOperand(4).getReg();
7843       AddDefaultPred(BuildMI(BB, dl,
7844                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7845                      .addReg(LHS1).addReg(RHS1));
7846       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7847         .addReg(LHS2).addReg(RHS2)
7848         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7849     }
7850
7851     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7852     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7853     if (MI->getOperand(0).getImm() == ARMCC::NE)
7854       std::swap(destMBB, exitMBB);
7855
7856     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7857       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7858     if (isThumb2)
7859       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7860     else
7861       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7862
7863     MI->eraseFromParent();   // The pseudo instruction is gone now.
7864     return BB;
7865   }
7866
7867   case ARM::Int_eh_sjlj_setjmp:
7868   case ARM::Int_eh_sjlj_setjmp_nofp:
7869   case ARM::tInt_eh_sjlj_setjmp:
7870   case ARM::t2Int_eh_sjlj_setjmp:
7871   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7872     return BB;
7873
7874   case ARM::Int_eh_sjlj_setup_dispatch:
7875     EmitSjLjDispatchBlock(MI, BB);
7876     return BB;
7877
7878   case ARM::ABS:
7879   case ARM::t2ABS: {
7880     // To insert an ABS instruction, we have to insert the
7881     // diamond control-flow pattern.  The incoming instruction knows the
7882     // source vreg to test against 0, the destination vreg to set,
7883     // the condition code register to branch on, the
7884     // true/false values to select between, and a branch opcode to use.
7885     // It transforms
7886     //     V1 = ABS V0
7887     // into
7888     //     V2 = MOVS V0
7889     //     BCC                      (branch to SinkBB if V0 >= 0)
7890     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7891     //     SinkBB: V1 = PHI(V2, V3)
7892     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7893     MachineFunction::iterator BBI = BB;
7894     ++BBI;
7895     MachineFunction *Fn = BB->getParent();
7896     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7897     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7898     Fn->insert(BBI, RSBBB);
7899     Fn->insert(BBI, SinkBB);
7900
7901     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7902     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7903     bool ABSSrcKIll = MI->getOperand(1).isKill();
7904     bool isThumb2 = Subtarget->isThumb2();
7905     MachineRegisterInfo &MRI = Fn->getRegInfo();
7906     // In Thumb mode S must not be specified if source register is the SP or
7907     // PC and if destination register is the SP, so restrict register class
7908     unsigned NewRsbDstReg =
7909       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7910
7911     // Transfer the remainder of BB and its successor edges to sinkMBB.
7912     SinkBB->splice(SinkBB->begin(), BB,
7913                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7914     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7915
7916     BB->addSuccessor(RSBBB);
7917     BB->addSuccessor(SinkBB);
7918
7919     // fall through to SinkMBB
7920     RSBBB->addSuccessor(SinkBB);
7921
7922     // insert a cmp at the end of BB
7923     AddDefaultPred(BuildMI(BB, dl,
7924                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7925                    .addReg(ABSSrcReg).addImm(0));
7926
7927     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7928     BuildMI(BB, dl,
7929       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7930       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7931
7932     // insert rsbri in RSBBB
7933     // Note: BCC and rsbri will be converted into predicated rsbmi
7934     // by if-conversion pass
7935     BuildMI(*RSBBB, RSBBB->begin(), dl,
7936       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7937       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7938       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7939
7940     // insert PHI in SinkBB,
7941     // reuse ABSDstReg to not change uses of ABS instruction
7942     BuildMI(*SinkBB, SinkBB->begin(), dl,
7943       TII->get(ARM::PHI), ABSDstReg)
7944       .addReg(NewRsbDstReg).addMBB(RSBBB)
7945       .addReg(ABSSrcReg).addMBB(BB);
7946
7947     // remove ABS instruction
7948     MI->eraseFromParent();
7949
7950     // return last added BB
7951     return SinkBB;
7952   }
7953   case ARM::COPY_STRUCT_BYVAL_I32:
7954     ++NumLoopByVals;
7955     return EmitStructByval(MI, BB);
7956   case ARM::WIN__CHKSTK:
7957     return EmitLowered__chkstk(MI, BB);
7958   }
7959 }
7960
7961 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7962                                                       SDNode *Node) const {
7963   const MCInstrDesc *MCID = &MI->getDesc();
7964   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7965   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7966   // operand is still set to noreg. If needed, set the optional operand's
7967   // register to CPSR, and remove the redundant implicit def.
7968   //
7969   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7970
7971   // Rename pseudo opcodes.
7972   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7973   if (NewOpc) {
7974     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7975     MCID = &TII->get(NewOpc);
7976
7977     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7978            "converted opcode should be the same except for cc_out");
7979
7980     MI->setDesc(*MCID);
7981
7982     // Add the optional cc_out operand
7983     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7984   }
7985   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7986
7987   // Any ARM instruction that sets the 's' bit should specify an optional
7988   // "cc_out" operand in the last operand position.
7989   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7990     assert(!NewOpc && "Optional cc_out operand required");
7991     return;
7992   }
7993   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7994   // since we already have an optional CPSR def.
7995   bool definesCPSR = false;
7996   bool deadCPSR = false;
7997   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7998        i != e; ++i) {
7999     const MachineOperand &MO = MI->getOperand(i);
8000     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8001       definesCPSR = true;
8002       if (MO.isDead())
8003         deadCPSR = true;
8004       MI->RemoveOperand(i);
8005       break;
8006     }
8007   }
8008   if (!definesCPSR) {
8009     assert(!NewOpc && "Optional cc_out operand required");
8010     return;
8011   }
8012   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8013   if (deadCPSR) {
8014     assert(!MI->getOperand(ccOutIdx).getReg() &&
8015            "expect uninitialized optional cc_out operand");
8016     return;
8017   }
8018
8019   // If this instruction was defined with an optional CPSR def and its dag node
8020   // had a live implicit CPSR def, then activate the optional CPSR def.
8021   MachineOperand &MO = MI->getOperand(ccOutIdx);
8022   MO.setReg(ARM::CPSR);
8023   MO.setIsDef(true);
8024 }
8025
8026 //===----------------------------------------------------------------------===//
8027 //                           ARM Optimization Hooks
8028 //===----------------------------------------------------------------------===//
8029
8030 // Helper function that checks if N is a null or all ones constant.
8031 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8032   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8033   if (!C)
8034     return false;
8035   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8036 }
8037
8038 // Return true if N is conditionally 0 or all ones.
8039 // Detects these expressions where cc is an i1 value:
8040 //
8041 //   (select cc 0, y)   [AllOnes=0]
8042 //   (select cc y, 0)   [AllOnes=0]
8043 //   (zext cc)          [AllOnes=0]
8044 //   (sext cc)          [AllOnes=0/1]
8045 //   (select cc -1, y)  [AllOnes=1]
8046 //   (select cc y, -1)  [AllOnes=1]
8047 //
8048 // Invert is set when N is the null/all ones constant when CC is false.
8049 // OtherOp is set to the alternative value of N.
8050 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8051                                        SDValue &CC, bool &Invert,
8052                                        SDValue &OtherOp,
8053                                        SelectionDAG &DAG) {
8054   switch (N->getOpcode()) {
8055   default: return false;
8056   case ISD::SELECT: {
8057     CC = N->getOperand(0);
8058     SDValue N1 = N->getOperand(1);
8059     SDValue N2 = N->getOperand(2);
8060     if (isZeroOrAllOnes(N1, AllOnes)) {
8061       Invert = false;
8062       OtherOp = N2;
8063       return true;
8064     }
8065     if (isZeroOrAllOnes(N2, AllOnes)) {
8066       Invert = true;
8067       OtherOp = N1;
8068       return true;
8069     }
8070     return false;
8071   }
8072   case ISD::ZERO_EXTEND:
8073     // (zext cc) can never be the all ones value.
8074     if (AllOnes)
8075       return false;
8076     // Fall through.
8077   case ISD::SIGN_EXTEND: {
8078     SDLoc dl(N);
8079     EVT VT = N->getValueType(0);
8080     CC = N->getOperand(0);
8081     if (CC.getValueType() != MVT::i1)
8082       return false;
8083     Invert = !AllOnes;
8084     if (AllOnes)
8085       // When looking for an AllOnes constant, N is an sext, and the 'other'
8086       // value is 0.
8087       OtherOp = DAG.getConstant(0, dl, VT);
8088     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8089       // When looking for a 0 constant, N can be zext or sext.
8090       OtherOp = DAG.getConstant(1, dl, VT);
8091     else
8092       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8093                                 VT);
8094     return true;
8095   }
8096   }
8097 }
8098
8099 // Combine a constant select operand into its use:
8100 //
8101 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8102 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8103 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8104 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8105 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8106 //
8107 // The transform is rejected if the select doesn't have a constant operand that
8108 // is null, or all ones when AllOnes is set.
8109 //
8110 // Also recognize sext/zext from i1:
8111 //
8112 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8113 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8114 //
8115 // These transformations eventually create predicated instructions.
8116 //
8117 // @param N       The node to transform.
8118 // @param Slct    The N operand that is a select.
8119 // @param OtherOp The other N operand (x above).
8120 // @param DCI     Context.
8121 // @param AllOnes Require the select constant to be all ones instead of null.
8122 // @returns The new node, or SDValue() on failure.
8123 static
8124 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8125                             TargetLowering::DAGCombinerInfo &DCI,
8126                             bool AllOnes = false) {
8127   SelectionDAG &DAG = DCI.DAG;
8128   EVT VT = N->getValueType(0);
8129   SDValue NonConstantVal;
8130   SDValue CCOp;
8131   bool SwapSelectOps;
8132   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8133                                   NonConstantVal, DAG))
8134     return SDValue();
8135
8136   // Slct is now know to be the desired identity constant when CC is true.
8137   SDValue TrueVal = OtherOp;
8138   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8139                                  OtherOp, NonConstantVal);
8140   // Unless SwapSelectOps says CC should be false.
8141   if (SwapSelectOps)
8142     std::swap(TrueVal, FalseVal);
8143
8144   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8145                      CCOp, TrueVal, FalseVal);
8146 }
8147
8148 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8149 static
8150 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8151                                        TargetLowering::DAGCombinerInfo &DCI) {
8152   SDValue N0 = N->getOperand(0);
8153   SDValue N1 = N->getOperand(1);
8154   if (N0.getNode()->hasOneUse()) {
8155     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8156     if (Result.getNode())
8157       return Result;
8158   }
8159   if (N1.getNode()->hasOneUse()) {
8160     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8161     if (Result.getNode())
8162       return Result;
8163   }
8164   return SDValue();
8165 }
8166
8167 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8168 // (only after legalization).
8169 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8170                                  TargetLowering::DAGCombinerInfo &DCI,
8171                                  const ARMSubtarget *Subtarget) {
8172
8173   // Only perform optimization if after legalize, and if NEON is available. We
8174   // also expected both operands to be BUILD_VECTORs.
8175   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8176       || N0.getOpcode() != ISD::BUILD_VECTOR
8177       || N1.getOpcode() != ISD::BUILD_VECTOR)
8178     return SDValue();
8179
8180   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8181   EVT VT = N->getValueType(0);
8182   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8183     return SDValue();
8184
8185   // Check that the vector operands are of the right form.
8186   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8187   // operands, where N is the size of the formed vector.
8188   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8189   // index such that we have a pair wise add pattern.
8190
8191   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8192   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8193     return SDValue();
8194   SDValue Vec = N0->getOperand(0)->getOperand(0);
8195   SDNode *V = Vec.getNode();
8196   unsigned nextIndex = 0;
8197
8198   // For each operands to the ADD which are BUILD_VECTORs,
8199   // check to see if each of their operands are an EXTRACT_VECTOR with
8200   // the same vector and appropriate index.
8201   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8202     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8203         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8204
8205       SDValue ExtVec0 = N0->getOperand(i);
8206       SDValue ExtVec1 = N1->getOperand(i);
8207
8208       // First operand is the vector, verify its the same.
8209       if (V != ExtVec0->getOperand(0).getNode() ||
8210           V != ExtVec1->getOperand(0).getNode())
8211         return SDValue();
8212
8213       // Second is the constant, verify its correct.
8214       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8215       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8216
8217       // For the constant, we want to see all the even or all the odd.
8218       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8219           || C1->getZExtValue() != nextIndex+1)
8220         return SDValue();
8221
8222       // Increment index.
8223       nextIndex+=2;
8224     } else
8225       return SDValue();
8226   }
8227
8228   // Create VPADDL node.
8229   SelectionDAG &DAG = DCI.DAG;
8230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8231
8232   SDLoc dl(N);
8233
8234   // Build operand list.
8235   SmallVector<SDValue, 8> Ops;
8236   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8237                                 TLI.getPointerTy(DAG.getDataLayout())));
8238
8239   // Input is the vector.
8240   Ops.push_back(Vec);
8241
8242   // Get widened type and narrowed type.
8243   MVT widenType;
8244   unsigned numElem = VT.getVectorNumElements();
8245   
8246   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8247   switch (inputLaneType.getSimpleVT().SimpleTy) {
8248     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8249     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8250     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8251     default:
8252       llvm_unreachable("Invalid vector element type for padd optimization.");
8253   }
8254
8255   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8256   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8257   return DAG.getNode(ExtOp, dl, VT, tmp);
8258 }
8259
8260 static SDValue findMUL_LOHI(SDValue V) {
8261   if (V->getOpcode() == ISD::UMUL_LOHI ||
8262       V->getOpcode() == ISD::SMUL_LOHI)
8263     return V;
8264   return SDValue();
8265 }
8266
8267 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8268                                      TargetLowering::DAGCombinerInfo &DCI,
8269                                      const ARMSubtarget *Subtarget) {
8270
8271   if (Subtarget->isThumb1Only()) return SDValue();
8272
8273   // Only perform the checks after legalize when the pattern is available.
8274   if (DCI.isBeforeLegalize()) return SDValue();
8275
8276   // Look for multiply add opportunities.
8277   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8278   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8279   // a glue link from the first add to the second add.
8280   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8281   // a S/UMLAL instruction.
8282   //                  UMUL_LOHI
8283   //                 / :lo    \ :hi
8284   //                /          \          [no multiline comment]
8285   //    loAdd ->  ADDE         |
8286   //                 \ :glue  /
8287   //                  \      /
8288   //                    ADDC   <- hiAdd
8289   //
8290   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8291   SDValue AddcOp0 = AddcNode->getOperand(0);
8292   SDValue AddcOp1 = AddcNode->getOperand(1);
8293
8294   // Check if the two operands are from the same mul_lohi node.
8295   if (AddcOp0.getNode() == AddcOp1.getNode())
8296     return SDValue();
8297
8298   assert(AddcNode->getNumValues() == 2 &&
8299          AddcNode->getValueType(0) == MVT::i32 &&
8300          "Expect ADDC with two result values. First: i32");
8301
8302   // Check that we have a glued ADDC node.
8303   if (AddcNode->getValueType(1) != MVT::Glue)
8304     return SDValue();
8305
8306   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8307   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8308       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8309       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8310       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8311     return SDValue();
8312
8313   // Look for the glued ADDE.
8314   SDNode* AddeNode = AddcNode->getGluedUser();
8315   if (!AddeNode)
8316     return SDValue();
8317
8318   // Make sure it is really an ADDE.
8319   if (AddeNode->getOpcode() != ISD::ADDE)
8320     return SDValue();
8321
8322   assert(AddeNode->getNumOperands() == 3 &&
8323          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8324          "ADDE node has the wrong inputs");
8325
8326   // Check for the triangle shape.
8327   SDValue AddeOp0 = AddeNode->getOperand(0);
8328   SDValue AddeOp1 = AddeNode->getOperand(1);
8329
8330   // Make sure that the ADDE operands are not coming from the same node.
8331   if (AddeOp0.getNode() == AddeOp1.getNode())
8332     return SDValue();
8333
8334   // Find the MUL_LOHI node walking up ADDE's operands.
8335   bool IsLeftOperandMUL = false;
8336   SDValue MULOp = findMUL_LOHI(AddeOp0);
8337   if (MULOp == SDValue())
8338    MULOp = findMUL_LOHI(AddeOp1);
8339   else
8340     IsLeftOperandMUL = true;
8341   if (MULOp == SDValue())
8342     return SDValue();
8343
8344   // Figure out the right opcode.
8345   unsigned Opc = MULOp->getOpcode();
8346   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8347
8348   // Figure out the high and low input values to the MLAL node.
8349   SDValue* HiAdd = nullptr;
8350   SDValue* LoMul = nullptr;
8351   SDValue* LowAdd = nullptr;
8352
8353   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8354   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8355     return SDValue();
8356
8357   if (IsLeftOperandMUL)
8358     HiAdd = &AddeOp1;
8359   else
8360     HiAdd = &AddeOp0;
8361
8362
8363   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8364   // whose low result is fed to the ADDC we are checking.
8365
8366   if (AddcOp0 == MULOp.getValue(0)) {
8367     LoMul = &AddcOp0;
8368     LowAdd = &AddcOp1;
8369   }
8370   if (AddcOp1 == MULOp.getValue(0)) {
8371     LoMul = &AddcOp1;
8372     LowAdd = &AddcOp0;
8373   }
8374
8375   if (!LoMul)
8376     return SDValue();
8377
8378   // Create the merged node.
8379   SelectionDAG &DAG = DCI.DAG;
8380
8381   // Build operand list.
8382   SmallVector<SDValue, 8> Ops;
8383   Ops.push_back(LoMul->getOperand(0));
8384   Ops.push_back(LoMul->getOperand(1));
8385   Ops.push_back(*LowAdd);
8386   Ops.push_back(*HiAdd);
8387
8388   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8389                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8390
8391   // Replace the ADDs' nodes uses by the MLA node's values.
8392   SDValue HiMLALResult(MLALNode.getNode(), 1);
8393   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8394
8395   SDValue LoMLALResult(MLALNode.getNode(), 0);
8396   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8397
8398   // Return original node to notify the driver to stop replacing.
8399   SDValue resNode(AddcNode, 0);
8400   return resNode;
8401 }
8402
8403 /// PerformADDCCombine - Target-specific dag combine transform from
8404 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8405 static SDValue PerformADDCCombine(SDNode *N,
8406                                  TargetLowering::DAGCombinerInfo &DCI,
8407                                  const ARMSubtarget *Subtarget) {
8408
8409   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8410
8411 }
8412
8413 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8414 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8415 /// called with the default operands, and if that fails, with commuted
8416 /// operands.
8417 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8418                                           TargetLowering::DAGCombinerInfo &DCI,
8419                                           const ARMSubtarget *Subtarget){
8420
8421   // Attempt to create vpaddl for this add.
8422   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8423   if (Result.getNode())
8424     return Result;
8425
8426   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8427   if (N0.getNode()->hasOneUse()) {
8428     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8429     if (Result.getNode()) return Result;
8430   }
8431   return SDValue();
8432 }
8433
8434 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8435 ///
8436 static SDValue PerformADDCombine(SDNode *N,
8437                                  TargetLowering::DAGCombinerInfo &DCI,
8438                                  const ARMSubtarget *Subtarget) {
8439   SDValue N0 = N->getOperand(0);
8440   SDValue N1 = N->getOperand(1);
8441
8442   // First try with the default operand order.
8443   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8444   if (Result.getNode())
8445     return Result;
8446
8447   // If that didn't work, try again with the operands commuted.
8448   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8449 }
8450
8451 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8452 ///
8453 static SDValue PerformSUBCombine(SDNode *N,
8454                                  TargetLowering::DAGCombinerInfo &DCI) {
8455   SDValue N0 = N->getOperand(0);
8456   SDValue N1 = N->getOperand(1);
8457
8458   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8459   if (N1.getNode()->hasOneUse()) {
8460     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8461     if (Result.getNode()) return Result;
8462   }
8463
8464   return SDValue();
8465 }
8466
8467 /// PerformVMULCombine
8468 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8469 /// special multiplier accumulator forwarding.
8470 ///   vmul d3, d0, d2
8471 ///   vmla d3, d1, d2
8472 /// is faster than
8473 ///   vadd d3, d0, d1
8474 ///   vmul d3, d3, d2
8475 //  However, for (A + B) * (A + B),
8476 //    vadd d2, d0, d1
8477 //    vmul d3, d0, d2
8478 //    vmla d3, d1, d2
8479 //  is slower than
8480 //    vadd d2, d0, d1
8481 //    vmul d3, d2, d2
8482 static SDValue PerformVMULCombine(SDNode *N,
8483                                   TargetLowering::DAGCombinerInfo &DCI,
8484                                   const ARMSubtarget *Subtarget) {
8485   if (!Subtarget->hasVMLxForwarding())
8486     return SDValue();
8487
8488   SelectionDAG &DAG = DCI.DAG;
8489   SDValue N0 = N->getOperand(0);
8490   SDValue N1 = N->getOperand(1);
8491   unsigned Opcode = N0.getOpcode();
8492   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8493       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8494     Opcode = N1.getOpcode();
8495     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8496         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8497       return SDValue();
8498     std::swap(N0, N1);
8499   }
8500
8501   if (N0 == N1)
8502     return SDValue();
8503
8504   EVT VT = N->getValueType(0);
8505   SDLoc DL(N);
8506   SDValue N00 = N0->getOperand(0);
8507   SDValue N01 = N0->getOperand(1);
8508   return DAG.getNode(Opcode, DL, VT,
8509                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8510                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8511 }
8512
8513 static SDValue PerformMULCombine(SDNode *N,
8514                                  TargetLowering::DAGCombinerInfo &DCI,
8515                                  const ARMSubtarget *Subtarget) {
8516   SelectionDAG &DAG = DCI.DAG;
8517
8518   if (Subtarget->isThumb1Only())
8519     return SDValue();
8520
8521   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8522     return SDValue();
8523
8524   EVT VT = N->getValueType(0);
8525   if (VT.is64BitVector() || VT.is128BitVector())
8526     return PerformVMULCombine(N, DCI, Subtarget);
8527   if (VT != MVT::i32)
8528     return SDValue();
8529
8530   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8531   if (!C)
8532     return SDValue();
8533
8534   int64_t MulAmt = C->getSExtValue();
8535   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8536
8537   ShiftAmt = ShiftAmt & (32 - 1);
8538   SDValue V = N->getOperand(0);
8539   SDLoc DL(N);
8540
8541   SDValue Res;
8542   MulAmt >>= ShiftAmt;
8543
8544   if (MulAmt >= 0) {
8545     if (isPowerOf2_32(MulAmt - 1)) {
8546       // (mul x, 2^N + 1) => (add (shl x, N), x)
8547       Res = DAG.getNode(ISD::ADD, DL, VT,
8548                         V,
8549                         DAG.getNode(ISD::SHL, DL, VT,
8550                                     V,
8551                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8552                                                     MVT::i32)));
8553     } else if (isPowerOf2_32(MulAmt + 1)) {
8554       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8555       Res = DAG.getNode(ISD::SUB, DL, VT,
8556                         DAG.getNode(ISD::SHL, DL, VT,
8557                                     V,
8558                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8559                                                     MVT::i32)),
8560                         V);
8561     } else
8562       return SDValue();
8563   } else {
8564     uint64_t MulAmtAbs = -MulAmt;
8565     if (isPowerOf2_32(MulAmtAbs + 1)) {
8566       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8567       Res = DAG.getNode(ISD::SUB, DL, VT,
8568                         V,
8569                         DAG.getNode(ISD::SHL, DL, VT,
8570                                     V,
8571                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8572                                                     MVT::i32)));
8573     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8574       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8575       Res = DAG.getNode(ISD::ADD, DL, VT,
8576                         V,
8577                         DAG.getNode(ISD::SHL, DL, VT,
8578                                     V,
8579                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8580                                                     MVT::i32)));
8581       Res = DAG.getNode(ISD::SUB, DL, VT,
8582                         DAG.getConstant(0, DL, MVT::i32), Res);
8583
8584     } else
8585       return SDValue();
8586   }
8587
8588   if (ShiftAmt != 0)
8589     Res = DAG.getNode(ISD::SHL, DL, VT,
8590                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8591
8592   // Do not add new nodes to DAG combiner worklist.
8593   DCI.CombineTo(N, Res, false);
8594   return SDValue();
8595 }
8596
8597 static SDValue PerformANDCombine(SDNode *N,
8598                                  TargetLowering::DAGCombinerInfo &DCI,
8599                                  const ARMSubtarget *Subtarget) {
8600
8601   // Attempt to use immediate-form VBIC
8602   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8603   SDLoc dl(N);
8604   EVT VT = N->getValueType(0);
8605   SelectionDAG &DAG = DCI.DAG;
8606
8607   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8608     return SDValue();
8609
8610   APInt SplatBits, SplatUndef;
8611   unsigned SplatBitSize;
8612   bool HasAnyUndefs;
8613   if (BVN &&
8614       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8615     if (SplatBitSize <= 64) {
8616       EVT VbicVT;
8617       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8618                                       SplatUndef.getZExtValue(), SplatBitSize,
8619                                       DAG, dl, VbicVT, VT.is128BitVector(),
8620                                       OtherModImm);
8621       if (Val.getNode()) {
8622         SDValue Input =
8623           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8624         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8625         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8626       }
8627     }
8628   }
8629
8630   if (!Subtarget->isThumb1Only()) {
8631     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8632     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8633     if (Result.getNode())
8634       return Result;
8635   }
8636
8637   return SDValue();
8638 }
8639
8640 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8641 static SDValue PerformORCombine(SDNode *N,
8642                                 TargetLowering::DAGCombinerInfo &DCI,
8643                                 const ARMSubtarget *Subtarget) {
8644   // Attempt to use immediate-form VORR
8645   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8646   SDLoc dl(N);
8647   EVT VT = N->getValueType(0);
8648   SelectionDAG &DAG = DCI.DAG;
8649
8650   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8651     return SDValue();
8652
8653   APInt SplatBits, SplatUndef;
8654   unsigned SplatBitSize;
8655   bool HasAnyUndefs;
8656   if (BVN && Subtarget->hasNEON() &&
8657       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8658     if (SplatBitSize <= 64) {
8659       EVT VorrVT;
8660       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8661                                       SplatUndef.getZExtValue(), SplatBitSize,
8662                                       DAG, dl, VorrVT, VT.is128BitVector(),
8663                                       OtherModImm);
8664       if (Val.getNode()) {
8665         SDValue Input =
8666           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8667         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8668         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8669       }
8670     }
8671   }
8672
8673   if (!Subtarget->isThumb1Only()) {
8674     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8675     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8676     if (Result.getNode())
8677       return Result;
8678   }
8679
8680   // The code below optimizes (or (and X, Y), Z).
8681   // The AND operand needs to have a single user to make these optimizations
8682   // profitable.
8683   SDValue N0 = N->getOperand(0);
8684   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8685     return SDValue();
8686   SDValue N1 = N->getOperand(1);
8687
8688   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8689   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8690       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8691     APInt SplatUndef;
8692     unsigned SplatBitSize;
8693     bool HasAnyUndefs;
8694
8695     APInt SplatBits0, SplatBits1;
8696     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8697     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8698     // Ensure that the second operand of both ands are constants
8699     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8700                                       HasAnyUndefs) && !HasAnyUndefs) {
8701         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8702                                           HasAnyUndefs) && !HasAnyUndefs) {
8703             // Ensure that the bit width of the constants are the same and that
8704             // the splat arguments are logical inverses as per the pattern we
8705             // are trying to simplify.
8706             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8707                 SplatBits0 == ~SplatBits1) {
8708                 // Canonicalize the vector type to make instruction selection
8709                 // simpler.
8710                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8711                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8712                                              N0->getOperand(1),
8713                                              N0->getOperand(0),
8714                                              N1->getOperand(0));
8715                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8716             }
8717         }
8718     }
8719   }
8720
8721   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8722   // reasonable.
8723
8724   // BFI is only available on V6T2+
8725   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8726     return SDValue();
8727
8728   SDLoc DL(N);
8729   // 1) or (and A, mask), val => ARMbfi A, val, mask
8730   //      iff (val & mask) == val
8731   //
8732   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8733   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8734   //          && mask == ~mask2
8735   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8736   //          && ~mask == mask2
8737   //  (i.e., copy a bitfield value into another bitfield of the same width)
8738
8739   if (VT != MVT::i32)
8740     return SDValue();
8741
8742   SDValue N00 = N0.getOperand(0);
8743
8744   // The value and the mask need to be constants so we can verify this is
8745   // actually a bitfield set. If the mask is 0xffff, we can do better
8746   // via a movt instruction, so don't use BFI in that case.
8747   SDValue MaskOp = N0.getOperand(1);
8748   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8749   if (!MaskC)
8750     return SDValue();
8751   unsigned Mask = MaskC->getZExtValue();
8752   if (Mask == 0xffff)
8753     return SDValue();
8754   SDValue Res;
8755   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8756   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8757   if (N1C) {
8758     unsigned Val = N1C->getZExtValue();
8759     if ((Val & ~Mask) != Val)
8760       return SDValue();
8761
8762     if (ARM::isBitFieldInvertedMask(Mask)) {
8763       Val >>= countTrailingZeros(~Mask);
8764
8765       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8766                         DAG.getConstant(Val, DL, MVT::i32),
8767                         DAG.getConstant(Mask, DL, MVT::i32));
8768
8769       // Do not add new nodes to DAG combiner worklist.
8770       DCI.CombineTo(N, Res, false);
8771       return SDValue();
8772     }
8773   } else if (N1.getOpcode() == ISD::AND) {
8774     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8775     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8776     if (!N11C)
8777       return SDValue();
8778     unsigned Mask2 = N11C->getZExtValue();
8779
8780     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8781     // as is to match.
8782     if (ARM::isBitFieldInvertedMask(Mask) &&
8783         (Mask == ~Mask2)) {
8784       // The pack halfword instruction works better for masks that fit it,
8785       // so use that when it's available.
8786       if (Subtarget->hasT2ExtractPack() &&
8787           (Mask == 0xffff || Mask == 0xffff0000))
8788         return SDValue();
8789       // 2a
8790       unsigned amt = countTrailingZeros(Mask2);
8791       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8792                         DAG.getConstant(amt, DL, MVT::i32));
8793       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8794                         DAG.getConstant(Mask, DL, MVT::i32));
8795       // Do not add new nodes to DAG combiner worklist.
8796       DCI.CombineTo(N, Res, false);
8797       return SDValue();
8798     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8799                (~Mask == Mask2)) {
8800       // The pack halfword instruction works better for masks that fit it,
8801       // so use that when it's available.
8802       if (Subtarget->hasT2ExtractPack() &&
8803           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8804         return SDValue();
8805       // 2b
8806       unsigned lsb = countTrailingZeros(Mask);
8807       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8808                         DAG.getConstant(lsb, DL, MVT::i32));
8809       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8810                         DAG.getConstant(Mask2, DL, MVT::i32));
8811       // Do not add new nodes to DAG combiner worklist.
8812       DCI.CombineTo(N, Res, false);
8813       return SDValue();
8814     }
8815   }
8816
8817   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8818       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8819       ARM::isBitFieldInvertedMask(~Mask)) {
8820     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8821     // where lsb(mask) == #shamt and masked bits of B are known zero.
8822     SDValue ShAmt = N00.getOperand(1);
8823     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8824     unsigned LSB = countTrailingZeros(Mask);
8825     if (ShAmtC != LSB)
8826       return SDValue();
8827
8828     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8829                       DAG.getConstant(~Mask, DL, MVT::i32));
8830
8831     // Do not add new nodes to DAG combiner worklist.
8832     DCI.CombineTo(N, Res, false);
8833   }
8834
8835   return SDValue();
8836 }
8837
8838 static SDValue PerformXORCombine(SDNode *N,
8839                                  TargetLowering::DAGCombinerInfo &DCI,
8840                                  const ARMSubtarget *Subtarget) {
8841   EVT VT = N->getValueType(0);
8842   SelectionDAG &DAG = DCI.DAG;
8843
8844   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8845     return SDValue();
8846
8847   if (!Subtarget->isThumb1Only()) {
8848     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8849     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8850     if (Result.getNode())
8851       return Result;
8852   }
8853
8854   return SDValue();
8855 }
8856
8857 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8858 /// the bits being cleared by the AND are not demanded by the BFI.
8859 static SDValue PerformBFICombine(SDNode *N,
8860                                  TargetLowering::DAGCombinerInfo &DCI) {
8861   SDValue N1 = N->getOperand(1);
8862   if (N1.getOpcode() == ISD::AND) {
8863     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8864     if (!N11C)
8865       return SDValue();
8866     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8867     unsigned LSB = countTrailingZeros(~InvMask);
8868     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8869     assert(Width <
8870                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8871            "undefined behavior");
8872     unsigned Mask = (1u << Width) - 1;
8873     unsigned Mask2 = N11C->getZExtValue();
8874     if ((Mask & (~Mask2)) == 0)
8875       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8876                              N->getOperand(0), N1.getOperand(0),
8877                              N->getOperand(2));
8878   }
8879   return SDValue();
8880 }
8881
8882 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8883 /// ARMISD::VMOVRRD.
8884 static SDValue PerformVMOVRRDCombine(SDNode *N,
8885                                      TargetLowering::DAGCombinerInfo &DCI,
8886                                      const ARMSubtarget *Subtarget) {
8887   // vmovrrd(vmovdrr x, y) -> x,y
8888   SDValue InDouble = N->getOperand(0);
8889   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8890     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8891
8892   // vmovrrd(load f64) -> (load i32), (load i32)
8893   SDNode *InNode = InDouble.getNode();
8894   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8895       InNode->getValueType(0) == MVT::f64 &&
8896       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8897       !cast<LoadSDNode>(InNode)->isVolatile()) {
8898     // TODO: Should this be done for non-FrameIndex operands?
8899     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8900
8901     SelectionDAG &DAG = DCI.DAG;
8902     SDLoc DL(LD);
8903     SDValue BasePtr = LD->getBasePtr();
8904     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8905                                  LD->getPointerInfo(), LD->isVolatile(),
8906                                  LD->isNonTemporal(), LD->isInvariant(),
8907                                  LD->getAlignment());
8908
8909     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8910                                     DAG.getConstant(4, DL, MVT::i32));
8911     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8912                                  LD->getPointerInfo(), LD->isVolatile(),
8913                                  LD->isNonTemporal(), LD->isInvariant(),
8914                                  std::min(4U, LD->getAlignment() / 2));
8915
8916     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8917     if (DCI.DAG.getDataLayout().isBigEndian())
8918       std::swap (NewLD1, NewLD2);
8919     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8920     return Result;
8921   }
8922
8923   return SDValue();
8924 }
8925
8926 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8927 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8928 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8929   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8930   SDValue Op0 = N->getOperand(0);
8931   SDValue Op1 = N->getOperand(1);
8932   if (Op0.getOpcode() == ISD::BITCAST)
8933     Op0 = Op0.getOperand(0);
8934   if (Op1.getOpcode() == ISD::BITCAST)
8935     Op1 = Op1.getOperand(0);
8936   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8937       Op0.getNode() == Op1.getNode() &&
8938       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8939     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8940                        N->getValueType(0), Op0.getOperand(0));
8941   return SDValue();
8942 }
8943
8944 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8945 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8946 /// i64 vector to have f64 elements, since the value can then be loaded
8947 /// directly into a VFP register.
8948 static bool hasNormalLoadOperand(SDNode *N) {
8949   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8950   for (unsigned i = 0; i < NumElts; ++i) {
8951     SDNode *Elt = N->getOperand(i).getNode();
8952     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8953       return true;
8954   }
8955   return false;
8956 }
8957
8958 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8959 /// ISD::BUILD_VECTOR.
8960 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8961                                           TargetLowering::DAGCombinerInfo &DCI,
8962                                           const ARMSubtarget *Subtarget) {
8963   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8964   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8965   // into a pair of GPRs, which is fine when the value is used as a scalar,
8966   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8967   SelectionDAG &DAG = DCI.DAG;
8968   if (N->getNumOperands() == 2) {
8969     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8970     if (RV.getNode())
8971       return RV;
8972   }
8973
8974   // Load i64 elements as f64 values so that type legalization does not split
8975   // them up into i32 values.
8976   EVT VT = N->getValueType(0);
8977   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8978     return SDValue();
8979   SDLoc dl(N);
8980   SmallVector<SDValue, 8> Ops;
8981   unsigned NumElts = VT.getVectorNumElements();
8982   for (unsigned i = 0; i < NumElts; ++i) {
8983     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8984     Ops.push_back(V);
8985     // Make the DAGCombiner fold the bitcast.
8986     DCI.AddToWorklist(V.getNode());
8987   }
8988   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8989   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8990   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8991 }
8992
8993 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8994 static SDValue
8995 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8996   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8997   // At that time, we may have inserted bitcasts from integer to float.
8998   // If these bitcasts have survived DAGCombine, change the lowering of this
8999   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9000   // force to use floating point types.
9001
9002   // Make sure we can change the type of the vector.
9003   // This is possible iff:
9004   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9005   //    1.1. Vector is used only once.
9006   //    1.2. Use is a bit convert to an integer type.
9007   // 2. The size of its operands are 32-bits (64-bits are not legal).
9008   EVT VT = N->getValueType(0);
9009   EVT EltVT = VT.getVectorElementType();
9010
9011   // Check 1.1. and 2.
9012   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9013     return SDValue();
9014
9015   // By construction, the input type must be float.
9016   assert(EltVT == MVT::f32 && "Unexpected type!");
9017
9018   // Check 1.2.
9019   SDNode *Use = *N->use_begin();
9020   if (Use->getOpcode() != ISD::BITCAST ||
9021       Use->getValueType(0).isFloatingPoint())
9022     return SDValue();
9023
9024   // Check profitability.
9025   // Model is, if more than half of the relevant operands are bitcast from
9026   // i32, turn the build_vector into a sequence of insert_vector_elt.
9027   // Relevant operands are everything that is not statically
9028   // (i.e., at compile time) bitcasted.
9029   unsigned NumOfBitCastedElts = 0;
9030   unsigned NumElts = VT.getVectorNumElements();
9031   unsigned NumOfRelevantElts = NumElts;
9032   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9033     SDValue Elt = N->getOperand(Idx);
9034     if (Elt->getOpcode() == ISD::BITCAST) {
9035       // Assume only bit cast to i32 will go away.
9036       if (Elt->getOperand(0).getValueType() == MVT::i32)
9037         ++NumOfBitCastedElts;
9038     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9039       // Constants are statically casted, thus do not count them as
9040       // relevant operands.
9041       --NumOfRelevantElts;
9042   }
9043
9044   // Check if more than half of the elements require a non-free bitcast.
9045   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9046     return SDValue();
9047
9048   SelectionDAG &DAG = DCI.DAG;
9049   // Create the new vector type.
9050   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9051   // Check if the type is legal.
9052   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9053   if (!TLI.isTypeLegal(VecVT))
9054     return SDValue();
9055
9056   // Combine:
9057   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9058   // => BITCAST INSERT_VECTOR_ELT
9059   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9060   //                      (BITCAST EN), N.
9061   SDValue Vec = DAG.getUNDEF(VecVT);
9062   SDLoc dl(N);
9063   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9064     SDValue V = N->getOperand(Idx);
9065     if (V.getOpcode() == ISD::UNDEF)
9066       continue;
9067     if (V.getOpcode() == ISD::BITCAST &&
9068         V->getOperand(0).getValueType() == MVT::i32)
9069       // Fold obvious case.
9070       V = V.getOperand(0);
9071     else {
9072       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9073       // Make the DAGCombiner fold the bitcasts.
9074       DCI.AddToWorklist(V.getNode());
9075     }
9076     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9077     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9078   }
9079   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9080   // Make the DAGCombiner fold the bitcasts.
9081   DCI.AddToWorklist(Vec.getNode());
9082   return Vec;
9083 }
9084
9085 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9086 /// ISD::INSERT_VECTOR_ELT.
9087 static SDValue PerformInsertEltCombine(SDNode *N,
9088                                        TargetLowering::DAGCombinerInfo &DCI) {
9089   // Bitcast an i64 load inserted into a vector to f64.
9090   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9091   EVT VT = N->getValueType(0);
9092   SDNode *Elt = N->getOperand(1).getNode();
9093   if (VT.getVectorElementType() != MVT::i64 ||
9094       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9095     return SDValue();
9096
9097   SelectionDAG &DAG = DCI.DAG;
9098   SDLoc dl(N);
9099   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9100                                  VT.getVectorNumElements());
9101   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9102   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9103   // Make the DAGCombiner fold the bitcasts.
9104   DCI.AddToWorklist(Vec.getNode());
9105   DCI.AddToWorklist(V.getNode());
9106   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9107                                Vec, V, N->getOperand(2));
9108   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9109 }
9110
9111 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9112 /// ISD::VECTOR_SHUFFLE.
9113 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9114   // The LLVM shufflevector instruction does not require the shuffle mask
9115   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9116   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9117   // operands do not match the mask length, they are extended by concatenating
9118   // them with undef vectors.  That is probably the right thing for other
9119   // targets, but for NEON it is better to concatenate two double-register
9120   // size vector operands into a single quad-register size vector.  Do that
9121   // transformation here:
9122   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9123   //   shuffle(concat(v1, v2), undef)
9124   SDValue Op0 = N->getOperand(0);
9125   SDValue Op1 = N->getOperand(1);
9126   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9127       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9128       Op0.getNumOperands() != 2 ||
9129       Op1.getNumOperands() != 2)
9130     return SDValue();
9131   SDValue Concat0Op1 = Op0.getOperand(1);
9132   SDValue Concat1Op1 = Op1.getOperand(1);
9133   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9134       Concat1Op1.getOpcode() != ISD::UNDEF)
9135     return SDValue();
9136   // Skip the transformation if any of the types are illegal.
9137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9138   EVT VT = N->getValueType(0);
9139   if (!TLI.isTypeLegal(VT) ||
9140       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9141       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9142     return SDValue();
9143
9144   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9145                                   Op0.getOperand(0), Op1.getOperand(0));
9146   // Translate the shuffle mask.
9147   SmallVector<int, 16> NewMask;
9148   unsigned NumElts = VT.getVectorNumElements();
9149   unsigned HalfElts = NumElts/2;
9150   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9151   for (unsigned n = 0; n < NumElts; ++n) {
9152     int MaskElt = SVN->getMaskElt(n);
9153     int NewElt = -1;
9154     if (MaskElt < (int)HalfElts)
9155       NewElt = MaskElt;
9156     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9157       NewElt = HalfElts + MaskElt - NumElts;
9158     NewMask.push_back(NewElt);
9159   }
9160   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9161                               DAG.getUNDEF(VT), NewMask.data());
9162 }
9163
9164 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9165 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9166 /// base address updates.
9167 /// For generic load/stores, the memory type is assumed to be a vector.
9168 /// The caller is assumed to have checked legality.
9169 static SDValue CombineBaseUpdate(SDNode *N,
9170                                  TargetLowering::DAGCombinerInfo &DCI) {
9171   SelectionDAG &DAG = DCI.DAG;
9172   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9173                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9174   const bool isStore = N->getOpcode() == ISD::STORE;
9175   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9176   SDValue Addr = N->getOperand(AddrOpIdx);
9177   MemSDNode *MemN = cast<MemSDNode>(N);
9178   SDLoc dl(N);
9179
9180   // Search for a use of the address operand that is an increment.
9181   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9182          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9183     SDNode *User = *UI;
9184     if (User->getOpcode() != ISD::ADD ||
9185         UI.getUse().getResNo() != Addr.getResNo())
9186       continue;
9187
9188     // Check that the add is independent of the load/store.  Otherwise, folding
9189     // it would create a cycle.
9190     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9191       continue;
9192
9193     // Find the new opcode for the updating load/store.
9194     bool isLoadOp = true;
9195     bool isLaneOp = false;
9196     unsigned NewOpc = 0;
9197     unsigned NumVecs = 0;
9198     if (isIntrinsic) {
9199       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9200       switch (IntNo) {
9201       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9202       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9203         NumVecs = 1; break;
9204       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9205         NumVecs = 2; break;
9206       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9207         NumVecs = 3; break;
9208       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9209         NumVecs = 4; break;
9210       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9211         NumVecs = 2; isLaneOp = true; break;
9212       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9213         NumVecs = 3; isLaneOp = true; break;
9214       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9215         NumVecs = 4; isLaneOp = true; break;
9216       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9217         NumVecs = 1; isLoadOp = false; break;
9218       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9219         NumVecs = 2; isLoadOp = false; break;
9220       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9221         NumVecs = 3; isLoadOp = false; break;
9222       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9223         NumVecs = 4; isLoadOp = false; break;
9224       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9225         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9226       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9227         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9228       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9229         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9230       }
9231     } else {
9232       isLaneOp = true;
9233       switch (N->getOpcode()) {
9234       default: llvm_unreachable("unexpected opcode for Neon base update");
9235       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9236       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9237       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9238       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9239         NumVecs = 1; isLaneOp = false; break;
9240       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9241         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9242       }
9243     }
9244
9245     // Find the size of memory referenced by the load/store.
9246     EVT VecTy;
9247     if (isLoadOp) {
9248       VecTy = N->getValueType(0);
9249     } else if (isIntrinsic) {
9250       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9251     } else {
9252       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9253       VecTy = N->getOperand(1).getValueType();
9254     }
9255
9256     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9257     if (isLaneOp)
9258       NumBytes /= VecTy.getVectorNumElements();
9259
9260     // If the increment is a constant, it must match the memory ref size.
9261     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9262     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9263       uint64_t IncVal = CInc->getZExtValue();
9264       if (IncVal != NumBytes)
9265         continue;
9266     } else if (NumBytes >= 3 * 16) {
9267       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9268       // separate instructions that make it harder to use a non-constant update.
9269       continue;
9270     }
9271
9272     // OK, we found an ADD we can fold into the base update.
9273     // Now, create a _UPD node, taking care of not breaking alignment.
9274
9275     EVT AlignedVecTy = VecTy;
9276     unsigned Alignment = MemN->getAlignment();
9277
9278     // If this is a less-than-standard-aligned load/store, change the type to
9279     // match the standard alignment.
9280     // The alignment is overlooked when selecting _UPD variants; and it's
9281     // easier to introduce bitcasts here than fix that.
9282     // There are 3 ways to get to this base-update combine:
9283     // - intrinsics: they are assumed to be properly aligned (to the standard
9284     //   alignment of the memory type), so we don't need to do anything.
9285     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9286     //   intrinsics, so, likewise, there's nothing to do.
9287     // - generic load/store instructions: the alignment is specified as an
9288     //   explicit operand, rather than implicitly as the standard alignment
9289     //   of the memory type (like the intrisics).  We need to change the
9290     //   memory type to match the explicit alignment.  That way, we don't
9291     //   generate non-standard-aligned ARMISD::VLDx nodes.
9292     if (isa<LSBaseSDNode>(N)) {
9293       if (Alignment == 0)
9294         Alignment = 1;
9295       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9296         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9297         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9298         assert(!isLaneOp && "Unexpected generic load/store lane.");
9299         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9300         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9301       }
9302       // Don't set an explicit alignment on regular load/stores that we want
9303       // to transform to VLD/VST 1_UPD nodes.
9304       // This matches the behavior of regular load/stores, which only get an
9305       // explicit alignment if the MMO alignment is larger than the standard
9306       // alignment of the memory type.
9307       // Intrinsics, however, always get an explicit alignment, set to the
9308       // alignment of the MMO.
9309       Alignment = 1;
9310     }
9311
9312     // Create the new updating load/store node.
9313     // First, create an SDVTList for the new updating node's results.
9314     EVT Tys[6];
9315     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9316     unsigned n;
9317     for (n = 0; n < NumResultVecs; ++n)
9318       Tys[n] = AlignedVecTy;
9319     Tys[n++] = MVT::i32;
9320     Tys[n] = MVT::Other;
9321     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9322
9323     // Then, gather the new node's operands.
9324     SmallVector<SDValue, 8> Ops;
9325     Ops.push_back(N->getOperand(0)); // incoming chain
9326     Ops.push_back(N->getOperand(AddrOpIdx));
9327     Ops.push_back(Inc);
9328
9329     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9330       // Try to match the intrinsic's signature
9331       Ops.push_back(StN->getValue());
9332     } else {
9333       // Loads (and of course intrinsics) match the intrinsics' signature,
9334       // so just add all but the alignment operand.
9335       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9336         Ops.push_back(N->getOperand(i));
9337     }
9338
9339     // For all node types, the alignment operand is always the last one.
9340     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9341
9342     // If this is a non-standard-aligned STORE, the penultimate operand is the
9343     // stored value.  Bitcast it to the aligned type.
9344     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9345       SDValue &StVal = Ops[Ops.size()-2];
9346       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9347     }
9348
9349     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9350                                            Ops, AlignedVecTy,
9351                                            MemN->getMemOperand());
9352
9353     // Update the uses.
9354     SmallVector<SDValue, 5> NewResults;
9355     for (unsigned i = 0; i < NumResultVecs; ++i)
9356       NewResults.push_back(SDValue(UpdN.getNode(), i));
9357
9358     // If this is an non-standard-aligned LOAD, the first result is the loaded
9359     // value.  Bitcast it to the expected result type.
9360     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9361       SDValue &LdVal = NewResults[0];
9362       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9363     }
9364
9365     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9366     DCI.CombineTo(N, NewResults);
9367     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9368
9369     break;
9370   }
9371   return SDValue();
9372 }
9373
9374 static SDValue PerformVLDCombine(SDNode *N,
9375                                  TargetLowering::DAGCombinerInfo &DCI) {
9376   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9377     return SDValue();
9378
9379   return CombineBaseUpdate(N, DCI);
9380 }
9381
9382 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9383 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9384 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9385 /// return true.
9386 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9387   SelectionDAG &DAG = DCI.DAG;
9388   EVT VT = N->getValueType(0);
9389   // vldN-dup instructions only support 64-bit vectors for N > 1.
9390   if (!VT.is64BitVector())
9391     return false;
9392
9393   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9394   SDNode *VLD = N->getOperand(0).getNode();
9395   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9396     return false;
9397   unsigned NumVecs = 0;
9398   unsigned NewOpc = 0;
9399   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9400   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9401     NumVecs = 2;
9402     NewOpc = ARMISD::VLD2DUP;
9403   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9404     NumVecs = 3;
9405     NewOpc = ARMISD::VLD3DUP;
9406   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9407     NumVecs = 4;
9408     NewOpc = ARMISD::VLD4DUP;
9409   } else {
9410     return false;
9411   }
9412
9413   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9414   // numbers match the load.
9415   unsigned VLDLaneNo =
9416     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9417   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9418        UI != UE; ++UI) {
9419     // Ignore uses of the chain result.
9420     if (UI.getUse().getResNo() == NumVecs)
9421       continue;
9422     SDNode *User = *UI;
9423     if (User->getOpcode() != ARMISD::VDUPLANE ||
9424         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9425       return false;
9426   }
9427
9428   // Create the vldN-dup node.
9429   EVT Tys[5];
9430   unsigned n;
9431   for (n = 0; n < NumVecs; ++n)
9432     Tys[n] = VT;
9433   Tys[n] = MVT::Other;
9434   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9435   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9436   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9437   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9438                                            Ops, VLDMemInt->getMemoryVT(),
9439                                            VLDMemInt->getMemOperand());
9440
9441   // Update the uses.
9442   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9443        UI != UE; ++UI) {
9444     unsigned ResNo = UI.getUse().getResNo();
9445     // Ignore uses of the chain result.
9446     if (ResNo == NumVecs)
9447       continue;
9448     SDNode *User = *UI;
9449     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9450   }
9451
9452   // Now the vldN-lane intrinsic is dead except for its chain result.
9453   // Update uses of the chain.
9454   std::vector<SDValue> VLDDupResults;
9455   for (unsigned n = 0; n < NumVecs; ++n)
9456     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9457   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9458   DCI.CombineTo(VLD, VLDDupResults);
9459
9460   return true;
9461 }
9462
9463 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9464 /// ARMISD::VDUPLANE.
9465 static SDValue PerformVDUPLANECombine(SDNode *N,
9466                                       TargetLowering::DAGCombinerInfo &DCI) {
9467   SDValue Op = N->getOperand(0);
9468
9469   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9470   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9471   if (CombineVLDDUP(N, DCI))
9472     return SDValue(N, 0);
9473
9474   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9475   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9476   while (Op.getOpcode() == ISD::BITCAST)
9477     Op = Op.getOperand(0);
9478   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9479     return SDValue();
9480
9481   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9482   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9483   // The canonical VMOV for a zero vector uses a 32-bit element size.
9484   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9485   unsigned EltBits;
9486   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9487     EltSize = 8;
9488   EVT VT = N->getValueType(0);
9489   if (EltSize > VT.getVectorElementType().getSizeInBits())
9490     return SDValue();
9491
9492   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9493 }
9494
9495 static SDValue PerformLOADCombine(SDNode *N,
9496                                   TargetLowering::DAGCombinerInfo &DCI) {
9497   EVT VT = N->getValueType(0);
9498
9499   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9500   if (ISD::isNormalLoad(N) && VT.isVector() &&
9501       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9502     return CombineBaseUpdate(N, DCI);
9503
9504   return SDValue();
9505 }
9506
9507 /// PerformSTORECombine - Target-specific dag combine xforms for
9508 /// ISD::STORE.
9509 static SDValue PerformSTORECombine(SDNode *N,
9510                                    TargetLowering::DAGCombinerInfo &DCI) {
9511   StoreSDNode *St = cast<StoreSDNode>(N);
9512   if (St->isVolatile())
9513     return SDValue();
9514
9515   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9516   // pack all of the elements in one place.  Next, store to memory in fewer
9517   // chunks.
9518   SDValue StVal = St->getValue();
9519   EVT VT = StVal.getValueType();
9520   if (St->isTruncatingStore() && VT.isVector()) {
9521     SelectionDAG &DAG = DCI.DAG;
9522     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9523     EVT StVT = St->getMemoryVT();
9524     unsigned NumElems = VT.getVectorNumElements();
9525     assert(StVT != VT && "Cannot truncate to the same type");
9526     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9527     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9528
9529     // From, To sizes and ElemCount must be pow of two
9530     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9531
9532     // We are going to use the original vector elt for storing.
9533     // Accumulated smaller vector elements must be a multiple of the store size.
9534     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9535
9536     unsigned SizeRatio  = FromEltSz / ToEltSz;
9537     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9538
9539     // Create a type on which we perform the shuffle.
9540     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9541                                      NumElems*SizeRatio);
9542     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9543
9544     SDLoc DL(St);
9545     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9546     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9547     for (unsigned i = 0; i < NumElems; ++i)
9548       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9549                           ? (i + 1) * SizeRatio - 1
9550                           : i * SizeRatio;
9551
9552     // Can't shuffle using an illegal type.
9553     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9554
9555     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9556                                 DAG.getUNDEF(WideVec.getValueType()),
9557                                 ShuffleVec.data());
9558     // At this point all of the data is stored at the bottom of the
9559     // register. We now need to save it to mem.
9560
9561     // Find the largest store unit
9562     MVT StoreType = MVT::i8;
9563     for (MVT Tp : MVT::integer_valuetypes()) {
9564       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9565         StoreType = Tp;
9566     }
9567     // Didn't find a legal store type.
9568     if (!TLI.isTypeLegal(StoreType))
9569       return SDValue();
9570
9571     // Bitcast the original vector into a vector of store-size units
9572     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9573             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9574     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9575     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9576     SmallVector<SDValue, 8> Chains;
9577     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9578                                         TLI.getPointerTy(DAG.getDataLayout()));
9579     SDValue BasePtr = St->getBasePtr();
9580
9581     // Perform one or more big stores into memory.
9582     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9583     for (unsigned I = 0; I < E; I++) {
9584       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9585                                    StoreType, ShuffWide,
9586                                    DAG.getIntPtrConstant(I, DL));
9587       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9588                                 St->getPointerInfo(), St->isVolatile(),
9589                                 St->isNonTemporal(), St->getAlignment());
9590       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9591                             Increment);
9592       Chains.push_back(Ch);
9593     }
9594     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9595   }
9596
9597   if (!ISD::isNormalStore(St))
9598     return SDValue();
9599
9600   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9601   // ARM stores of arguments in the same cache line.
9602   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9603       StVal.getNode()->hasOneUse()) {
9604     SelectionDAG  &DAG = DCI.DAG;
9605     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9606     SDLoc DL(St);
9607     SDValue BasePtr = St->getBasePtr();
9608     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9609                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9610                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9611                                   St->isNonTemporal(), St->getAlignment());
9612
9613     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9614                                     DAG.getConstant(4, DL, MVT::i32));
9615     return DAG.getStore(NewST1.getValue(0), DL,
9616                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9617                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9618                         St->isNonTemporal(),
9619                         std::min(4U, St->getAlignment() / 2));
9620   }
9621
9622   if (StVal.getValueType() == MVT::i64 &&
9623       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9624
9625     // Bitcast an i64 store extracted from a vector to f64.
9626     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9627     SelectionDAG &DAG = DCI.DAG;
9628     SDLoc dl(StVal);
9629     SDValue IntVec = StVal.getOperand(0);
9630     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9631                                    IntVec.getValueType().getVectorNumElements());
9632     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9633     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9634                                  Vec, StVal.getOperand(1));
9635     dl = SDLoc(N);
9636     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9637     // Make the DAGCombiner fold the bitcasts.
9638     DCI.AddToWorklist(Vec.getNode());
9639     DCI.AddToWorklist(ExtElt.getNode());
9640     DCI.AddToWorklist(V.getNode());
9641     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9642                         St->getPointerInfo(), St->isVolatile(),
9643                         St->isNonTemporal(), St->getAlignment(),
9644                         St->getAAInfo());
9645   }
9646
9647   // If this is a legal vector store, try to combine it into a VST1_UPD.
9648   if (ISD::isNormalStore(N) && VT.isVector() &&
9649       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9650     return CombineBaseUpdate(N, DCI);
9651
9652   return SDValue();
9653 }
9654
9655 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9656 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9657 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9658 {
9659   integerPart cN;
9660   integerPart c0 = 0;
9661   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9662        I != E; I++) {
9663     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9664     if (!C)
9665       return false;
9666
9667     bool isExact;
9668     APFloat APF = C->getValueAPF();
9669     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9670         != APFloat::opOK || !isExact)
9671       return false;
9672
9673     c0 = (I == 0) ? cN : c0;
9674     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9675       return false;
9676   }
9677   C = c0;
9678   return true;
9679 }
9680
9681 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9682 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9683 /// when the VMUL has a constant operand that is a power of 2.
9684 ///
9685 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9686 ///  vmul.f32        d16, d17, d16
9687 ///  vcvt.s32.f32    d16, d16
9688 /// becomes:
9689 ///  vcvt.s32.f32    d16, d16, #3
9690 static SDValue PerformVCVTCombine(SDNode *N,
9691                                   TargetLowering::DAGCombinerInfo &DCI,
9692                                   const ARMSubtarget *Subtarget) {
9693   SelectionDAG &DAG = DCI.DAG;
9694   SDValue Op = N->getOperand(0);
9695
9696   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9697       Op.getOpcode() != ISD::FMUL)
9698     return SDValue();
9699
9700   uint64_t C;
9701   SDValue N0 = Op->getOperand(0);
9702   SDValue ConstVec = Op->getOperand(1);
9703   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9704
9705   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9706       !isConstVecPow2(ConstVec, isSigned, C))
9707     return SDValue();
9708
9709   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9710   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9711   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9712   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9713       NumLanes > 4) {
9714     // These instructions only exist converting from f32 to i32. We can handle
9715     // smaller integers by generating an extra truncate, but larger ones would
9716     // be lossy. We also can't handle more then 4 lanes, since these intructions
9717     // only support v2i32/v4i32 types.
9718     return SDValue();
9719   }
9720
9721   SDLoc dl(N);
9722   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9723     Intrinsic::arm_neon_vcvtfp2fxu;
9724   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9725                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9726                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9727                                  N0,
9728                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9729
9730   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9731     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9732
9733   return FixConv;
9734 }
9735
9736 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9737 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9738 /// when the VDIV has a constant operand that is a power of 2.
9739 ///
9740 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9741 ///  vcvt.f32.s32    d16, d16
9742 ///  vdiv.f32        d16, d17, d16
9743 /// becomes:
9744 ///  vcvt.f32.s32    d16, d16, #3
9745 static SDValue PerformVDIVCombine(SDNode *N,
9746                                   TargetLowering::DAGCombinerInfo &DCI,
9747                                   const ARMSubtarget *Subtarget) {
9748   SelectionDAG &DAG = DCI.DAG;
9749   SDValue Op = N->getOperand(0);
9750   unsigned OpOpcode = Op.getNode()->getOpcode();
9751
9752   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9753       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9754     return SDValue();
9755
9756   uint64_t C;
9757   SDValue ConstVec = N->getOperand(1);
9758   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9759
9760   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9761       !isConstVecPow2(ConstVec, isSigned, C))
9762     return SDValue();
9763
9764   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9765   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9766   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9767     // These instructions only exist converting from i32 to f32. We can handle
9768     // smaller integers by generating an extra extend, but larger ones would
9769     // be lossy.
9770     return SDValue();
9771   }
9772
9773   SDLoc dl(N);
9774   SDValue ConvInput = Op.getOperand(0);
9775   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9776   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9777     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9778                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9779                             ConvInput);
9780
9781   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9782     Intrinsic::arm_neon_vcvtfxu2fp;
9783   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9784                      Op.getValueType(),
9785                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9786                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9787 }
9788
9789 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9790 /// operand of a vector shift operation, where all the elements of the
9791 /// build_vector must have the same constant integer value.
9792 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9793   // Ignore bit_converts.
9794   while (Op.getOpcode() == ISD::BITCAST)
9795     Op = Op.getOperand(0);
9796   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9797   APInt SplatBits, SplatUndef;
9798   unsigned SplatBitSize;
9799   bool HasAnyUndefs;
9800   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9801                                       HasAnyUndefs, ElementBits) ||
9802       SplatBitSize > ElementBits)
9803     return false;
9804   Cnt = SplatBits.getSExtValue();
9805   return true;
9806 }
9807
9808 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9809 /// operand of a vector shift left operation.  That value must be in the range:
9810 ///   0 <= Value < ElementBits for a left shift; or
9811 ///   0 <= Value <= ElementBits for a long left shift.
9812 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9813   assert(VT.isVector() && "vector shift count is not a vector type");
9814   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9815   if (! getVShiftImm(Op, ElementBits, Cnt))
9816     return false;
9817   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9818 }
9819
9820 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9821 /// operand of a vector shift right operation.  For a shift opcode, the value
9822 /// is positive, but for an intrinsic the value count must be negative. The
9823 /// absolute value must be in the range:
9824 ///   1 <= |Value| <= ElementBits for a right shift; or
9825 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9826 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9827                          int64_t &Cnt) {
9828   assert(VT.isVector() && "vector shift count is not a vector type");
9829   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9830   if (! getVShiftImm(Op, ElementBits, Cnt))
9831     return false;
9832   if (!isIntrinsic)
9833     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9834   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9835     Cnt = -Cnt;
9836     return true;
9837   }
9838   return false;
9839 }
9840
9841 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9842 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9843   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9844   switch (IntNo) {
9845   default:
9846     // Don't do anything for most intrinsics.
9847     break;
9848
9849   case Intrinsic::arm_neon_vabds:
9850     if (!N->getValueType(0).isInteger())
9851       return SDValue();
9852     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9853                        N->getOperand(1), N->getOperand(2));
9854   case Intrinsic::arm_neon_vabdu:
9855     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9856                        N->getOperand(1), N->getOperand(2));
9857
9858   // Vector shifts: check for immediate versions and lower them.
9859   // Note: This is done during DAG combining instead of DAG legalizing because
9860   // the build_vectors for 64-bit vector element shift counts are generally
9861   // not legal, and it is hard to see their values after they get legalized to
9862   // loads from a constant pool.
9863   case Intrinsic::arm_neon_vshifts:
9864   case Intrinsic::arm_neon_vshiftu:
9865   case Intrinsic::arm_neon_vrshifts:
9866   case Intrinsic::arm_neon_vrshiftu:
9867   case Intrinsic::arm_neon_vrshiftn:
9868   case Intrinsic::arm_neon_vqshifts:
9869   case Intrinsic::arm_neon_vqshiftu:
9870   case Intrinsic::arm_neon_vqshiftsu:
9871   case Intrinsic::arm_neon_vqshiftns:
9872   case Intrinsic::arm_neon_vqshiftnu:
9873   case Intrinsic::arm_neon_vqshiftnsu:
9874   case Intrinsic::arm_neon_vqrshiftns:
9875   case Intrinsic::arm_neon_vqrshiftnu:
9876   case Intrinsic::arm_neon_vqrshiftnsu: {
9877     EVT VT = N->getOperand(1).getValueType();
9878     int64_t Cnt;
9879     unsigned VShiftOpc = 0;
9880
9881     switch (IntNo) {
9882     case Intrinsic::arm_neon_vshifts:
9883     case Intrinsic::arm_neon_vshiftu:
9884       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9885         VShiftOpc = ARMISD::VSHL;
9886         break;
9887       }
9888       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9889         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9890                      ARMISD::VSHRs : ARMISD::VSHRu);
9891         break;
9892       }
9893       return SDValue();
9894
9895     case Intrinsic::arm_neon_vrshifts:
9896     case Intrinsic::arm_neon_vrshiftu:
9897       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9898         break;
9899       return SDValue();
9900
9901     case Intrinsic::arm_neon_vqshifts:
9902     case Intrinsic::arm_neon_vqshiftu:
9903       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9904         break;
9905       return SDValue();
9906
9907     case Intrinsic::arm_neon_vqshiftsu:
9908       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9909         break;
9910       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9911
9912     case Intrinsic::arm_neon_vrshiftn:
9913     case Intrinsic::arm_neon_vqshiftns:
9914     case Intrinsic::arm_neon_vqshiftnu:
9915     case Intrinsic::arm_neon_vqshiftnsu:
9916     case Intrinsic::arm_neon_vqrshiftns:
9917     case Intrinsic::arm_neon_vqrshiftnu:
9918     case Intrinsic::arm_neon_vqrshiftnsu:
9919       // Narrowing shifts require an immediate right shift.
9920       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9921         break;
9922       llvm_unreachable("invalid shift count for narrowing vector shift "
9923                        "intrinsic");
9924
9925     default:
9926       llvm_unreachable("unhandled vector shift");
9927     }
9928
9929     switch (IntNo) {
9930     case Intrinsic::arm_neon_vshifts:
9931     case Intrinsic::arm_neon_vshiftu:
9932       // Opcode already set above.
9933       break;
9934     case Intrinsic::arm_neon_vrshifts:
9935       VShiftOpc = ARMISD::VRSHRs; break;
9936     case Intrinsic::arm_neon_vrshiftu:
9937       VShiftOpc = ARMISD::VRSHRu; break;
9938     case Intrinsic::arm_neon_vrshiftn:
9939       VShiftOpc = ARMISD::VRSHRN; break;
9940     case Intrinsic::arm_neon_vqshifts:
9941       VShiftOpc = ARMISD::VQSHLs; break;
9942     case Intrinsic::arm_neon_vqshiftu:
9943       VShiftOpc = ARMISD::VQSHLu; break;
9944     case Intrinsic::arm_neon_vqshiftsu:
9945       VShiftOpc = ARMISD::VQSHLsu; break;
9946     case Intrinsic::arm_neon_vqshiftns:
9947       VShiftOpc = ARMISD::VQSHRNs; break;
9948     case Intrinsic::arm_neon_vqshiftnu:
9949       VShiftOpc = ARMISD::VQSHRNu; break;
9950     case Intrinsic::arm_neon_vqshiftnsu:
9951       VShiftOpc = ARMISD::VQSHRNsu; break;
9952     case Intrinsic::arm_neon_vqrshiftns:
9953       VShiftOpc = ARMISD::VQRSHRNs; break;
9954     case Intrinsic::arm_neon_vqrshiftnu:
9955       VShiftOpc = ARMISD::VQRSHRNu; break;
9956     case Intrinsic::arm_neon_vqrshiftnsu:
9957       VShiftOpc = ARMISD::VQRSHRNsu; break;
9958     }
9959
9960     SDLoc dl(N);
9961     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9962                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9963   }
9964
9965   case Intrinsic::arm_neon_vshiftins: {
9966     EVT VT = N->getOperand(1).getValueType();
9967     int64_t Cnt;
9968     unsigned VShiftOpc = 0;
9969
9970     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9971       VShiftOpc = ARMISD::VSLI;
9972     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9973       VShiftOpc = ARMISD::VSRI;
9974     else {
9975       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9976     }
9977
9978     SDLoc dl(N);
9979     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9980                        N->getOperand(1), N->getOperand(2),
9981                        DAG.getConstant(Cnt, dl, MVT::i32));
9982   }
9983
9984   case Intrinsic::arm_neon_vqrshifts:
9985   case Intrinsic::arm_neon_vqrshiftu:
9986     // No immediate versions of these to check for.
9987     break;
9988   }
9989
9990   return SDValue();
9991 }
9992
9993 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9994 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9995 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9996 /// vector element shift counts are generally not legal, and it is hard to see
9997 /// their values after they get legalized to loads from a constant pool.
9998 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9999                                    const ARMSubtarget *ST) {
10000   EVT VT = N->getValueType(0);
10001   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10002     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10003     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10004     SDValue N1 = N->getOperand(1);
10005     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10006       SDValue N0 = N->getOperand(0);
10007       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10008           DAG.MaskedValueIsZero(N0.getOperand(0),
10009                                 APInt::getHighBitsSet(32, 16)))
10010         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10011     }
10012   }
10013
10014   // Nothing to be done for scalar shifts.
10015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10016   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10017     return SDValue();
10018
10019   assert(ST->hasNEON() && "unexpected vector shift");
10020   int64_t Cnt;
10021
10022   switch (N->getOpcode()) {
10023   default: llvm_unreachable("unexpected shift opcode");
10024
10025   case ISD::SHL:
10026     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10027       SDLoc dl(N);
10028       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10029                          DAG.getConstant(Cnt, dl, MVT::i32));
10030     }
10031     break;
10032
10033   case ISD::SRA:
10034   case ISD::SRL:
10035     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10036       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10037                             ARMISD::VSHRs : ARMISD::VSHRu);
10038       SDLoc dl(N);
10039       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10040                          DAG.getConstant(Cnt, dl, MVT::i32));
10041     }
10042   }
10043   return SDValue();
10044 }
10045
10046 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10047 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10048 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10049                                     const ARMSubtarget *ST) {
10050   SDValue N0 = N->getOperand(0);
10051
10052   // Check for sign- and zero-extensions of vector extract operations of 8-
10053   // and 16-bit vector elements.  NEON supports these directly.  They are
10054   // handled during DAG combining because type legalization will promote them
10055   // to 32-bit types and it is messy to recognize the operations after that.
10056   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10057     SDValue Vec = N0.getOperand(0);
10058     SDValue Lane = N0.getOperand(1);
10059     EVT VT = N->getValueType(0);
10060     EVT EltVT = N0.getValueType();
10061     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10062
10063     if (VT == MVT::i32 &&
10064         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10065         TLI.isTypeLegal(Vec.getValueType()) &&
10066         isa<ConstantSDNode>(Lane)) {
10067
10068       unsigned Opc = 0;
10069       switch (N->getOpcode()) {
10070       default: llvm_unreachable("unexpected opcode");
10071       case ISD::SIGN_EXTEND:
10072         Opc = ARMISD::VGETLANEs;
10073         break;
10074       case ISD::ZERO_EXTEND:
10075       case ISD::ANY_EXTEND:
10076         Opc = ARMISD::VGETLANEu;
10077         break;
10078       }
10079       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10080     }
10081   }
10082
10083   return SDValue();
10084 }
10085
10086 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10087 SDValue
10088 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10089   SDValue Cmp = N->getOperand(4);
10090   if (Cmp.getOpcode() != ARMISD::CMPZ)
10091     // Only looking at EQ and NE cases.
10092     return SDValue();
10093
10094   EVT VT = N->getValueType(0);
10095   SDLoc dl(N);
10096   SDValue LHS = Cmp.getOperand(0);
10097   SDValue RHS = Cmp.getOperand(1);
10098   SDValue FalseVal = N->getOperand(0);
10099   SDValue TrueVal = N->getOperand(1);
10100   SDValue ARMcc = N->getOperand(2);
10101   ARMCC::CondCodes CC =
10102     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10103
10104   // Simplify
10105   //   mov     r1, r0
10106   //   cmp     r1, x
10107   //   mov     r0, y
10108   //   moveq   r0, x
10109   // to
10110   //   cmp     r0, x
10111   //   movne   r0, y
10112   //
10113   //   mov     r1, r0
10114   //   cmp     r1, x
10115   //   mov     r0, x
10116   //   movne   r0, y
10117   // to
10118   //   cmp     r0, x
10119   //   movne   r0, y
10120   /// FIXME: Turn this into a target neutral optimization?
10121   SDValue Res;
10122   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10123     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10124                       N->getOperand(3), Cmp);
10125   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10126     SDValue ARMcc;
10127     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10128     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10129                       N->getOperand(3), NewCmp);
10130   }
10131
10132   if (Res.getNode()) {
10133     APInt KnownZero, KnownOne;
10134     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10135     // Capture demanded bits information that would be otherwise lost.
10136     if (KnownZero == 0xfffffffe)
10137       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10138                         DAG.getValueType(MVT::i1));
10139     else if (KnownZero == 0xffffff00)
10140       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10141                         DAG.getValueType(MVT::i8));
10142     else if (KnownZero == 0xffff0000)
10143       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10144                         DAG.getValueType(MVT::i16));
10145   }
10146
10147   return Res;
10148 }
10149
10150 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10151                                              DAGCombinerInfo &DCI) const {
10152   switch (N->getOpcode()) {
10153   default: break;
10154   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10155   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10156   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10157   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10158   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10159   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10160   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10161   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10162   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10163   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10164   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10165   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10166   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10167   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10168   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10169   case ISD::FP_TO_SINT:
10170   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10171   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10172   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10173   case ISD::SHL:
10174   case ISD::SRA:
10175   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10176   case ISD::SIGN_EXTEND:
10177   case ISD::ZERO_EXTEND:
10178   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10179   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10180   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10181   case ARMISD::VLD2DUP:
10182   case ARMISD::VLD3DUP:
10183   case ARMISD::VLD4DUP:
10184     return PerformVLDCombine(N, DCI);
10185   case ARMISD::BUILD_VECTOR:
10186     return PerformARMBUILD_VECTORCombine(N, DCI);
10187   case ISD::INTRINSIC_VOID:
10188   case ISD::INTRINSIC_W_CHAIN:
10189     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10190     case Intrinsic::arm_neon_vld1:
10191     case Intrinsic::arm_neon_vld2:
10192     case Intrinsic::arm_neon_vld3:
10193     case Intrinsic::arm_neon_vld4:
10194     case Intrinsic::arm_neon_vld2lane:
10195     case Intrinsic::arm_neon_vld3lane:
10196     case Intrinsic::arm_neon_vld4lane:
10197     case Intrinsic::arm_neon_vst1:
10198     case Intrinsic::arm_neon_vst2:
10199     case Intrinsic::arm_neon_vst3:
10200     case Intrinsic::arm_neon_vst4:
10201     case Intrinsic::arm_neon_vst2lane:
10202     case Intrinsic::arm_neon_vst3lane:
10203     case Intrinsic::arm_neon_vst4lane:
10204       return PerformVLDCombine(N, DCI);
10205     default: break;
10206     }
10207     break;
10208   }
10209   return SDValue();
10210 }
10211
10212 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10213                                                           EVT VT) const {
10214   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10215 }
10216
10217 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10218                                                        unsigned,
10219                                                        unsigned,
10220                                                        bool *Fast) const {
10221   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10222   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10223
10224   switch (VT.getSimpleVT().SimpleTy) {
10225   default:
10226     return false;
10227   case MVT::i8:
10228   case MVT::i16:
10229   case MVT::i32: {
10230     // Unaligned access can use (for example) LRDB, LRDH, LDR
10231     if (AllowsUnaligned) {
10232       if (Fast)
10233         *Fast = Subtarget->hasV7Ops();
10234       return true;
10235     }
10236     return false;
10237   }
10238   case MVT::f64:
10239   case MVT::v2f64: {
10240     // For any little-endian targets with neon, we can support unaligned ld/st
10241     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10242     // A big-endian target may also explicitly support unaligned accesses
10243     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10244       if (Fast)
10245         *Fast = true;
10246       return true;
10247     }
10248     return false;
10249   }
10250   }
10251 }
10252
10253 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10254                        unsigned AlignCheck) {
10255   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10256           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10257 }
10258
10259 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10260                                            unsigned DstAlign, unsigned SrcAlign,
10261                                            bool IsMemset, bool ZeroMemset,
10262                                            bool MemcpyStrSrc,
10263                                            MachineFunction &MF) const {
10264   const Function *F = MF.getFunction();
10265
10266   // See if we can use NEON instructions for this...
10267   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10268       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10269     bool Fast;
10270     if (Size >= 16 &&
10271         (memOpAlign(SrcAlign, DstAlign, 16) ||
10272          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10273       return MVT::v2f64;
10274     } else if (Size >= 8 &&
10275                (memOpAlign(SrcAlign, DstAlign, 8) ||
10276                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10277                  Fast))) {
10278       return MVT::f64;
10279     }
10280   }
10281
10282   // Lowering to i32/i16 if the size permits.
10283   if (Size >= 4)
10284     return MVT::i32;
10285   else if (Size >= 2)
10286     return MVT::i16;
10287
10288   // Let the target-independent logic figure it out.
10289   return MVT::Other;
10290 }
10291
10292 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10293   if (Val.getOpcode() != ISD::LOAD)
10294     return false;
10295
10296   EVT VT1 = Val.getValueType();
10297   if (!VT1.isSimple() || !VT1.isInteger() ||
10298       !VT2.isSimple() || !VT2.isInteger())
10299     return false;
10300
10301   switch (VT1.getSimpleVT().SimpleTy) {
10302   default: break;
10303   case MVT::i1:
10304   case MVT::i8:
10305   case MVT::i16:
10306     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10307     return true;
10308   }
10309
10310   return false;
10311 }
10312
10313 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10314   EVT VT = ExtVal.getValueType();
10315
10316   if (!isTypeLegal(VT))
10317     return false;
10318
10319   // Don't create a loadext if we can fold the extension into a wide/long
10320   // instruction.
10321   // If there's more than one user instruction, the loadext is desirable no
10322   // matter what.  There can be two uses by the same instruction.
10323   if (ExtVal->use_empty() ||
10324       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10325     return true;
10326
10327   SDNode *U = *ExtVal->use_begin();
10328   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10329        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10330     return false;
10331
10332   return true;
10333 }
10334
10335 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10336   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10337     return false;
10338
10339   if (!isTypeLegal(EVT::getEVT(Ty1)))
10340     return false;
10341
10342   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10343
10344   // Assuming the caller doesn't have a zeroext or signext return parameter,
10345   // truncation all the way down to i1 is valid.
10346   return true;
10347 }
10348
10349
10350 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10351   if (V < 0)
10352     return false;
10353
10354   unsigned Scale = 1;
10355   switch (VT.getSimpleVT().SimpleTy) {
10356   default: return false;
10357   case MVT::i1:
10358   case MVT::i8:
10359     // Scale == 1;
10360     break;
10361   case MVT::i16:
10362     // Scale == 2;
10363     Scale = 2;
10364     break;
10365   case MVT::i32:
10366     // Scale == 4;
10367     Scale = 4;
10368     break;
10369   }
10370
10371   if ((V & (Scale - 1)) != 0)
10372     return false;
10373   V /= Scale;
10374   return V == (V & ((1LL << 5) - 1));
10375 }
10376
10377 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10378                                       const ARMSubtarget *Subtarget) {
10379   bool isNeg = false;
10380   if (V < 0) {
10381     isNeg = true;
10382     V = - V;
10383   }
10384
10385   switch (VT.getSimpleVT().SimpleTy) {
10386   default: return false;
10387   case MVT::i1:
10388   case MVT::i8:
10389   case MVT::i16:
10390   case MVT::i32:
10391     // + imm12 or - imm8
10392     if (isNeg)
10393       return V == (V & ((1LL << 8) - 1));
10394     return V == (V & ((1LL << 12) - 1));
10395   case MVT::f32:
10396   case MVT::f64:
10397     // Same as ARM mode. FIXME: NEON?
10398     if (!Subtarget->hasVFP2())
10399       return false;
10400     if ((V & 3) != 0)
10401       return false;
10402     V >>= 2;
10403     return V == (V & ((1LL << 8) - 1));
10404   }
10405 }
10406
10407 /// isLegalAddressImmediate - Return true if the integer value can be used
10408 /// as the offset of the target addressing mode for load / store of the
10409 /// given type.
10410 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10411                                     const ARMSubtarget *Subtarget) {
10412   if (V == 0)
10413     return true;
10414
10415   if (!VT.isSimple())
10416     return false;
10417
10418   if (Subtarget->isThumb1Only())
10419     return isLegalT1AddressImmediate(V, VT);
10420   else if (Subtarget->isThumb2())
10421     return isLegalT2AddressImmediate(V, VT, Subtarget);
10422
10423   // ARM mode.
10424   if (V < 0)
10425     V = - V;
10426   switch (VT.getSimpleVT().SimpleTy) {
10427   default: return false;
10428   case MVT::i1:
10429   case MVT::i8:
10430   case MVT::i32:
10431     // +- imm12
10432     return V == (V & ((1LL << 12) - 1));
10433   case MVT::i16:
10434     // +- imm8
10435     return V == (V & ((1LL << 8) - 1));
10436   case MVT::f32:
10437   case MVT::f64:
10438     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10439       return false;
10440     if ((V & 3) != 0)
10441       return false;
10442     V >>= 2;
10443     return V == (V & ((1LL << 8) - 1));
10444   }
10445 }
10446
10447 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10448                                                       EVT VT) const {
10449   int Scale = AM.Scale;
10450   if (Scale < 0)
10451     return false;
10452
10453   switch (VT.getSimpleVT().SimpleTy) {
10454   default: return false;
10455   case MVT::i1:
10456   case MVT::i8:
10457   case MVT::i16:
10458   case MVT::i32:
10459     if (Scale == 1)
10460       return true;
10461     // r + r << imm
10462     Scale = Scale & ~1;
10463     return Scale == 2 || Scale == 4 || Scale == 8;
10464   case MVT::i64:
10465     // r + r
10466     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10467       return true;
10468     return false;
10469   case MVT::isVoid:
10470     // Note, we allow "void" uses (basically, uses that aren't loads or
10471     // stores), because arm allows folding a scale into many arithmetic
10472     // operations.  This should be made more precise and revisited later.
10473
10474     // Allow r << imm, but the imm has to be a multiple of two.
10475     if (Scale & 1) return false;
10476     return isPowerOf2_32(Scale);
10477   }
10478 }
10479
10480 /// isLegalAddressingMode - Return true if the addressing mode represented
10481 /// by AM is legal for this target, for a load/store of the specified type.
10482 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10483                                               const AddrMode &AM, Type *Ty,
10484                                               unsigned AS) const {
10485   EVT VT = getValueType(DL, Ty, true);
10486   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10487     return false;
10488
10489   // Can never fold addr of global into load/store.
10490   if (AM.BaseGV)
10491     return false;
10492
10493   switch (AM.Scale) {
10494   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10495     break;
10496   case 1:
10497     if (Subtarget->isThumb1Only())
10498       return false;
10499     // FALL THROUGH.
10500   default:
10501     // ARM doesn't support any R+R*scale+imm addr modes.
10502     if (AM.BaseOffs)
10503       return false;
10504
10505     if (!VT.isSimple())
10506       return false;
10507
10508     if (Subtarget->isThumb2())
10509       return isLegalT2ScaledAddressingMode(AM, VT);
10510
10511     int Scale = AM.Scale;
10512     switch (VT.getSimpleVT().SimpleTy) {
10513     default: return false;
10514     case MVT::i1:
10515     case MVT::i8:
10516     case MVT::i32:
10517       if (Scale < 0) Scale = -Scale;
10518       if (Scale == 1)
10519         return true;
10520       // r + r << imm
10521       return isPowerOf2_32(Scale & ~1);
10522     case MVT::i16:
10523     case MVT::i64:
10524       // r + r
10525       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10526         return true;
10527       return false;
10528
10529     case MVT::isVoid:
10530       // Note, we allow "void" uses (basically, uses that aren't loads or
10531       // stores), because arm allows folding a scale into many arithmetic
10532       // operations.  This should be made more precise and revisited later.
10533
10534       // Allow r << imm, but the imm has to be a multiple of two.
10535       if (Scale & 1) return false;
10536       return isPowerOf2_32(Scale);
10537     }
10538   }
10539   return true;
10540 }
10541
10542 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10543 /// icmp immediate, that is the target has icmp instructions which can compare
10544 /// a register against the immediate without having to materialize the
10545 /// immediate into a register.
10546 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10547   // Thumb2 and ARM modes can use cmn for negative immediates.
10548   if (!Subtarget->isThumb())
10549     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10550   if (Subtarget->isThumb2())
10551     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10552   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10553   return Imm >= 0 && Imm <= 255;
10554 }
10555
10556 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10557 /// *or sub* immediate, that is the target has add or sub instructions which can
10558 /// add a register with the immediate without having to materialize the
10559 /// immediate into a register.
10560 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10561   // Same encoding for add/sub, just flip the sign.
10562   int64_t AbsImm = std::abs(Imm);
10563   if (!Subtarget->isThumb())
10564     return ARM_AM::getSOImmVal(AbsImm) != -1;
10565   if (Subtarget->isThumb2())
10566     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10567   // Thumb1 only has 8-bit unsigned immediate.
10568   return AbsImm >= 0 && AbsImm <= 255;
10569 }
10570
10571 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10572                                       bool isSEXTLoad, SDValue &Base,
10573                                       SDValue &Offset, bool &isInc,
10574                                       SelectionDAG &DAG) {
10575   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10576     return false;
10577
10578   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10579     // AddressingMode 3
10580     Base = Ptr->getOperand(0);
10581     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10582       int RHSC = (int)RHS->getZExtValue();
10583       if (RHSC < 0 && RHSC > -256) {
10584         assert(Ptr->getOpcode() == ISD::ADD);
10585         isInc = false;
10586         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10587         return true;
10588       }
10589     }
10590     isInc = (Ptr->getOpcode() == ISD::ADD);
10591     Offset = Ptr->getOperand(1);
10592     return true;
10593   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10594     // AddressingMode 2
10595     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10596       int RHSC = (int)RHS->getZExtValue();
10597       if (RHSC < 0 && RHSC > -0x1000) {
10598         assert(Ptr->getOpcode() == ISD::ADD);
10599         isInc = false;
10600         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10601         Base = Ptr->getOperand(0);
10602         return true;
10603       }
10604     }
10605
10606     if (Ptr->getOpcode() == ISD::ADD) {
10607       isInc = true;
10608       ARM_AM::ShiftOpc ShOpcVal=
10609         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10610       if (ShOpcVal != ARM_AM::no_shift) {
10611         Base = Ptr->getOperand(1);
10612         Offset = Ptr->getOperand(0);
10613       } else {
10614         Base = Ptr->getOperand(0);
10615         Offset = Ptr->getOperand(1);
10616       }
10617       return true;
10618     }
10619
10620     isInc = (Ptr->getOpcode() == ISD::ADD);
10621     Base = Ptr->getOperand(0);
10622     Offset = Ptr->getOperand(1);
10623     return true;
10624   }
10625
10626   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10627   return false;
10628 }
10629
10630 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10631                                      bool isSEXTLoad, SDValue &Base,
10632                                      SDValue &Offset, bool &isInc,
10633                                      SelectionDAG &DAG) {
10634   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10635     return false;
10636
10637   Base = Ptr->getOperand(0);
10638   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10639     int RHSC = (int)RHS->getZExtValue();
10640     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10641       assert(Ptr->getOpcode() == ISD::ADD);
10642       isInc = false;
10643       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10644       return true;
10645     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10646       isInc = Ptr->getOpcode() == ISD::ADD;
10647       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10648       return true;
10649     }
10650   }
10651
10652   return false;
10653 }
10654
10655 /// getPreIndexedAddressParts - returns true by value, base pointer and
10656 /// offset pointer and addressing mode by reference if the node's address
10657 /// can be legally represented as pre-indexed load / store address.
10658 bool
10659 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10660                                              SDValue &Offset,
10661                                              ISD::MemIndexedMode &AM,
10662                                              SelectionDAG &DAG) const {
10663   if (Subtarget->isThumb1Only())
10664     return false;
10665
10666   EVT VT;
10667   SDValue Ptr;
10668   bool isSEXTLoad = false;
10669   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10670     Ptr = LD->getBasePtr();
10671     VT  = LD->getMemoryVT();
10672     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10673   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10674     Ptr = ST->getBasePtr();
10675     VT  = ST->getMemoryVT();
10676   } else
10677     return false;
10678
10679   bool isInc;
10680   bool isLegal = false;
10681   if (Subtarget->isThumb2())
10682     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10683                                        Offset, isInc, DAG);
10684   else
10685     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10686                                         Offset, isInc, DAG);
10687   if (!isLegal)
10688     return false;
10689
10690   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10691   return true;
10692 }
10693
10694 /// getPostIndexedAddressParts - returns true by value, base pointer and
10695 /// offset pointer and addressing mode by reference if this node can be
10696 /// combined with a load / store to form a post-indexed load / store.
10697 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10698                                                    SDValue &Base,
10699                                                    SDValue &Offset,
10700                                                    ISD::MemIndexedMode &AM,
10701                                                    SelectionDAG &DAG) const {
10702   if (Subtarget->isThumb1Only())
10703     return false;
10704
10705   EVT VT;
10706   SDValue Ptr;
10707   bool isSEXTLoad = false;
10708   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10709     VT  = LD->getMemoryVT();
10710     Ptr = LD->getBasePtr();
10711     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10712   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10713     VT  = ST->getMemoryVT();
10714     Ptr = ST->getBasePtr();
10715   } else
10716     return false;
10717
10718   bool isInc;
10719   bool isLegal = false;
10720   if (Subtarget->isThumb2())
10721     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10722                                        isInc, DAG);
10723   else
10724     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10725                                         isInc, DAG);
10726   if (!isLegal)
10727     return false;
10728
10729   if (Ptr != Base) {
10730     // Swap base ptr and offset to catch more post-index load / store when
10731     // it's legal. In Thumb2 mode, offset must be an immediate.
10732     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10733         !Subtarget->isThumb2())
10734       std::swap(Base, Offset);
10735
10736     // Post-indexed load / store update the base pointer.
10737     if (Ptr != Base)
10738       return false;
10739   }
10740
10741   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10742   return true;
10743 }
10744
10745 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10746                                                       APInt &KnownZero,
10747                                                       APInt &KnownOne,
10748                                                       const SelectionDAG &DAG,
10749                                                       unsigned Depth) const {
10750   unsigned BitWidth = KnownOne.getBitWidth();
10751   KnownZero = KnownOne = APInt(BitWidth, 0);
10752   switch (Op.getOpcode()) {
10753   default: break;
10754   case ARMISD::ADDC:
10755   case ARMISD::ADDE:
10756   case ARMISD::SUBC:
10757   case ARMISD::SUBE:
10758     // These nodes' second result is a boolean
10759     if (Op.getResNo() == 0)
10760       break;
10761     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10762     break;
10763   case ARMISD::CMOV: {
10764     // Bits are known zero/one if known on the LHS and RHS.
10765     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10766     if (KnownZero == 0 && KnownOne == 0) return;
10767
10768     APInt KnownZeroRHS, KnownOneRHS;
10769     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10770     KnownZero &= KnownZeroRHS;
10771     KnownOne  &= KnownOneRHS;
10772     return;
10773   }
10774   case ISD::INTRINSIC_W_CHAIN: {
10775     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10776     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10777     switch (IntID) {
10778     default: return;
10779     case Intrinsic::arm_ldaex:
10780     case Intrinsic::arm_ldrex: {
10781       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10782       unsigned MemBits = VT.getScalarType().getSizeInBits();
10783       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10784       return;
10785     }
10786     }
10787   }
10788   }
10789 }
10790
10791 //===----------------------------------------------------------------------===//
10792 //                           ARM Inline Assembly Support
10793 //===----------------------------------------------------------------------===//
10794
10795 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10796   // Looking for "rev" which is V6+.
10797   if (!Subtarget->hasV6Ops())
10798     return false;
10799
10800   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10801   std::string AsmStr = IA->getAsmString();
10802   SmallVector<StringRef, 4> AsmPieces;
10803   SplitString(AsmStr, AsmPieces, ";\n");
10804
10805   switch (AsmPieces.size()) {
10806   default: return false;
10807   case 1:
10808     AsmStr = AsmPieces[0];
10809     AsmPieces.clear();
10810     SplitString(AsmStr, AsmPieces, " \t,");
10811
10812     // rev $0, $1
10813     if (AsmPieces.size() == 3 &&
10814         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10815         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10816       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10817       if (Ty && Ty->getBitWidth() == 32)
10818         return IntrinsicLowering::LowerToByteSwap(CI);
10819     }
10820     break;
10821   }
10822
10823   return false;
10824 }
10825
10826 /// getConstraintType - Given a constraint letter, return the type of
10827 /// constraint it is for this target.
10828 ARMTargetLowering::ConstraintType
10829 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10830   if (Constraint.size() == 1) {
10831     switch (Constraint[0]) {
10832     default:  break;
10833     case 'l': return C_RegisterClass;
10834     case 'w': return C_RegisterClass;
10835     case 'h': return C_RegisterClass;
10836     case 'x': return C_RegisterClass;
10837     case 't': return C_RegisterClass;
10838     case 'j': return C_Other; // Constant for movw.
10839       // An address with a single base register. Due to the way we
10840       // currently handle addresses it is the same as an 'r' memory constraint.
10841     case 'Q': return C_Memory;
10842     }
10843   } else if (Constraint.size() == 2) {
10844     switch (Constraint[0]) {
10845     default: break;
10846     // All 'U+' constraints are addresses.
10847     case 'U': return C_Memory;
10848     }
10849   }
10850   return TargetLowering::getConstraintType(Constraint);
10851 }
10852
10853 /// Examine constraint type and operand type and determine a weight value.
10854 /// This object must already have been set up with the operand type
10855 /// and the current alternative constraint selected.
10856 TargetLowering::ConstraintWeight
10857 ARMTargetLowering::getSingleConstraintMatchWeight(
10858     AsmOperandInfo &info, const char *constraint) const {
10859   ConstraintWeight weight = CW_Invalid;
10860   Value *CallOperandVal = info.CallOperandVal;
10861     // If we don't have a value, we can't do a match,
10862     // but allow it at the lowest weight.
10863   if (!CallOperandVal)
10864     return CW_Default;
10865   Type *type = CallOperandVal->getType();
10866   // Look at the constraint type.
10867   switch (*constraint) {
10868   default:
10869     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10870     break;
10871   case 'l':
10872     if (type->isIntegerTy()) {
10873       if (Subtarget->isThumb())
10874         weight = CW_SpecificReg;
10875       else
10876         weight = CW_Register;
10877     }
10878     break;
10879   case 'w':
10880     if (type->isFloatingPointTy())
10881       weight = CW_Register;
10882     break;
10883   }
10884   return weight;
10885 }
10886
10887 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10888 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10889     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10890   if (Constraint.size() == 1) {
10891     // GCC ARM Constraint Letters
10892     switch (Constraint[0]) {
10893     case 'l': // Low regs or general regs.
10894       if (Subtarget->isThumb())
10895         return RCPair(0U, &ARM::tGPRRegClass);
10896       return RCPair(0U, &ARM::GPRRegClass);
10897     case 'h': // High regs or no regs.
10898       if (Subtarget->isThumb())
10899         return RCPair(0U, &ARM::hGPRRegClass);
10900       break;
10901     case 'r':
10902       if (Subtarget->isThumb1Only())
10903         return RCPair(0U, &ARM::tGPRRegClass);
10904       return RCPair(0U, &ARM::GPRRegClass);
10905     case 'w':
10906       if (VT == MVT::Other)
10907         break;
10908       if (VT == MVT::f32)
10909         return RCPair(0U, &ARM::SPRRegClass);
10910       if (VT.getSizeInBits() == 64)
10911         return RCPair(0U, &ARM::DPRRegClass);
10912       if (VT.getSizeInBits() == 128)
10913         return RCPair(0U, &ARM::QPRRegClass);
10914       break;
10915     case 'x':
10916       if (VT == MVT::Other)
10917         break;
10918       if (VT == MVT::f32)
10919         return RCPair(0U, &ARM::SPR_8RegClass);
10920       if (VT.getSizeInBits() == 64)
10921         return RCPair(0U, &ARM::DPR_8RegClass);
10922       if (VT.getSizeInBits() == 128)
10923         return RCPair(0U, &ARM::QPR_8RegClass);
10924       break;
10925     case 't':
10926       if (VT == MVT::f32)
10927         return RCPair(0U, &ARM::SPRRegClass);
10928       break;
10929     }
10930   }
10931   if (StringRef("{cc}").equals_lower(Constraint))
10932     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10933
10934   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10935 }
10936
10937 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10938 /// vector.  If it is invalid, don't add anything to Ops.
10939 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10940                                                      std::string &Constraint,
10941                                                      std::vector<SDValue>&Ops,
10942                                                      SelectionDAG &DAG) const {
10943   SDValue Result;
10944
10945   // Currently only support length 1 constraints.
10946   if (Constraint.length() != 1) return;
10947
10948   char ConstraintLetter = Constraint[0];
10949   switch (ConstraintLetter) {
10950   default: break;
10951   case 'j':
10952   case 'I': case 'J': case 'K': case 'L':
10953   case 'M': case 'N': case 'O':
10954     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10955     if (!C)
10956       return;
10957
10958     int64_t CVal64 = C->getSExtValue();
10959     int CVal = (int) CVal64;
10960     // None of these constraints allow values larger than 32 bits.  Check
10961     // that the value fits in an int.
10962     if (CVal != CVal64)
10963       return;
10964
10965     switch (ConstraintLetter) {
10966       case 'j':
10967         // Constant suitable for movw, must be between 0 and
10968         // 65535.
10969         if (Subtarget->hasV6T2Ops())
10970           if (CVal >= 0 && CVal <= 65535)
10971             break;
10972         return;
10973       case 'I':
10974         if (Subtarget->isThumb1Only()) {
10975           // This must be a constant between 0 and 255, for ADD
10976           // immediates.
10977           if (CVal >= 0 && CVal <= 255)
10978             break;
10979         } else if (Subtarget->isThumb2()) {
10980           // A constant that can be used as an immediate value in a
10981           // data-processing instruction.
10982           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10983             break;
10984         } else {
10985           // A constant that can be used as an immediate value in a
10986           // data-processing instruction.
10987           if (ARM_AM::getSOImmVal(CVal) != -1)
10988             break;
10989         }
10990         return;
10991
10992       case 'J':
10993         if (Subtarget->isThumb()) {  // FIXME thumb2
10994           // This must be a constant between -255 and -1, for negated ADD
10995           // immediates. This can be used in GCC with an "n" modifier that
10996           // prints the negated value, for use with SUB instructions. It is
10997           // not useful otherwise but is implemented for compatibility.
10998           if (CVal >= -255 && CVal <= -1)
10999             break;
11000         } else {
11001           // This must be a constant between -4095 and 4095. It is not clear
11002           // what this constraint is intended for. Implemented for
11003           // compatibility with GCC.
11004           if (CVal >= -4095 && CVal <= 4095)
11005             break;
11006         }
11007         return;
11008
11009       case 'K':
11010         if (Subtarget->isThumb1Only()) {
11011           // A 32-bit value where only one byte has a nonzero value. Exclude
11012           // zero to match GCC. This constraint is used by GCC internally for
11013           // constants that can be loaded with a move/shift combination.
11014           // It is not useful otherwise but is implemented for compatibility.
11015           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11016             break;
11017         } else if (Subtarget->isThumb2()) {
11018           // A constant whose bitwise inverse can be used as an immediate
11019           // value in a data-processing instruction. This can be used in GCC
11020           // with a "B" modifier that prints the inverted value, for use with
11021           // BIC and MVN instructions. It is not useful otherwise but is
11022           // implemented for compatibility.
11023           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11024             break;
11025         } else {
11026           // A constant whose bitwise inverse can be used as an immediate
11027           // value in a data-processing instruction. This can be used in GCC
11028           // with a "B" modifier that prints the inverted value, for use with
11029           // BIC and MVN instructions. It is not useful otherwise but is
11030           // implemented for compatibility.
11031           if (ARM_AM::getSOImmVal(~CVal) != -1)
11032             break;
11033         }
11034         return;
11035
11036       case 'L':
11037         if (Subtarget->isThumb1Only()) {
11038           // This must be a constant between -7 and 7,
11039           // for 3-operand ADD/SUB immediate instructions.
11040           if (CVal >= -7 && CVal < 7)
11041             break;
11042         } else if (Subtarget->isThumb2()) {
11043           // A constant whose negation can be used as an immediate value in a
11044           // data-processing instruction. This can be used in GCC with an "n"
11045           // modifier that prints the negated value, for use with SUB
11046           // instructions. It is not useful otherwise but is implemented for
11047           // compatibility.
11048           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11049             break;
11050         } else {
11051           // A constant whose negation can be used as an immediate value in a
11052           // data-processing instruction. This can be used in GCC with an "n"
11053           // modifier that prints the negated value, for use with SUB
11054           // instructions. It is not useful otherwise but is implemented for
11055           // compatibility.
11056           if (ARM_AM::getSOImmVal(-CVal) != -1)
11057             break;
11058         }
11059         return;
11060
11061       case 'M':
11062         if (Subtarget->isThumb()) { // FIXME thumb2
11063           // This must be a multiple of 4 between 0 and 1020, for
11064           // ADD sp + immediate.
11065           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11066             break;
11067         } else {
11068           // A power of two or a constant between 0 and 32.  This is used in
11069           // GCC for the shift amount on shifted register operands, but it is
11070           // useful in general for any shift amounts.
11071           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11072             break;
11073         }
11074         return;
11075
11076       case 'N':
11077         if (Subtarget->isThumb()) {  // FIXME thumb2
11078           // This must be a constant between 0 and 31, for shift amounts.
11079           if (CVal >= 0 && CVal <= 31)
11080             break;
11081         }
11082         return;
11083
11084       case 'O':
11085         if (Subtarget->isThumb()) {  // FIXME thumb2
11086           // This must be a multiple of 4 between -508 and 508, for
11087           // ADD/SUB sp = sp + immediate.
11088           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11089             break;
11090         }
11091         return;
11092     }
11093     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11094     break;
11095   }
11096
11097   if (Result.getNode()) {
11098     Ops.push_back(Result);
11099     return;
11100   }
11101   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11102 }
11103
11104 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11105   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11106          "Register-based DivRem lowering only");
11107   unsigned Opcode = Op->getOpcode();
11108   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11109          "Invalid opcode for Div/Rem lowering");
11110   bool isSigned = (Opcode == ISD::SDIVREM);
11111   EVT VT = Op->getValueType(0);
11112   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11113
11114   RTLIB::Libcall LC;
11115   switch (VT.getSimpleVT().SimpleTy) {
11116   default: llvm_unreachable("Unexpected request for libcall!");
11117   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11118   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11119   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11120   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11121   }
11122
11123   SDValue InChain = DAG.getEntryNode();
11124
11125   TargetLowering::ArgListTy Args;
11126   TargetLowering::ArgListEntry Entry;
11127   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11128     EVT ArgVT = Op->getOperand(i).getValueType();
11129     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11130     Entry.Node = Op->getOperand(i);
11131     Entry.Ty = ArgTy;
11132     Entry.isSExt = isSigned;
11133     Entry.isZExt = !isSigned;
11134     Args.push_back(Entry);
11135   }
11136
11137   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11138                                          getPointerTy(DAG.getDataLayout()));
11139
11140   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11141
11142   SDLoc dl(Op);
11143   TargetLowering::CallLoweringInfo CLI(DAG);
11144   CLI.setDebugLoc(dl).setChain(InChain)
11145     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11146     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11147
11148   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11149   return CallInfo.first;
11150 }
11151
11152 SDValue
11153 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11154   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11155   SDLoc DL(Op);
11156
11157   // Get the inputs.
11158   SDValue Chain = Op.getOperand(0);
11159   SDValue Size  = Op.getOperand(1);
11160
11161   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11162                               DAG.getConstant(2, DL, MVT::i32));
11163
11164   SDValue Flag;
11165   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11166   Flag = Chain.getValue(1);
11167
11168   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11169   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11170
11171   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11172   Chain = NewSP.getValue(1);
11173
11174   SDValue Ops[2] = { NewSP, Chain };
11175   return DAG.getMergeValues(Ops, DL);
11176 }
11177
11178 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11179   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11180          "Unexpected type for custom-lowering FP_EXTEND");
11181
11182   RTLIB::Libcall LC;
11183   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11184
11185   SDValue SrcVal = Op.getOperand(0);
11186   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11187                      /*isSigned*/ false, SDLoc(Op)).first;
11188 }
11189
11190 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11191   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11192          Subtarget->isFPOnlySP() &&
11193          "Unexpected type for custom-lowering FP_ROUND");
11194
11195   RTLIB::Libcall LC;
11196   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11197
11198   SDValue SrcVal = Op.getOperand(0);
11199   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11200                      /*isSigned*/ false, SDLoc(Op)).first;
11201 }
11202
11203 bool
11204 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11205   // The ARM target isn't yet aware of offsets.
11206   return false;
11207 }
11208
11209 bool ARM::isBitFieldInvertedMask(unsigned v) {
11210   if (v == 0xffffffff)
11211     return false;
11212
11213   // there can be 1's on either or both "outsides", all the "inside"
11214   // bits must be 0's
11215   return isShiftedMask_32(~v);
11216 }
11217
11218 /// isFPImmLegal - Returns true if the target can instruction select the
11219 /// specified FP immediate natively. If false, the legalizer will
11220 /// materialize the FP immediate as a load from a constant pool.
11221 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11222   if (!Subtarget->hasVFP3())
11223     return false;
11224   if (VT == MVT::f32)
11225     return ARM_AM::getFP32Imm(Imm) != -1;
11226   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11227     return ARM_AM::getFP64Imm(Imm) != -1;
11228   return false;
11229 }
11230
11231 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11232 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11233 /// specified in the intrinsic calls.
11234 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11235                                            const CallInst &I,
11236                                            unsigned Intrinsic) const {
11237   switch (Intrinsic) {
11238   case Intrinsic::arm_neon_vld1:
11239   case Intrinsic::arm_neon_vld2:
11240   case Intrinsic::arm_neon_vld3:
11241   case Intrinsic::arm_neon_vld4:
11242   case Intrinsic::arm_neon_vld2lane:
11243   case Intrinsic::arm_neon_vld3lane:
11244   case Intrinsic::arm_neon_vld4lane: {
11245     Info.opc = ISD::INTRINSIC_W_CHAIN;
11246     // Conservatively set memVT to the entire set of vectors loaded.
11247     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11248     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11249     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11250     Info.ptrVal = I.getArgOperand(0);
11251     Info.offset = 0;
11252     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11253     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11254     Info.vol = false; // volatile loads with NEON intrinsics not supported
11255     Info.readMem = true;
11256     Info.writeMem = false;
11257     return true;
11258   }
11259   case Intrinsic::arm_neon_vst1:
11260   case Intrinsic::arm_neon_vst2:
11261   case Intrinsic::arm_neon_vst3:
11262   case Intrinsic::arm_neon_vst4:
11263   case Intrinsic::arm_neon_vst2lane:
11264   case Intrinsic::arm_neon_vst3lane:
11265   case Intrinsic::arm_neon_vst4lane: {
11266     Info.opc = ISD::INTRINSIC_VOID;
11267     // Conservatively set memVT to the entire set of vectors stored.
11268     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11269     unsigned NumElts = 0;
11270     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11271       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11272       if (!ArgTy->isVectorTy())
11273         break;
11274       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11275     }
11276     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11277     Info.ptrVal = I.getArgOperand(0);
11278     Info.offset = 0;
11279     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11280     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11281     Info.vol = false; // volatile stores with NEON intrinsics not supported
11282     Info.readMem = false;
11283     Info.writeMem = true;
11284     return true;
11285   }
11286   case Intrinsic::arm_ldaex:
11287   case Intrinsic::arm_ldrex: {
11288     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11289     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11290     Info.opc = ISD::INTRINSIC_W_CHAIN;
11291     Info.memVT = MVT::getVT(PtrTy->getElementType());
11292     Info.ptrVal = I.getArgOperand(0);
11293     Info.offset = 0;
11294     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11295     Info.vol = true;
11296     Info.readMem = true;
11297     Info.writeMem = false;
11298     return true;
11299   }
11300   case Intrinsic::arm_stlex:
11301   case Intrinsic::arm_strex: {
11302     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11303     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11304     Info.opc = ISD::INTRINSIC_W_CHAIN;
11305     Info.memVT = MVT::getVT(PtrTy->getElementType());
11306     Info.ptrVal = I.getArgOperand(1);
11307     Info.offset = 0;
11308     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11309     Info.vol = true;
11310     Info.readMem = false;
11311     Info.writeMem = true;
11312     return true;
11313   }
11314   case Intrinsic::arm_stlexd:
11315   case Intrinsic::arm_strexd: {
11316     Info.opc = ISD::INTRINSIC_W_CHAIN;
11317     Info.memVT = MVT::i64;
11318     Info.ptrVal = I.getArgOperand(2);
11319     Info.offset = 0;
11320     Info.align = 8;
11321     Info.vol = true;
11322     Info.readMem = false;
11323     Info.writeMem = true;
11324     return true;
11325   }
11326   case Intrinsic::arm_ldaexd:
11327   case Intrinsic::arm_ldrexd: {
11328     Info.opc = ISD::INTRINSIC_W_CHAIN;
11329     Info.memVT = MVT::i64;
11330     Info.ptrVal = I.getArgOperand(0);
11331     Info.offset = 0;
11332     Info.align = 8;
11333     Info.vol = true;
11334     Info.readMem = true;
11335     Info.writeMem = false;
11336     return true;
11337   }
11338   default:
11339     break;
11340   }
11341
11342   return false;
11343 }
11344
11345 /// \brief Returns true if it is beneficial to convert a load of a constant
11346 /// to just the constant itself.
11347 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11348                                                           Type *Ty) const {
11349   assert(Ty->isIntegerTy());
11350
11351   unsigned Bits = Ty->getPrimitiveSizeInBits();
11352   if (Bits == 0 || Bits > 32)
11353     return false;
11354   return true;
11355 }
11356
11357 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11358
11359 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11360                                         ARM_MB::MemBOpt Domain) const {
11361   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11362
11363   // First, if the target has no DMB, see what fallback we can use.
11364   if (!Subtarget->hasDataBarrier()) {
11365     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11366     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11367     // here.
11368     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11369       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11370       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11371                         Builder.getInt32(0), Builder.getInt32(7),
11372                         Builder.getInt32(10), Builder.getInt32(5)};
11373       return Builder.CreateCall(MCR, args);
11374     } else {
11375       // Instead of using barriers, atomic accesses on these subtargets use
11376       // libcalls.
11377       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11378     }
11379   } else {
11380     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11381     // Only a full system barrier exists in the M-class architectures.
11382     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11383     Constant *CDomain = Builder.getInt32(Domain);
11384     return Builder.CreateCall(DMB, CDomain);
11385   }
11386 }
11387
11388 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11389 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11390                                          AtomicOrdering Ord, bool IsStore,
11391                                          bool IsLoad) const {
11392   if (!getInsertFencesForAtomic())
11393     return nullptr;
11394
11395   switch (Ord) {
11396   case NotAtomic:
11397   case Unordered:
11398     llvm_unreachable("Invalid fence: unordered/non-atomic");
11399   case Monotonic:
11400   case Acquire:
11401     return nullptr; // Nothing to do
11402   case SequentiallyConsistent:
11403     if (!IsStore)
11404       return nullptr; // Nothing to do
11405     /*FALLTHROUGH*/
11406   case Release:
11407   case AcquireRelease:
11408     if (Subtarget->isSwift())
11409       return makeDMB(Builder, ARM_MB::ISHST);
11410     // FIXME: add a comment with a link to documentation justifying this.
11411     else
11412       return makeDMB(Builder, ARM_MB::ISH);
11413   }
11414   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11415 }
11416
11417 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11418                                           AtomicOrdering Ord, bool IsStore,
11419                                           bool IsLoad) const {
11420   if (!getInsertFencesForAtomic())
11421     return nullptr;
11422
11423   switch (Ord) {
11424   case NotAtomic:
11425   case Unordered:
11426     llvm_unreachable("Invalid fence: unordered/not-atomic");
11427   case Monotonic:
11428   case Release:
11429     return nullptr; // Nothing to do
11430   case Acquire:
11431   case AcquireRelease:
11432   case SequentiallyConsistent:
11433     return makeDMB(Builder, ARM_MB::ISH);
11434   }
11435   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11436 }
11437
11438 // Loads and stores less than 64-bits are already atomic; ones above that
11439 // are doomed anyway, so defer to the default libcall and blame the OS when
11440 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11441 // anything for those.
11442 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11443   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11444   return (Size == 64) && !Subtarget->isMClass();
11445 }
11446
11447 // Loads and stores less than 64-bits are already atomic; ones above that
11448 // are doomed anyway, so defer to the default libcall and blame the OS when
11449 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11450 // anything for those.
11451 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11452 // guarantee, see DDI0406C ARM architecture reference manual,
11453 // sections A8.8.72-74 LDRD)
11454 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11455   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11456   return (Size == 64) && !Subtarget->isMClass();
11457 }
11458
11459 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11460 // and up to 64 bits on the non-M profiles
11461 TargetLoweringBase::AtomicRMWExpansionKind
11462 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11463   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11464   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11465              ? AtomicRMWExpansionKind::LLSC
11466              : AtomicRMWExpansionKind::None;
11467 }
11468
11469 // This has so far only been implemented for MachO.
11470 bool ARMTargetLowering::useLoadStackGuardNode() const {
11471   return Subtarget->isTargetMachO();
11472 }
11473
11474 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11475                                                   unsigned &Cost) const {
11476   // If we do not have NEON, vector types are not natively supported.
11477   if (!Subtarget->hasNEON())
11478     return false;
11479
11480   // Floating point values and vector values map to the same register file.
11481   // Therefore, although we could do a store extract of a vector type, this is
11482   // better to leave at float as we have more freedom in the addressing mode for
11483   // those.
11484   if (VectorTy->isFPOrFPVectorTy())
11485     return false;
11486
11487   // If the index is unknown at compile time, this is very expensive to lower
11488   // and it is not possible to combine the store with the extract.
11489   if (!isa<ConstantInt>(Idx))
11490     return false;
11491
11492   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11493   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11494   // We can do a store + vector extract on any vector that fits perfectly in a D
11495   // or Q register.
11496   if (BitWidth == 64 || BitWidth == 128) {
11497     Cost = 0;
11498     return true;
11499   }
11500   return false;
11501 }
11502
11503 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11504                                          AtomicOrdering Ord) const {
11505   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11506   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11507   bool IsAcquire = isAtLeastAcquire(Ord);
11508
11509   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11510   // intrinsic must return {i32, i32} and we have to recombine them into a
11511   // single i64 here.
11512   if (ValTy->getPrimitiveSizeInBits() == 64) {
11513     Intrinsic::ID Int =
11514         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11515     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11516
11517     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11518     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11519
11520     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11521     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11522     if (!Subtarget->isLittle())
11523       std::swap (Lo, Hi);
11524     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11525     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11526     return Builder.CreateOr(
11527         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11528   }
11529
11530   Type *Tys[] = { Addr->getType() };
11531   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11532   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11533
11534   return Builder.CreateTruncOrBitCast(
11535       Builder.CreateCall(Ldrex, Addr),
11536       cast<PointerType>(Addr->getType())->getElementType());
11537 }
11538
11539 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11540                                                Value *Addr,
11541                                                AtomicOrdering Ord) const {
11542   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11543   bool IsRelease = isAtLeastRelease(Ord);
11544
11545   // Since the intrinsics must have legal type, the i64 intrinsics take two
11546   // parameters: "i32, i32". We must marshal Val into the appropriate form
11547   // before the call.
11548   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11549     Intrinsic::ID Int =
11550         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11551     Function *Strex = Intrinsic::getDeclaration(M, Int);
11552     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11553
11554     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11555     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11556     if (!Subtarget->isLittle())
11557       std::swap (Lo, Hi);
11558     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11559     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11560   }
11561
11562   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11563   Type *Tys[] = { Addr->getType() };
11564   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11565
11566   return Builder.CreateCall(
11567       Strex, {Builder.CreateZExtOrBitCast(
11568                   Val, Strex->getFunctionType()->getParamType(0)),
11569               Addr});
11570 }
11571
11572 /// \brief Lower an interleaved load into a vldN intrinsic.
11573 ///
11574 /// E.g. Lower an interleaved load (Factor = 2):
11575 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11576 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11577 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11578 ///
11579 ///      Into:
11580 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11581 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11582 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11583 bool ARMTargetLowering::lowerInterleavedLoad(
11584     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11585     ArrayRef<unsigned> Indices, unsigned Factor) const {
11586   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11587          "Invalid interleave factor");
11588   assert(!Shuffles.empty() && "Empty shufflevector input");
11589   assert(Shuffles.size() == Indices.size() &&
11590          "Unmatched number of shufflevectors and indices");
11591
11592   VectorType *VecTy = Shuffles[0]->getType();
11593   Type *EltTy = VecTy->getVectorElementType();
11594
11595   const DataLayout &DL = LI->getModule()->getDataLayout();
11596   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11597   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11598
11599   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11600   // support i64/f64 element).
11601   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11602     return false;
11603
11604   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11605   // load integer vectors first and then convert to pointer vectors.
11606   if (EltTy->isPointerTy())
11607     VecTy =
11608         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11609
11610   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11611                                             Intrinsic::arm_neon_vld3,
11612                                             Intrinsic::arm_neon_vld4};
11613
11614   Function *VldnFunc =
11615       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11616
11617   IRBuilder<> Builder(LI);
11618   SmallVector<Value *, 2> Ops;
11619
11620   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11621   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11622   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11623
11624   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11625
11626   // Replace uses of each shufflevector with the corresponding vector loaded
11627   // by ldN.
11628   for (unsigned i = 0; i < Shuffles.size(); i++) {
11629     ShuffleVectorInst *SV = Shuffles[i];
11630     unsigned Index = Indices[i];
11631
11632     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11633
11634     // Convert the integer vector to pointer vector if the element is pointer.
11635     if (EltTy->isPointerTy())
11636       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11637
11638     SV->replaceAllUsesWith(SubVec);
11639   }
11640
11641   return true;
11642 }
11643
11644 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11645 ///
11646 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11647 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11648                                    unsigned NumElts) {
11649   SmallVector<Constant *, 16> Mask;
11650   for (unsigned i = 0; i < NumElts; i++)
11651     Mask.push_back(Builder.getInt32(Start + i));
11652
11653   return ConstantVector::get(Mask);
11654 }
11655
11656 /// \brief Lower an interleaved store into a vstN intrinsic.
11657 ///
11658 /// E.g. Lower an interleaved store (Factor = 3):
11659 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11660 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11661 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11662 ///
11663 ///      Into:
11664 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11665 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11666 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11667 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11668 ///
11669 /// Note that the new shufflevectors will be removed and we'll only generate one
11670 /// vst3 instruction in CodeGen.
11671 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11672                                               ShuffleVectorInst *SVI,
11673                                               unsigned Factor) const {
11674   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11675          "Invalid interleave factor");
11676
11677   VectorType *VecTy = SVI->getType();
11678   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11679          "Invalid interleaved store");
11680
11681   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11682   Type *EltTy = VecTy->getVectorElementType();
11683   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11684
11685   const DataLayout &DL = SI->getModule()->getDataLayout();
11686   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11687   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11688
11689   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11690   // doesn't support i64/f64 element).
11691   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11692     return false;
11693
11694   Value *Op0 = SVI->getOperand(0);
11695   Value *Op1 = SVI->getOperand(1);
11696   IRBuilder<> Builder(SI);
11697
11698   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11699   // vectors to integer vectors.
11700   if (EltTy->isPointerTy()) {
11701     Type *IntTy = DL.getIntPtrType(EltTy);
11702
11703     // Convert to the corresponding integer vector.
11704     Type *IntVecTy =
11705         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11706     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11707     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11708
11709     SubVecTy = VectorType::get(IntTy, NumSubElts);
11710   }
11711
11712   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11713                                        Intrinsic::arm_neon_vst3,
11714                                        Intrinsic::arm_neon_vst4};
11715   Function *VstNFunc = Intrinsic::getDeclaration(
11716       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11717
11718   SmallVector<Value *, 6> Ops;
11719
11720   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11721   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11722
11723   // Split the shufflevector operands into sub vectors for the new vstN call.
11724   for (unsigned i = 0; i < Factor; i++)
11725     Ops.push_back(Builder.CreateShuffleVector(
11726         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11727
11728   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11729   Builder.CreateCall(VstNFunc, Ops);
11730   return true;
11731 }
11732
11733 enum HABaseType {
11734   HA_UNKNOWN = 0,
11735   HA_FLOAT,
11736   HA_DOUBLE,
11737   HA_VECT64,
11738   HA_VECT128
11739 };
11740
11741 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11742                                    uint64_t &Members) {
11743   if (auto *ST = dyn_cast<StructType>(Ty)) {
11744     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11745       uint64_t SubMembers = 0;
11746       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11747         return false;
11748       Members += SubMembers;
11749     }
11750   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11751     uint64_t SubMembers = 0;
11752     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11753       return false;
11754     Members += SubMembers * AT->getNumElements();
11755   } else if (Ty->isFloatTy()) {
11756     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11757       return false;
11758     Members = 1;
11759     Base = HA_FLOAT;
11760   } else if (Ty->isDoubleTy()) {
11761     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11762       return false;
11763     Members = 1;
11764     Base = HA_DOUBLE;
11765   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11766     Members = 1;
11767     switch (Base) {
11768     case HA_FLOAT:
11769     case HA_DOUBLE:
11770       return false;
11771     case HA_VECT64:
11772       return VT->getBitWidth() == 64;
11773     case HA_VECT128:
11774       return VT->getBitWidth() == 128;
11775     case HA_UNKNOWN:
11776       switch (VT->getBitWidth()) {
11777       case 64:
11778         Base = HA_VECT64;
11779         return true;
11780       case 128:
11781         Base = HA_VECT128;
11782         return true;
11783       default:
11784         return false;
11785       }
11786     }
11787   }
11788
11789   return (Members > 0 && Members <= 4);
11790 }
11791
11792 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11793 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11794 /// passing according to AAPCS rules.
11795 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11796     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11797   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11798       CallingConv::ARM_AAPCS_VFP)
11799     return false;
11800
11801   HABaseType Base = HA_UNKNOWN;
11802   uint64_t Members = 0;
11803   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11804   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11805
11806   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11807   return IsHA || IsIntArray;
11808 }