d63cb32bcdee2da10f7239336fc1de187f2c52cd
[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 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       static const struct {
175         const RTLIB::Libcall Op;
176         const char * const Name;
177         const ISD::CondCode Cond;
178       } LibraryCalls[] = {
179         // Single-precision floating-point arithmetic.
180         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184
185         // Double-precision floating-point arithmetic.
186         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190
191         // Single-precision comparisons.
192         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200
201         // Double-precision comparisons.
202         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210
211         // Floating-point to integer conversions.
212         // i64 conversions are done via library routines even when generating VFP
213         // instructions, so use the same ones.
214         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218
219         // Conversions between floating types.
220         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222
223         // Integer to floating-point conversions.
224         // i64 conversions are done via library routines even when generating VFP
225         // instructions, so use the same ones.
226         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227         // e.g., __floatunsidf vs. __floatunssidfvfp.
228         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232       };
233
234       for (const auto &LC : LibraryCalls) {
235         setLibcallName(LC.Op, LC.Name);
236         if (LC.Cond != ISD::SETCC_INVALID)
237           setCmpLibcallCC(LC.Op, LC.Cond);
238       }
239     }
240   }
241
242   // These libcalls are not available in 32-bit.
243   setLibcallName(RTLIB::SHL_I128, nullptr);
244   setLibcallName(RTLIB::SRL_I128, nullptr);
245   setLibcallName(RTLIB::SRA_I128, nullptr);
246
247   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248       !Subtarget->isTargetWindows()) {
249     static const struct {
250       const RTLIB::Libcall Op;
251       const char * const Name;
252       const CallingConv::ID CC;
253       const ISD::CondCode Cond;
254     } LibraryCalls[] = {
255       // Double-precision floating-point arithmetic helper functions
256       // RTABI chapter 4.1.2, Table 2
257       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261
262       // Double-precision floating-point comparison helper functions
263       // RTABI chapter 4.1.2, Table 3
264       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
272
273       // Single-precision floating-point arithmetic helper functions
274       // RTABI chapter 4.1.2, Table 4
275       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279
280       // Single-precision floating-point comparison helper functions
281       // RTABI chapter 4.1.2, Table 5
282       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
290
291       // Floating-point to integer conversions.
292       // RTABI chapter 4.1.2, Table 6
293       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301
302       // Conversions between floating types.
303       // RTABI chapter 4.1.2, Table 7
304       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Integer to floating-point conversions.
309       // RTABI chapter 4.1.2, Table 8
310       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Long long helper functions
320       // RTABI chapter 4.2, Table 9
321       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325
326       // Integer division functions
327       // RTABI chapter 4.3.1
328       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Memory operations
338       // RTABI chapter 4.3.4
339       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342     };
343
344     for (const auto &LC : LibraryCalls) {
345       setLibcallName(LC.Op, LC.Name);
346       setLibcallCallingConv(LC.Op, LC.CC);
347       if (LC.Cond != ISD::SETCC_INVALID)
348         setCmpLibcallCC(LC.Op, LC.Cond);
349     }
350   }
351
352   if (Subtarget->isTargetWindows()) {
353     static const struct {
354       const RTLIB::Libcall Op;
355       const char * const Name;
356       const CallingConv::ID CC;
357     } LibraryCalls[] = {
358       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
366     };
367
368     for (const auto &LC : LibraryCalls) {
369       setLibcallName(LC.Op, LC.Name);
370       setLibcallCallingConv(LC.Op, LC.CC);
371     }
372   }
373
374   // Use divmod compiler-rt calls for iOS 5.0 and later.
375   if (Subtarget->getTargetTriple().isiOS() &&
376       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
377     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
378     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
379   }
380
381   // The half <-> float conversion functions are always soft-float, but are
382   // needed for some targets which use a hard-float calling convention by
383   // default.
384   if (Subtarget->isAAPCS_ABI()) {
385     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
388   } else {
389     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
390     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
391     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
392   }
393
394   if (Subtarget->isThumb1Only())
395     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
396   else
397     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
398   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
399       !Subtarget->isThumb1Only()) {
400     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
401     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
402   }
403
404   for (MVT VT : MVT::vector_valuetypes()) {
405     for (MVT InnerVT : MVT::vector_valuetypes()) {
406       setTruncStoreAction(VT, InnerVT, Expand);
407       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
408       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
409       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
410     }
411
412     setOperationAction(ISD::MULHS, VT, Expand);
413     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
414     setOperationAction(ISD::MULHU, VT, Expand);
415     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
416
417     setOperationAction(ISD::BSWAP, VT, Expand);
418   }
419
420   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
421   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
422
423   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
424   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
425
426   if (Subtarget->hasNEON()) {
427     addDRTypeForNEON(MVT::v2f32);
428     addDRTypeForNEON(MVT::v8i8);
429     addDRTypeForNEON(MVT::v4i16);
430     addDRTypeForNEON(MVT::v2i32);
431     addDRTypeForNEON(MVT::v1i64);
432
433     addQRTypeForNEON(MVT::v4f32);
434     addQRTypeForNEON(MVT::v2f64);
435     addQRTypeForNEON(MVT::v16i8);
436     addQRTypeForNEON(MVT::v8i16);
437     addQRTypeForNEON(MVT::v4i32);
438     addQRTypeForNEON(MVT::v2i64);
439
440     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
441     // neither Neon nor VFP support any arithmetic operations on it.
442     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
443     // supported for v4f32.
444     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
445     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
446     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
447     // FIXME: Code duplication: FDIV and FREM are expanded always, see
448     // ARMTargetLowering::addTypeForNEON method for details.
449     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
450     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
451     // FIXME: Create unittest.
452     // In another words, find a way when "copysign" appears in DAG with vector
453     // operands.
454     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
455     // FIXME: Code duplication: SETCC has custom operation action, see
456     // ARMTargetLowering::addTypeForNEON method for details.
457     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
458     // FIXME: Create unittest for FNEG and for FABS.
459     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
472     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
473     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
474     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
475     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
476     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
477     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
478
479     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
480     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
481     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
482     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
483     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
485     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
487     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
488     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
490     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
491     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
492     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
494
495     // Mark v2f32 intrinsics.
496     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
497     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
498     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
499     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
500     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
502     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
504     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
505     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
511
512     // Neon does not support some operations on v1i64 and v2i64 types.
513     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
514     // Custom handling for some quad-vector types to detect VMULL.
515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
518     // Custom handling for some vector types to avoid expensive expansions
519     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
522     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
523     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
524     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
525     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
526     // a destination type that is wider than the source, and nor does
527     // it have a FP_TO_[SU]INT instruction with a narrower destination than
528     // source.
529     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
530     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
531     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
532     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
533
534     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
535     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
536
537     // NEON does not have single instruction CTPOP for vectors with element
538     // types wider than 8-bits.  However, custom lowering can leverage the
539     // v8i8/v16i8 vcnt instruction.
540     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
542     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
544
545     // NEON does not have single instruction CTTZ for vectors.
546     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
547     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
548     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
549     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
550
551     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
552     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
555
556     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
557     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
558     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
559     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
560
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
565
566     // NEON only has FMA instructions as of VFP4.
567     if (!Subtarget->hasVFP4()) {
568       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
569       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
570     }
571
572     setTargetDAGCombine(ISD::INTRINSIC_VOID);
573     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
574     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
575     setTargetDAGCombine(ISD::SHL);
576     setTargetDAGCombine(ISD::SRL);
577     setTargetDAGCombine(ISD::SRA);
578     setTargetDAGCombine(ISD::SIGN_EXTEND);
579     setTargetDAGCombine(ISD::ZERO_EXTEND);
580     setTargetDAGCombine(ISD::ANY_EXTEND);
581     setTargetDAGCombine(ISD::SELECT_CC);
582     setTargetDAGCombine(ISD::BUILD_VECTOR);
583     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
584     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
585     setTargetDAGCombine(ISD::STORE);
586     setTargetDAGCombine(ISD::FP_TO_SINT);
587     setTargetDAGCombine(ISD::FP_TO_UINT);
588     setTargetDAGCombine(ISD::FDIV);
589     setTargetDAGCombine(ISD::LOAD);
590
591     // It is legal to extload from v4i8 to v4i16 or v4i32.
592     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
593                    MVT::v2i32}) {
594       for (MVT VT : MVT::integer_vector_valuetypes()) {
595         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
596         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
597         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
598       }
599     }
600   }
601
602   // ARM and Thumb2 support UMLAL/SMLAL.
603   if (!Subtarget->isThumb1Only())
604     setTargetDAGCombine(ISD::ADDC);
605
606   if (Subtarget->isFPOnlySP()) {
607     // When targetting a floating-point unit with only single-precision
608     // operations, f64 is legal for the few double-precision instructions which
609     // are present However, no double-precision operations other than moves,
610     // loads and stores are provided by the hardware.
611     setOperationAction(ISD::FADD,       MVT::f64, Expand);
612     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
613     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
614     setOperationAction(ISD::FMA,        MVT::f64, Expand);
615     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
616     setOperationAction(ISD::FREM,       MVT::f64, Expand);
617     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
618     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
619     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
620     setOperationAction(ISD::FABS,       MVT::f64, Expand);
621     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
622     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
623     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
624     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
625     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
626     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
627     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
628     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
629     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
630     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
631     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
632     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
633     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
634     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
635     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
636     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
637     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
638     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
639     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
640     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
641     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
642     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
643     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
644   }
645
646   computeRegisterProperties(Subtarget->getRegisterInfo());
647
648   // ARM does not have floating-point extending loads.
649   for (MVT VT : MVT::fp_valuetypes()) {
650     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
651     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
652   }
653
654   // ... or truncating stores
655   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
656   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
657   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
658
659   // ARM does not have i1 sign extending load.
660   for (MVT VT : MVT::integer_valuetypes())
661     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
662
663   // ARM supports all 4 flavors of integer indexed load / store.
664   if (!Subtarget->isThumb1Only()) {
665     for (unsigned im = (unsigned)ISD::PRE_INC;
666          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
667       setIndexedLoadAction(im,  MVT::i1,  Legal);
668       setIndexedLoadAction(im,  MVT::i8,  Legal);
669       setIndexedLoadAction(im,  MVT::i16, Legal);
670       setIndexedLoadAction(im,  MVT::i32, Legal);
671       setIndexedStoreAction(im, MVT::i1,  Legal);
672       setIndexedStoreAction(im, MVT::i8,  Legal);
673       setIndexedStoreAction(im, MVT::i16, Legal);
674       setIndexedStoreAction(im, MVT::i32, Legal);
675     }
676   }
677
678   setOperationAction(ISD::SADDO, MVT::i32, Custom);
679   setOperationAction(ISD::UADDO, MVT::i32, Custom);
680   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
681   setOperationAction(ISD::USUBO, MVT::i32, Custom);
682
683   // i64 operation support.
684   setOperationAction(ISD::MUL,     MVT::i64, Expand);
685   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
686   if (Subtarget->isThumb1Only()) {
687     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
688     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
689   }
690   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
691       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
692     setOperationAction(ISD::MULHS, MVT::i32, Expand);
693
694   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
695   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
696   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
697   setOperationAction(ISD::SRL,       MVT::i64, Custom);
698   setOperationAction(ISD::SRA,       MVT::i64, Custom);
699
700   if (!Subtarget->isThumb1Only()) {
701     // FIXME: We should do this for Thumb1 as well.
702     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
703     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
704     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
705     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
706   }
707
708   // ARM does not have ROTL.
709   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
710   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
711   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
712   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
713     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
714
715   // These just redirect to CTTZ and CTLZ on ARM.
716   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
717   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
718
719   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
720
721   // Only ARMv6 has BSWAP.
722   if (!Subtarget->hasV6Ops())
723     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
724
725   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
726       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
727     // These are expanded into libcalls if the cpu doesn't have HW divider.
728     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
729     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
730   }
731
732   // FIXME: Also set divmod for SREM on EABI/androideabi
733   setOperationAction(ISD::SREM,  MVT::i32, Expand);
734   setOperationAction(ISD::UREM,  MVT::i32, Expand);
735   // Register based DivRem for AEABI (RTABI 4.2)
736   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
737     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
738     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
739     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
740     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
741     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
742     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
743     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
744     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
745
746     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
747     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
748     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
749     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
750     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
751     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
752     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
754
755     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
756     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
757   } else {
758     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
759     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
760   }
761
762   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
763   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
764   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
765   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
766   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
767
768   setOperationAction(ISD::TRAP, MVT::Other, Legal);
769
770   // Use the default implementation.
771   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
772   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
773   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
774   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
775   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
776   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
777
778   if (!Subtarget->isTargetMachO()) {
779     // Non-MachO platforms may return values in these registers via the
780     // personality function.
781     setExceptionPointerRegister(ARM::R0);
782     setExceptionSelectorRegister(ARM::R1);
783   }
784
785   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
786     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
787   else
788     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
789
790   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
791   // the default expansion. If we are targeting a single threaded system,
792   // then set them all for expand so we can lower them later into their
793   // non-atomic form.
794   if (TM.Options.ThreadModel == ThreadModel::Single)
795     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
796   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
797     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
798     // to ldrex/strex loops already.
799     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
800
801     // On v8, we have particularly efficient implementations of atomic fences
802     // if they can be combined with nearby atomic loads and stores.
803     if (!Subtarget->hasV8Ops()) {
804       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
805       setInsertFencesForAtomic(true);
806     }
807   } else {
808     // If there's anything we can use as a barrier, go through custom lowering
809     // for ATOMIC_FENCE.
810     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
811                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
812
813     // Set them all for expansion, which will force libcalls.
814     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
815     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
816     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
817     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
818     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
819     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
820     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
826     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
827     // Unordered/Monotonic case.
828     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
829     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
830   }
831
832   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
833
834   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
835   if (!Subtarget->hasV6Ops()) {
836     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
837     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
838   }
839   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
840
841   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
842       !Subtarget->isThumb1Only()) {
843     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
844     // iff target supports vfp2.
845     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
846     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
847   }
848
849   // We want to custom lower some of our intrinsics.
850   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
851   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
852   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
853   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
854   if (Subtarget->isTargetDarwin())
855     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
856
857   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
858   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
859   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
860   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
861   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
862   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
863   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
864   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
865   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
866
867   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
868   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
869   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
870   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
871   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
872
873   // We don't support sin/cos/fmod/copysign/pow
874   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
875   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
876   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
877   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
878   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
879   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
880   setOperationAction(ISD::FREM,      MVT::f64, Expand);
881   setOperationAction(ISD::FREM,      MVT::f32, Expand);
882   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
883       !Subtarget->isThumb1Only()) {
884     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
885     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
886   }
887   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
888   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
889
890   if (!Subtarget->hasVFP4()) {
891     setOperationAction(ISD::FMA, MVT::f64, Expand);
892     setOperationAction(ISD::FMA, MVT::f32, Expand);
893   }
894
895   // Various VFP goodness
896   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
897     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
898     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
899       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
900       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
901     }
902
903     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
904     if (!Subtarget->hasFP16()) {
905       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
906       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
907     }
908   }
909
910   // Combine sin / cos into one node or libcall if possible.
911   if (Subtarget->hasSinCos()) {
912     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
913     setLibcallName(RTLIB::SINCOS_F64, "sincos");
914     if (Subtarget->getTargetTriple().isiOS()) {
915       // For iOS, we don't want to the normal expansion of a libcall to
916       // sincos. We want to issue a libcall to __sincos_stret.
917       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
918       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
919     }
920   }
921
922   // FP-ARMv8 implements a lot of rounding-like FP operations.
923   if (Subtarget->hasFPARMv8()) {
924     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
925     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
926     setOperationAction(ISD::FROUND, MVT::f32, Legal);
927     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
928     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
929     setOperationAction(ISD::FRINT, MVT::f32, Legal);
930     if (!Subtarget->isFPOnlySP()) {
931       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
932       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
933       setOperationAction(ISD::FROUND, MVT::f64, Legal);
934       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
935       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
936       setOperationAction(ISD::FRINT, MVT::f64, Legal);
937     }
938   }
939   // We have target-specific dag combine patterns for the following nodes:
940   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
941   setTargetDAGCombine(ISD::ADD);
942   setTargetDAGCombine(ISD::SUB);
943   setTargetDAGCombine(ISD::MUL);
944   setTargetDAGCombine(ISD::AND);
945   setTargetDAGCombine(ISD::OR);
946   setTargetDAGCombine(ISD::XOR);
947
948   if (Subtarget->hasV6Ops())
949     setTargetDAGCombine(ISD::SRL);
950
951   setStackPointerRegisterToSaveRestore(ARM::SP);
952
953   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
954       !Subtarget->hasVFP2())
955     setSchedulingPreference(Sched::RegPressure);
956   else
957     setSchedulingPreference(Sched::Hybrid);
958
959   //// temporary - rewrite interface to use type
960   MaxStoresPerMemset = 8;
961   MaxStoresPerMemsetOptSize = 4;
962   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
963   MaxStoresPerMemcpyOptSize = 2;
964   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
965   MaxStoresPerMemmoveOptSize = 2;
966
967   // On ARM arguments smaller than 4 bytes are extended, so all arguments
968   // are at least 4 bytes aligned.
969   setMinStackArgumentAlignment(4);
970
971   // Prefer likely predicted branches to selects on out-of-order cores.
972   PredictableSelectIsExpensive = Subtarget->isLikeA9();
973
974   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
975 }
976
977 bool ARMTargetLowering::useSoftFloat() const {
978   return Subtarget->useSoftFloat();
979 }
980
981 // FIXME: It might make sense to define the representative register class as the
982 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
983 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
984 // SPR's representative would be DPR_VFP2. This should work well if register
985 // pressure tracking were modified such that a register use would increment the
986 // pressure of the register class's representative and all of it's super
987 // classes' representatives transitively. We have not implemented this because
988 // of the difficulty prior to coalescing of modeling operand register classes
989 // due to the common occurrence of cross class copies and subregister insertions
990 // and extractions.
991 std::pair<const TargetRegisterClass *, uint8_t>
992 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
993                                            MVT VT) const {
994   const TargetRegisterClass *RRC = nullptr;
995   uint8_t Cost = 1;
996   switch (VT.SimpleTy) {
997   default:
998     return TargetLowering::findRepresentativeClass(TRI, VT);
999   // Use DPR as representative register class for all floating point
1000   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1001   // the cost is 1 for both f32 and f64.
1002   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1003   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1004     RRC = &ARM::DPRRegClass;
1005     // When NEON is used for SP, only half of the register file is available
1006     // because operations that define both SP and DP results will be constrained
1007     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1008     // coalescing by double-counting the SP regs. See the FIXME above.
1009     if (Subtarget->useNEONForSinglePrecisionFP())
1010       Cost = 2;
1011     break;
1012   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1013   case MVT::v4f32: case MVT::v2f64:
1014     RRC = &ARM::DPRRegClass;
1015     Cost = 2;
1016     break;
1017   case MVT::v4i64:
1018     RRC = &ARM::DPRRegClass;
1019     Cost = 4;
1020     break;
1021   case MVT::v8i64:
1022     RRC = &ARM::DPRRegClass;
1023     Cost = 8;
1024     break;
1025   }
1026   return std::make_pair(RRC, Cost);
1027 }
1028
1029 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1030   switch ((ARMISD::NodeType)Opcode) {
1031   case ARMISD::FIRST_NUMBER:  break;
1032   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1033   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1034   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1035   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1036   case ARMISD::CALL:          return "ARMISD::CALL";
1037   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1038   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1039   case ARMISD::tCALL:         return "ARMISD::tCALL";
1040   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1041   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1042   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1043   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1044   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1045   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1046   case ARMISD::CMP:           return "ARMISD::CMP";
1047   case ARMISD::CMN:           return "ARMISD::CMN";
1048   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1049   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1050   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1051   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1052   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1053
1054   case ARMISD::CMOV:          return "ARMISD::CMOV";
1055
1056   case ARMISD::RBIT:          return "ARMISD::RBIT";
1057
1058   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1059   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1060   case ARMISD::RRX:           return "ARMISD::RRX";
1061
1062   case ARMISD::ADDC:          return "ARMISD::ADDC";
1063   case ARMISD::ADDE:          return "ARMISD::ADDE";
1064   case ARMISD::SUBC:          return "ARMISD::SUBC";
1065   case ARMISD::SUBE:          return "ARMISD::SUBE";
1066
1067   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1068   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1069
1070   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1071   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1072   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1073
1074   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1075
1076   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1077
1078   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1079
1080   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1081
1082   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1083
1084   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1085
1086   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1087   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1088   case ARMISD::VCGE:          return "ARMISD::VCGE";
1089   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1090   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1091   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1092   case ARMISD::VCGT:          return "ARMISD::VCGT";
1093   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1094   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1095   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1096   case ARMISD::VTST:          return "ARMISD::VTST";
1097
1098   case ARMISD::VSHL:          return "ARMISD::VSHL";
1099   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1100   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1101   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1102   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1103   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1104   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1105   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1106   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1107   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1108   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1109   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1110   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1111   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1112   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1113   case ARMISD::VSLI:          return "ARMISD::VSLI";
1114   case ARMISD::VSRI:          return "ARMISD::VSRI";
1115   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1116   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1117   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1118   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1119   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1120   case ARMISD::VDUP:          return "ARMISD::VDUP";
1121   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1122   case ARMISD::VEXT:          return "ARMISD::VEXT";
1123   case ARMISD::VREV64:        return "ARMISD::VREV64";
1124   case ARMISD::VREV32:        return "ARMISD::VREV32";
1125   case ARMISD::VREV16:        return "ARMISD::VREV16";
1126   case ARMISD::VZIP:          return "ARMISD::VZIP";
1127   case ARMISD::VUZP:          return "ARMISD::VUZP";
1128   case ARMISD::VTRN:          return "ARMISD::VTRN";
1129   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1130   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1131   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1132   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1133   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1134   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1135   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1136   case ARMISD::FMAX:          return "ARMISD::FMAX";
1137   case ARMISD::FMIN:          return "ARMISD::FMIN";
1138   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1139   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1140   case ARMISD::BFI:           return "ARMISD::BFI";
1141   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1142   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1143   case ARMISD::VBSL:          return "ARMISD::VBSL";
1144   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1145   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1146   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1147   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1148   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1149   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1150   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1151   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1152   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1153   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1154   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1155   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1156   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1157   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1158   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1159   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1160   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1161   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1162   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1163   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1164   }
1165   return nullptr;
1166 }
1167
1168 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1169                                           EVT VT) const {
1170   if (!VT.isVector())
1171     return getPointerTy(DL);
1172   return VT.changeVectorElementTypeToInteger();
1173 }
1174
1175 /// getRegClassFor - Return the register class that should be used for the
1176 /// specified value type.
1177 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1178   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1179   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1180   // load / store 4 to 8 consecutive D registers.
1181   if (Subtarget->hasNEON()) {
1182     if (VT == MVT::v4i64)
1183       return &ARM::QQPRRegClass;
1184     if (VT == MVT::v8i64)
1185       return &ARM::QQQQPRRegClass;
1186   }
1187   return TargetLowering::getRegClassFor(VT);
1188 }
1189
1190 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1191 // source/dest is aligned and the copy size is large enough. We therefore want
1192 // to align such objects passed to memory intrinsics.
1193 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1194                                                unsigned &PrefAlign) const {
1195   if (!isa<MemIntrinsic>(CI))
1196     return false;
1197   MinSize = 8;
1198   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1199   // cycle faster than 4-byte aligned LDM.
1200   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1201   return true;
1202 }
1203
1204 // Create a fast isel object.
1205 FastISel *
1206 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1207                                   const TargetLibraryInfo *libInfo) const {
1208   return ARM::createFastISel(funcInfo, libInfo);
1209 }
1210
1211 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1212   unsigned NumVals = N->getNumValues();
1213   if (!NumVals)
1214     return Sched::RegPressure;
1215
1216   for (unsigned i = 0; i != NumVals; ++i) {
1217     EVT VT = N->getValueType(i);
1218     if (VT == MVT::Glue || VT == MVT::Other)
1219       continue;
1220     if (VT.isFloatingPoint() || VT.isVector())
1221       return Sched::ILP;
1222   }
1223
1224   if (!N->isMachineOpcode())
1225     return Sched::RegPressure;
1226
1227   // Load are scheduled for latency even if there instruction itinerary
1228   // is not available.
1229   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1230   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1231
1232   if (MCID.getNumDefs() == 0)
1233     return Sched::RegPressure;
1234   if (!Itins->isEmpty() &&
1235       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1236     return Sched::ILP;
1237
1238   return Sched::RegPressure;
1239 }
1240
1241 //===----------------------------------------------------------------------===//
1242 // Lowering Code
1243 //===----------------------------------------------------------------------===//
1244
1245 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1246 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1247   switch (CC) {
1248   default: llvm_unreachable("Unknown condition code!");
1249   case ISD::SETNE:  return ARMCC::NE;
1250   case ISD::SETEQ:  return ARMCC::EQ;
1251   case ISD::SETGT:  return ARMCC::GT;
1252   case ISD::SETGE:  return ARMCC::GE;
1253   case ISD::SETLT:  return ARMCC::LT;
1254   case ISD::SETLE:  return ARMCC::LE;
1255   case ISD::SETUGT: return ARMCC::HI;
1256   case ISD::SETUGE: return ARMCC::HS;
1257   case ISD::SETULT: return ARMCC::LO;
1258   case ISD::SETULE: return ARMCC::LS;
1259   }
1260 }
1261
1262 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1263 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1264                         ARMCC::CondCodes &CondCode2) {
1265   CondCode2 = ARMCC::AL;
1266   switch (CC) {
1267   default: llvm_unreachable("Unknown FP condition!");
1268   case ISD::SETEQ:
1269   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1270   case ISD::SETGT:
1271   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1272   case ISD::SETGE:
1273   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1274   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1275   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1276   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1277   case ISD::SETO:   CondCode = ARMCC::VC; break;
1278   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1279   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1280   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1281   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1282   case ISD::SETLT:
1283   case ISD::SETULT: CondCode = ARMCC::LT; break;
1284   case ISD::SETLE:
1285   case ISD::SETULE: CondCode = ARMCC::LE; break;
1286   case ISD::SETNE:
1287   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1288   }
1289 }
1290
1291 //===----------------------------------------------------------------------===//
1292 //                      Calling Convention Implementation
1293 //===----------------------------------------------------------------------===//
1294
1295 #include "ARMGenCallingConv.inc"
1296
1297 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1298 /// account presence of floating point hardware and calling convention
1299 /// limitations, such as support for variadic functions.
1300 CallingConv::ID
1301 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1302                                            bool isVarArg) const {
1303   switch (CC) {
1304   default:
1305     llvm_unreachable("Unsupported calling convention");
1306   case CallingConv::ARM_AAPCS:
1307   case CallingConv::ARM_APCS:
1308   case CallingConv::GHC:
1309     return CC;
1310   case CallingConv::ARM_AAPCS_VFP:
1311     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1312   case CallingConv::C:
1313     if (!Subtarget->isAAPCS_ABI())
1314       return CallingConv::ARM_APCS;
1315     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1316              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1317              !isVarArg)
1318       return CallingConv::ARM_AAPCS_VFP;
1319     else
1320       return CallingConv::ARM_AAPCS;
1321   case CallingConv::Fast:
1322     if (!Subtarget->isAAPCS_ABI()) {
1323       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1324         return CallingConv::Fast;
1325       return CallingConv::ARM_APCS;
1326     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1327       return CallingConv::ARM_AAPCS_VFP;
1328     else
1329       return CallingConv::ARM_AAPCS;
1330   }
1331 }
1332
1333 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1334 /// CallingConvention.
1335 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1336                                                  bool Return,
1337                                                  bool isVarArg) const {
1338   switch (getEffectiveCallingConv(CC, isVarArg)) {
1339   default:
1340     llvm_unreachable("Unsupported calling convention");
1341   case CallingConv::ARM_APCS:
1342     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1343   case CallingConv::ARM_AAPCS:
1344     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1345   case CallingConv::ARM_AAPCS_VFP:
1346     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1347   case CallingConv::Fast:
1348     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1349   case CallingConv::GHC:
1350     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1351   }
1352 }
1353
1354 /// LowerCallResult - Lower the result values of a call into the
1355 /// appropriate copies out of appropriate physical registers.
1356 SDValue
1357 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1358                                    CallingConv::ID CallConv, bool isVarArg,
1359                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1360                                    SDLoc dl, SelectionDAG &DAG,
1361                                    SmallVectorImpl<SDValue> &InVals,
1362                                    bool isThisReturn, SDValue ThisVal) const {
1363
1364   // Assign locations to each value returned by this call.
1365   SmallVector<CCValAssign, 16> RVLocs;
1366   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1367                     *DAG.getContext(), Call);
1368   CCInfo.AnalyzeCallResult(Ins,
1369                            CCAssignFnForNode(CallConv, /* Return*/ true,
1370                                              isVarArg));
1371
1372   // Copy all of the result registers out of their specified physreg.
1373   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1374     CCValAssign VA = RVLocs[i];
1375
1376     // Pass 'this' value directly from the argument to return value, to avoid
1377     // reg unit interference
1378     if (i == 0 && isThisReturn) {
1379       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1380              "unexpected return calling convention register assignment");
1381       InVals.push_back(ThisVal);
1382       continue;
1383     }
1384
1385     SDValue Val;
1386     if (VA.needsCustom()) {
1387       // Handle f64 or half of a v2f64.
1388       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1389                                       InFlag);
1390       Chain = Lo.getValue(1);
1391       InFlag = Lo.getValue(2);
1392       VA = RVLocs[++i]; // skip ahead to next loc
1393       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1394                                       InFlag);
1395       Chain = Hi.getValue(1);
1396       InFlag = Hi.getValue(2);
1397       if (!Subtarget->isLittle())
1398         std::swap (Lo, Hi);
1399       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1400
1401       if (VA.getLocVT() == MVT::v2f64) {
1402         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1403         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1404                           DAG.getConstant(0, dl, MVT::i32));
1405
1406         VA = RVLocs[++i]; // skip ahead to next loc
1407         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1408         Chain = Lo.getValue(1);
1409         InFlag = Lo.getValue(2);
1410         VA = RVLocs[++i]; // skip ahead to next loc
1411         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1412         Chain = Hi.getValue(1);
1413         InFlag = Hi.getValue(2);
1414         if (!Subtarget->isLittle())
1415           std::swap (Lo, Hi);
1416         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1417         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1418                           DAG.getConstant(1, dl, MVT::i32));
1419       }
1420     } else {
1421       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1422                                InFlag);
1423       Chain = Val.getValue(1);
1424       InFlag = Val.getValue(2);
1425     }
1426
1427     switch (VA.getLocInfo()) {
1428     default: llvm_unreachable("Unknown loc info!");
1429     case CCValAssign::Full: break;
1430     case CCValAssign::BCvt:
1431       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1432       break;
1433     }
1434
1435     InVals.push_back(Val);
1436   }
1437
1438   return Chain;
1439 }
1440
1441 /// LowerMemOpCallTo - Store the argument to the stack.
1442 SDValue
1443 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1444                                     SDValue StackPtr, SDValue Arg,
1445                                     SDLoc dl, SelectionDAG &DAG,
1446                                     const CCValAssign &VA,
1447                                     ISD::ArgFlagsTy Flags) const {
1448   unsigned LocMemOffset = VA.getLocMemOffset();
1449   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1450   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1451                        StackPtr, PtrOff);
1452   return DAG.getStore(Chain, dl, Arg, PtrOff,
1453                       MachinePointerInfo::getStack(LocMemOffset),
1454                       false, false, 0);
1455 }
1456
1457 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1458                                          SDValue Chain, SDValue &Arg,
1459                                          RegsToPassVector &RegsToPass,
1460                                          CCValAssign &VA, CCValAssign &NextVA,
1461                                          SDValue &StackPtr,
1462                                          SmallVectorImpl<SDValue> &MemOpChains,
1463                                          ISD::ArgFlagsTy Flags) const {
1464
1465   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1466                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1467   unsigned id = Subtarget->isLittle() ? 0 : 1;
1468   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1469
1470   if (NextVA.isRegLoc())
1471     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1472   else {
1473     assert(NextVA.isMemLoc());
1474     if (!StackPtr.getNode())
1475       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1476                                     getPointerTy(DAG.getDataLayout()));
1477
1478     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1479                                            dl, DAG, NextVA,
1480                                            Flags));
1481   }
1482 }
1483
1484 /// LowerCall - Lowering a call into a callseq_start <-
1485 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1486 /// nodes.
1487 SDValue
1488 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1489                              SmallVectorImpl<SDValue> &InVals) const {
1490   SelectionDAG &DAG                     = CLI.DAG;
1491   SDLoc &dl                             = CLI.DL;
1492   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1493   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1494   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1495   SDValue Chain                         = CLI.Chain;
1496   SDValue Callee                        = CLI.Callee;
1497   bool &isTailCall                      = CLI.IsTailCall;
1498   CallingConv::ID CallConv              = CLI.CallConv;
1499   bool doesNotRet                       = CLI.DoesNotReturn;
1500   bool isVarArg                         = CLI.IsVarArg;
1501
1502   MachineFunction &MF = DAG.getMachineFunction();
1503   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1504   bool isThisReturn   = false;
1505   bool isSibCall      = false;
1506   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1507
1508   // Disable tail calls if they're not supported.
1509   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1510     isTailCall = false;
1511
1512   if (isTailCall) {
1513     // Check if it's really possible to do a tail call.
1514     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1515                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1516                                                    Outs, OutVals, Ins, DAG);
1517     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1518       report_fatal_error("failed to perform tail call elimination on a call "
1519                          "site marked musttail");
1520     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1521     // detected sibcalls.
1522     if (isTailCall) {
1523       ++NumTailCalls;
1524       isSibCall = true;
1525     }
1526   }
1527
1528   // Analyze operands of the call, assigning locations to each operand.
1529   SmallVector<CCValAssign, 16> ArgLocs;
1530   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1531                     *DAG.getContext(), Call);
1532   CCInfo.AnalyzeCallOperands(Outs,
1533                              CCAssignFnForNode(CallConv, /* Return*/ false,
1534                                                isVarArg));
1535
1536   // Get a count of how many bytes are to be pushed on the stack.
1537   unsigned NumBytes = CCInfo.getNextStackOffset();
1538
1539   // For tail calls, memory operands are available in our caller's stack.
1540   if (isSibCall)
1541     NumBytes = 0;
1542
1543   // Adjust the stack pointer for the new arguments...
1544   // These operations are automatically eliminated by the prolog/epilog pass
1545   if (!isSibCall)
1546     Chain = DAG.getCALLSEQ_START(Chain,
1547                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1548
1549   SDValue StackPtr =
1550       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1551
1552   RegsToPassVector RegsToPass;
1553   SmallVector<SDValue, 8> MemOpChains;
1554
1555   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1556   // of tail call optimization, arguments are handled later.
1557   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1558        i != e;
1559        ++i, ++realArgIdx) {
1560     CCValAssign &VA = ArgLocs[i];
1561     SDValue Arg = OutVals[realArgIdx];
1562     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1563     bool isByVal = Flags.isByVal();
1564
1565     // Promote the value if needed.
1566     switch (VA.getLocInfo()) {
1567     default: llvm_unreachable("Unknown loc info!");
1568     case CCValAssign::Full: break;
1569     case CCValAssign::SExt:
1570       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1571       break;
1572     case CCValAssign::ZExt:
1573       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1574       break;
1575     case CCValAssign::AExt:
1576       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1577       break;
1578     case CCValAssign::BCvt:
1579       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1580       break;
1581     }
1582
1583     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1584     if (VA.needsCustom()) {
1585       if (VA.getLocVT() == MVT::v2f64) {
1586         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1587                                   DAG.getConstant(0, dl, MVT::i32));
1588         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1589                                   DAG.getConstant(1, dl, MVT::i32));
1590
1591         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1592                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1593
1594         VA = ArgLocs[++i]; // skip ahead to next loc
1595         if (VA.isRegLoc()) {
1596           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1597                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1598         } else {
1599           assert(VA.isMemLoc());
1600
1601           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1602                                                  dl, DAG, VA, Flags));
1603         }
1604       } else {
1605         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1606                          StackPtr, MemOpChains, Flags);
1607       }
1608     } else if (VA.isRegLoc()) {
1609       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1610         assert(VA.getLocVT() == MVT::i32 &&
1611                "unexpected calling convention register assignment");
1612         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1613                "unexpected use of 'returned'");
1614         isThisReturn = true;
1615       }
1616       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1617     } else if (isByVal) {
1618       assert(VA.isMemLoc());
1619       unsigned offset = 0;
1620
1621       // True if this byval aggregate will be split between registers
1622       // and memory.
1623       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1624       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1625
1626       if (CurByValIdx < ByValArgsCount) {
1627
1628         unsigned RegBegin, RegEnd;
1629         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1630
1631         EVT PtrVT =
1632             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1633         unsigned int i, j;
1634         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1635           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1636           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1637           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1638                                      MachinePointerInfo(),
1639                                      false, false, false,
1640                                      DAG.InferPtrAlignment(AddArg));
1641           MemOpChains.push_back(Load.getValue(1));
1642           RegsToPass.push_back(std::make_pair(j, Load));
1643         }
1644
1645         // If parameter size outsides register area, "offset" value
1646         // helps us to calculate stack slot for remained part properly.
1647         offset = RegEnd - RegBegin;
1648
1649         CCInfo.nextInRegsParam();
1650       }
1651
1652       if (Flags.getByValSize() > 4*offset) {
1653         auto PtrVT = getPointerTy(DAG.getDataLayout());
1654         unsigned LocMemOffset = VA.getLocMemOffset();
1655         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1656         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1657         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1658         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1659         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1660                                            MVT::i32);
1661         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1662                                             MVT::i32);
1663
1664         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1665         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1666         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1667                                           Ops));
1668       }
1669     } else if (!isSibCall) {
1670       assert(VA.isMemLoc());
1671
1672       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1673                                              dl, DAG, VA, Flags));
1674     }
1675   }
1676
1677   if (!MemOpChains.empty())
1678     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1679
1680   // Build a sequence of copy-to-reg nodes chained together with token chain
1681   // and flag operands which copy the outgoing args into the appropriate regs.
1682   SDValue InFlag;
1683   // Tail call byval lowering might overwrite argument registers so in case of
1684   // tail call optimization the copies to registers are lowered later.
1685   if (!isTailCall)
1686     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1687       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1688                                RegsToPass[i].second, InFlag);
1689       InFlag = Chain.getValue(1);
1690     }
1691
1692   // For tail calls lower the arguments to the 'real' stack slot.
1693   if (isTailCall) {
1694     // Force all the incoming stack arguments to be loaded from the stack
1695     // before any new outgoing arguments are stored to the stack, because the
1696     // outgoing stack slots may alias the incoming argument stack slots, and
1697     // the alias isn't otherwise explicit. This is slightly more conservative
1698     // than necessary, because it means that each store effectively depends
1699     // on every argument instead of just those arguments it would clobber.
1700
1701     // Do not flag preceding copytoreg stuff together with the following stuff.
1702     InFlag = SDValue();
1703     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1704       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1705                                RegsToPass[i].second, InFlag);
1706       InFlag = Chain.getValue(1);
1707     }
1708     InFlag = SDValue();
1709   }
1710
1711   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1712   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1713   // node so that legalize doesn't hack it.
1714   bool isDirect = false;
1715   bool isARMFunc = false;
1716   bool isLocalARMFunc = false;
1717   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1718   auto PtrVt = getPointerTy(DAG.getDataLayout());
1719
1720   if (Subtarget->genLongCalls()) {
1721     assert((Subtarget->isTargetWindows() ||
1722             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1723            "long-calls with non-static relocation model!");
1724     // Handle a global address or an external symbol. If it's not one of
1725     // those, the target's already in a register, so we don't need to do
1726     // anything extra.
1727     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1728       const GlobalValue *GV = G->getGlobal();
1729       // Create a constant pool entry for the callee address
1730       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1731       ARMConstantPoolValue *CPV =
1732         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1733
1734       // Get the address of the callee into a register
1735       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1736       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1737       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1738                            MachinePointerInfo::getConstantPool(), false, false,
1739                            false, 0);
1740     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1741       const char *Sym = S->getSymbol();
1742
1743       // Create a constant pool entry for the callee address
1744       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1745       ARMConstantPoolValue *CPV =
1746         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1747                                       ARMPCLabelIndex, 0);
1748       // Get the address of the callee into a register
1749       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1750       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1751       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1752                            MachinePointerInfo::getConstantPool(), false, false,
1753                            false, 0);
1754     }
1755   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1756     const GlobalValue *GV = G->getGlobal();
1757     isDirect = true;
1758     bool isDef = GV->isStrongDefinitionForLinker();
1759     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1760                    getTargetMachine().getRelocationModel() != Reloc::Static;
1761     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1762     // ARM call to a local ARM function is predicable.
1763     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1764     // tBX takes a register source operand.
1765     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1766       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1767       Callee = DAG.getNode(
1768           ARMISD::WrapperPIC, dl, PtrVt,
1769           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1770       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1771                            MachinePointerInfo::getGOT(), false, false, true, 0);
1772     } else if (Subtarget->isTargetCOFF()) {
1773       assert(Subtarget->isTargetWindows() &&
1774              "Windows is the only supported COFF target");
1775       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1776                                  ? ARMII::MO_DLLIMPORT
1777                                  : ARMII::MO_NO_FLAG;
1778       Callee =
1779           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1780       if (GV->hasDLLImportStorageClass())
1781         Callee =
1782             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1783                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1784                         MachinePointerInfo::getGOT(), false, false, false, 0);
1785     } else {
1786       // On ELF targets for PIC code, direct calls should go through the PLT
1787       unsigned OpFlags = 0;
1788       if (Subtarget->isTargetELF() &&
1789           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1790         OpFlags = ARMII::MO_PLT;
1791       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1792     }
1793   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1794     isDirect = true;
1795     bool isStub = Subtarget->isTargetMachO() &&
1796                   getTargetMachine().getRelocationModel() != Reloc::Static;
1797     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1798     // tBX takes a register source operand.
1799     const char *Sym = S->getSymbol();
1800     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1801       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1802       ARMConstantPoolValue *CPV =
1803         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1804                                       ARMPCLabelIndex, 4);
1805       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1806       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1807       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1808                            MachinePointerInfo::getConstantPool(), false, false,
1809                            false, 0);
1810       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1811       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1812     } else {
1813       unsigned OpFlags = 0;
1814       // On ELF targets for PIC code, direct calls should go through the PLT
1815       if (Subtarget->isTargetELF() &&
1816                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1817         OpFlags = ARMII::MO_PLT;
1818       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1819     }
1820   }
1821
1822   // FIXME: handle tail calls differently.
1823   unsigned CallOpc;
1824   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1825   if (Subtarget->isThumb()) {
1826     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1827       CallOpc = ARMISD::CALL_NOLINK;
1828     else
1829       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1830   } else {
1831     if (!isDirect && !Subtarget->hasV5TOps())
1832       CallOpc = ARMISD::CALL_NOLINK;
1833     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1834                // Emit regular call when code size is the priority
1835                !HasMinSizeAttr)
1836       // "mov lr, pc; b _foo" to avoid confusing the RSP
1837       CallOpc = ARMISD::CALL_NOLINK;
1838     else
1839       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1840   }
1841
1842   std::vector<SDValue> Ops;
1843   Ops.push_back(Chain);
1844   Ops.push_back(Callee);
1845
1846   // Add argument registers to the end of the list so that they are known live
1847   // into the call.
1848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1849     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1850                                   RegsToPass[i].second.getValueType()));
1851
1852   // Add a register mask operand representing the call-preserved registers.
1853   if (!isTailCall) {
1854     const uint32_t *Mask;
1855     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1856     if (isThisReturn) {
1857       // For 'this' returns, use the R0-preserving mask if applicable
1858       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1859       if (!Mask) {
1860         // Set isThisReturn to false if the calling convention is not one that
1861         // allows 'returned' to be modeled in this way, so LowerCallResult does
1862         // not try to pass 'this' straight through
1863         isThisReturn = false;
1864         Mask = ARI->getCallPreservedMask(MF, CallConv);
1865       }
1866     } else
1867       Mask = ARI->getCallPreservedMask(MF, CallConv);
1868
1869     assert(Mask && "Missing call preserved mask for calling convention");
1870     Ops.push_back(DAG.getRegisterMask(Mask));
1871   }
1872
1873   if (InFlag.getNode())
1874     Ops.push_back(InFlag);
1875
1876   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1877   if (isTailCall) {
1878     MF.getFrameInfo()->setHasTailCall();
1879     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1880   }
1881
1882   // Returns a chain and a flag for retval copy to use.
1883   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1884   InFlag = Chain.getValue(1);
1885
1886   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1887                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1888   if (!Ins.empty())
1889     InFlag = Chain.getValue(1);
1890
1891   // Handle result values, copying them out of physregs into vregs that we
1892   // return.
1893   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1894                          InVals, isThisReturn,
1895                          isThisReturn ? OutVals[0] : SDValue());
1896 }
1897
1898 /// HandleByVal - Every parameter *after* a byval parameter is passed
1899 /// on the stack.  Remember the next parameter register to allocate,
1900 /// and then confiscate the rest of the parameter registers to insure
1901 /// this.
1902 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1903                                     unsigned Align) const {
1904   assert((State->getCallOrPrologue() == Prologue ||
1905           State->getCallOrPrologue() == Call) &&
1906          "unhandled ParmContext");
1907
1908   // Byval (as with any stack) slots are always at least 4 byte aligned.
1909   Align = std::max(Align, 4U);
1910
1911   unsigned Reg = State->AllocateReg(GPRArgRegs);
1912   if (!Reg)
1913     return;
1914
1915   unsigned AlignInRegs = Align / 4;
1916   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1917   for (unsigned i = 0; i < Waste; ++i)
1918     Reg = State->AllocateReg(GPRArgRegs);
1919
1920   if (!Reg)
1921     return;
1922
1923   unsigned Excess = 4 * (ARM::R4 - Reg);
1924
1925   // Special case when NSAA != SP and parameter size greater than size of
1926   // all remained GPR regs. In that case we can't split parameter, we must
1927   // send it to stack. We also must set NCRN to R4, so waste all
1928   // remained registers.
1929   const unsigned NSAAOffset = State->getNextStackOffset();
1930   if (NSAAOffset != 0 && Size > Excess) {
1931     while (State->AllocateReg(GPRArgRegs))
1932       ;
1933     return;
1934   }
1935
1936   // First register for byval parameter is the first register that wasn't
1937   // allocated before this method call, so it would be "reg".
1938   // If parameter is small enough to be saved in range [reg, r4), then
1939   // the end (first after last) register would be reg + param-size-in-regs,
1940   // else parameter would be splitted between registers and stack,
1941   // end register would be r4 in this case.
1942   unsigned ByValRegBegin = Reg;
1943   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1944   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1945   // Note, first register is allocated in the beginning of function already,
1946   // allocate remained amount of registers we need.
1947   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1948     State->AllocateReg(GPRArgRegs);
1949   // A byval parameter that is split between registers and memory needs its
1950   // size truncated here.
1951   // In the case where the entire structure fits in registers, we set the
1952   // size in memory to zero.
1953   Size = std::max<int>(Size - Excess, 0);
1954 }
1955
1956 /// MatchingStackOffset - Return true if the given stack call argument is
1957 /// already available in the same position (relatively) of the caller's
1958 /// incoming argument stack.
1959 static
1960 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1961                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1962                          const TargetInstrInfo *TII) {
1963   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1964   int FI = INT_MAX;
1965   if (Arg.getOpcode() == ISD::CopyFromReg) {
1966     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1967     if (!TargetRegisterInfo::isVirtualRegister(VR))
1968       return false;
1969     MachineInstr *Def = MRI->getVRegDef(VR);
1970     if (!Def)
1971       return false;
1972     if (!Flags.isByVal()) {
1973       if (!TII->isLoadFromStackSlot(Def, FI))
1974         return false;
1975     } else {
1976       return false;
1977     }
1978   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1979     if (Flags.isByVal())
1980       // ByVal argument is passed in as a pointer but it's now being
1981       // dereferenced. e.g.
1982       // define @foo(%struct.X* %A) {
1983       //   tail call @bar(%struct.X* byval %A)
1984       // }
1985       return false;
1986     SDValue Ptr = Ld->getBasePtr();
1987     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1988     if (!FINode)
1989       return false;
1990     FI = FINode->getIndex();
1991   } else
1992     return false;
1993
1994   assert(FI != INT_MAX);
1995   if (!MFI->isFixedObjectIndex(FI))
1996     return false;
1997   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1998 }
1999
2000 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2001 /// for tail call optimization. Targets which want to do tail call
2002 /// optimization should implement this function.
2003 bool
2004 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2005                                                      CallingConv::ID CalleeCC,
2006                                                      bool isVarArg,
2007                                                      bool isCalleeStructRet,
2008                                                      bool isCallerStructRet,
2009                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2010                                     const SmallVectorImpl<SDValue> &OutVals,
2011                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2012                                                      SelectionDAG& DAG) const {
2013   const Function *CallerF = DAG.getMachineFunction().getFunction();
2014   CallingConv::ID CallerCC = CallerF->getCallingConv();
2015   bool CCMatch = CallerCC == CalleeCC;
2016
2017   // Look for obvious safe cases to perform tail call optimization that do not
2018   // require ABI changes. This is what gcc calls sibcall.
2019
2020   // Do not sibcall optimize vararg calls unless the call site is not passing
2021   // any arguments.
2022   if (isVarArg && !Outs.empty())
2023     return false;
2024
2025   // Exception-handling functions need a special set of instructions to indicate
2026   // a return to the hardware. Tail-calling another function would probably
2027   // break this.
2028   if (CallerF->hasFnAttribute("interrupt"))
2029     return false;
2030
2031   // Also avoid sibcall optimization if either caller or callee uses struct
2032   // return semantics.
2033   if (isCalleeStructRet || isCallerStructRet)
2034     return false;
2035
2036   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2037   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2038   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2039   // support in the assembler and linker to be used. This would need to be
2040   // fixed to fully support tail calls in Thumb1.
2041   //
2042   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2043   // LR.  This means if we need to reload LR, it takes an extra instructions,
2044   // which outweighs the value of the tail call; but here we don't know yet
2045   // whether LR is going to be used.  Probably the right approach is to
2046   // generate the tail call here and turn it back into CALL/RET in
2047   // emitEpilogue if LR is used.
2048
2049   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2050   // but we need to make sure there are enough registers; the only valid
2051   // registers are the 4 used for parameters.  We don't currently do this
2052   // case.
2053   if (Subtarget->isThumb1Only())
2054     return false;
2055
2056   // Externally-defined functions with weak linkage should not be
2057   // tail-called on ARM when the OS does not support dynamic
2058   // pre-emption of symbols, as the AAELF spec requires normal calls
2059   // to undefined weak functions to be replaced with a NOP or jump to the
2060   // next instruction. The behaviour of branch instructions in this
2061   // situation (as used for tail calls) is implementation-defined, so we
2062   // cannot rely on the linker replacing the tail call with a return.
2063   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2064     const GlobalValue *GV = G->getGlobal();
2065     const Triple &TT = getTargetMachine().getTargetTriple();
2066     if (GV->hasExternalWeakLinkage() &&
2067         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2068       return false;
2069   }
2070
2071   // If the calling conventions do not match, then we'd better make sure the
2072   // results are returned in the same way as what the caller expects.
2073   if (!CCMatch) {
2074     SmallVector<CCValAssign, 16> RVLocs1;
2075     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2076                        *DAG.getContext(), Call);
2077     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2078
2079     SmallVector<CCValAssign, 16> RVLocs2;
2080     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2081                        *DAG.getContext(), Call);
2082     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2083
2084     if (RVLocs1.size() != RVLocs2.size())
2085       return false;
2086     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2087       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2088         return false;
2089       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2090         return false;
2091       if (RVLocs1[i].isRegLoc()) {
2092         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2093           return false;
2094       } else {
2095         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2096           return false;
2097       }
2098     }
2099   }
2100
2101   // If Caller's vararg or byval argument has been split between registers and
2102   // stack, do not perform tail call, since part of the argument is in caller's
2103   // local frame.
2104   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2105                                       getInfo<ARMFunctionInfo>();
2106   if (AFI_Caller->getArgRegsSaveSize())
2107     return false;
2108
2109   // If the callee takes no arguments then go on to check the results of the
2110   // call.
2111   if (!Outs.empty()) {
2112     // Check if stack adjustment is needed. For now, do not do this if any
2113     // argument is passed on the stack.
2114     SmallVector<CCValAssign, 16> ArgLocs;
2115     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2116                       *DAG.getContext(), Call);
2117     CCInfo.AnalyzeCallOperands(Outs,
2118                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2119     if (CCInfo.getNextStackOffset()) {
2120       MachineFunction &MF = DAG.getMachineFunction();
2121
2122       // Check if the arguments are already laid out in the right way as
2123       // the caller's fixed stack objects.
2124       MachineFrameInfo *MFI = MF.getFrameInfo();
2125       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2126       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2127       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2128            i != e;
2129            ++i, ++realArgIdx) {
2130         CCValAssign &VA = ArgLocs[i];
2131         EVT RegVT = VA.getLocVT();
2132         SDValue Arg = OutVals[realArgIdx];
2133         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2134         if (VA.getLocInfo() == CCValAssign::Indirect)
2135           return false;
2136         if (VA.needsCustom()) {
2137           // f64 and vector types are split into multiple registers or
2138           // register/stack-slot combinations.  The types will not match
2139           // the registers; give up on memory f64 refs until we figure
2140           // out what to do about this.
2141           if (!VA.isRegLoc())
2142             return false;
2143           if (!ArgLocs[++i].isRegLoc())
2144             return false;
2145           if (RegVT == MVT::v2f64) {
2146             if (!ArgLocs[++i].isRegLoc())
2147               return false;
2148             if (!ArgLocs[++i].isRegLoc())
2149               return false;
2150           }
2151         } else if (!VA.isRegLoc()) {
2152           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2153                                    MFI, MRI, TII))
2154             return false;
2155         }
2156       }
2157     }
2158   }
2159
2160   return true;
2161 }
2162
2163 bool
2164 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2165                                   MachineFunction &MF, bool isVarArg,
2166                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2167                                   LLVMContext &Context) const {
2168   SmallVector<CCValAssign, 16> RVLocs;
2169   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2170   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2171                                                     isVarArg));
2172 }
2173
2174 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2175                                     SDLoc DL, SelectionDAG &DAG) {
2176   const MachineFunction &MF = DAG.getMachineFunction();
2177   const Function *F = MF.getFunction();
2178
2179   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2180
2181   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2182   // version of the "preferred return address". These offsets affect the return
2183   // instruction if this is a return from PL1 without hypervisor extensions.
2184   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2185   //    SWI:     0      "subs pc, lr, #0"
2186   //    ABORT:   +4     "subs pc, lr, #4"
2187   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2188   // UNDEF varies depending on where the exception came from ARM or Thumb
2189   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2190
2191   int64_t LROffset;
2192   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2193       IntKind == "ABORT")
2194     LROffset = 4;
2195   else if (IntKind == "SWI" || IntKind == "UNDEF")
2196     LROffset = 0;
2197   else
2198     report_fatal_error("Unsupported interrupt attribute. If present, value "
2199                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2200
2201   RetOps.insert(RetOps.begin() + 1,
2202                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2203
2204   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2205 }
2206
2207 SDValue
2208 ARMTargetLowering::LowerReturn(SDValue Chain,
2209                                CallingConv::ID CallConv, bool isVarArg,
2210                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2211                                const SmallVectorImpl<SDValue> &OutVals,
2212                                SDLoc dl, SelectionDAG &DAG) const {
2213
2214   // CCValAssign - represent the assignment of the return value to a location.
2215   SmallVector<CCValAssign, 16> RVLocs;
2216
2217   // CCState - Info about the registers and stack slots.
2218   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2219                     *DAG.getContext(), Call);
2220
2221   // Analyze outgoing return values.
2222   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2223                                                isVarArg));
2224
2225   SDValue Flag;
2226   SmallVector<SDValue, 4> RetOps;
2227   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2228   bool isLittleEndian = Subtarget->isLittle();
2229
2230   MachineFunction &MF = DAG.getMachineFunction();
2231   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2232   AFI->setReturnRegsCount(RVLocs.size());
2233
2234   // Copy the result values into the output registers.
2235   for (unsigned i = 0, realRVLocIdx = 0;
2236        i != RVLocs.size();
2237        ++i, ++realRVLocIdx) {
2238     CCValAssign &VA = RVLocs[i];
2239     assert(VA.isRegLoc() && "Can only return in registers!");
2240
2241     SDValue Arg = OutVals[realRVLocIdx];
2242
2243     switch (VA.getLocInfo()) {
2244     default: llvm_unreachable("Unknown loc info!");
2245     case CCValAssign::Full: break;
2246     case CCValAssign::BCvt:
2247       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2248       break;
2249     }
2250
2251     if (VA.needsCustom()) {
2252       if (VA.getLocVT() == MVT::v2f64) {
2253         // Extract the first half and return it in two registers.
2254         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2255                                    DAG.getConstant(0, dl, MVT::i32));
2256         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2257                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2258
2259         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2260                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2261                                  Flag);
2262         Flag = Chain.getValue(1);
2263         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264         VA = RVLocs[++i]; // skip ahead to next loc
2265         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2266                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2267                                  Flag);
2268         Flag = Chain.getValue(1);
2269         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2270         VA = RVLocs[++i]; // skip ahead to next loc
2271
2272         // Extract the 2nd half and fall through to handle it as an f64 value.
2273         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2274                           DAG.getConstant(1, dl, MVT::i32));
2275       }
2276       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2277       // available.
2278       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2279                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2280       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2281                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2282                                Flag);
2283       Flag = Chain.getValue(1);
2284       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2285       VA = RVLocs[++i]; // skip ahead to next loc
2286       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2287                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2288                                Flag);
2289     } else
2290       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2291
2292     // Guarantee that all emitted copies are
2293     // stuck together, avoiding something bad.
2294     Flag = Chain.getValue(1);
2295     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2296   }
2297
2298   // Update chain and glue.
2299   RetOps[0] = Chain;
2300   if (Flag.getNode())
2301     RetOps.push_back(Flag);
2302
2303   // CPUs which aren't M-class use a special sequence to return from
2304   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2305   // though we use "subs pc, lr, #N").
2306   //
2307   // M-class CPUs actually use a normal return sequence with a special
2308   // (hardware-provided) value in LR, so the normal code path works.
2309   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2310       !Subtarget->isMClass()) {
2311     if (Subtarget->isThumb1Only())
2312       report_fatal_error("interrupt attribute is not supported in Thumb1");
2313     return LowerInterruptReturn(RetOps, dl, DAG);
2314   }
2315
2316   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2317 }
2318
2319 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2320   if (N->getNumValues() != 1)
2321     return false;
2322   if (!N->hasNUsesOfValue(1, 0))
2323     return false;
2324
2325   SDValue TCChain = Chain;
2326   SDNode *Copy = *N->use_begin();
2327   if (Copy->getOpcode() == ISD::CopyToReg) {
2328     // If the copy has a glue operand, we conservatively assume it isn't safe to
2329     // perform a tail call.
2330     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2331       return false;
2332     TCChain = Copy->getOperand(0);
2333   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2334     SDNode *VMov = Copy;
2335     // f64 returned in a pair of GPRs.
2336     SmallPtrSet<SDNode*, 2> Copies;
2337     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2338          UI != UE; ++UI) {
2339       if (UI->getOpcode() != ISD::CopyToReg)
2340         return false;
2341       Copies.insert(*UI);
2342     }
2343     if (Copies.size() > 2)
2344       return false;
2345
2346     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2347          UI != UE; ++UI) {
2348       SDValue UseChain = UI->getOperand(0);
2349       if (Copies.count(UseChain.getNode()))
2350         // Second CopyToReg
2351         Copy = *UI;
2352       else {
2353         // We are at the top of this chain.
2354         // If the copy has a glue operand, we conservatively assume it
2355         // isn't safe to perform a tail call.
2356         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2357           return false;
2358         // First CopyToReg
2359         TCChain = UseChain;
2360       }
2361     }
2362   } else if (Copy->getOpcode() == ISD::BITCAST) {
2363     // f32 returned in a single GPR.
2364     if (!Copy->hasOneUse())
2365       return false;
2366     Copy = *Copy->use_begin();
2367     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2368       return false;
2369     // If the copy has a glue operand, we conservatively assume it isn't safe to
2370     // perform a tail call.
2371     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2372       return false;
2373     TCChain = Copy->getOperand(0);
2374   } else {
2375     return false;
2376   }
2377
2378   bool HasRet = false;
2379   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2380        UI != UE; ++UI) {
2381     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2382         UI->getOpcode() != ARMISD::INTRET_FLAG)
2383       return false;
2384     HasRet = true;
2385   }
2386
2387   if (!HasRet)
2388     return false;
2389
2390   Chain = TCChain;
2391   return true;
2392 }
2393
2394 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2395   if (!Subtarget->supportsTailCall())
2396     return false;
2397
2398   auto Attr =
2399       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2400   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2401     return false;
2402
2403   return !Subtarget->isThumb1Only();
2404 }
2405
2406 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2407 // and pass the lower and high parts through.
2408 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2409   SDLoc DL(Op);
2410   SDValue WriteValue = Op->getOperand(2);
2411
2412   // This function is only supposed to be called for i64 type argument.
2413   assert(WriteValue.getValueType() == MVT::i64
2414           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2415
2416   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2417                            DAG.getConstant(0, DL, MVT::i32));
2418   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2419                            DAG.getConstant(1, DL, MVT::i32));
2420   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2421   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2422 }
2423
2424 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2425 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2426 // one of the above mentioned nodes. It has to be wrapped because otherwise
2427 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2428 // be used to form addressing mode. These wrapped nodes will be selected
2429 // into MOVi.
2430 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2431   EVT PtrVT = Op.getValueType();
2432   // FIXME there is no actual debug info here
2433   SDLoc dl(Op);
2434   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2435   SDValue Res;
2436   if (CP->isMachineConstantPoolEntry())
2437     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2438                                     CP->getAlignment());
2439   else
2440     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2441                                     CP->getAlignment());
2442   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2443 }
2444
2445 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2446   return MachineJumpTableInfo::EK_Inline;
2447 }
2448
2449 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2450                                              SelectionDAG &DAG) const {
2451   MachineFunction &MF = DAG.getMachineFunction();
2452   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2453   unsigned ARMPCLabelIndex = 0;
2454   SDLoc DL(Op);
2455   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2456   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2457   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2458   SDValue CPAddr;
2459   if (RelocM == Reloc::Static) {
2460     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2461   } else {
2462     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2463     ARMPCLabelIndex = AFI->createPICLabelUId();
2464     ARMConstantPoolValue *CPV =
2465       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2466                                       ARMCP::CPBlockAddress, PCAdj);
2467     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2468   }
2469   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2470   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2471                                MachinePointerInfo::getConstantPool(),
2472                                false, false, false, 0);
2473   if (RelocM == Reloc::Static)
2474     return Result;
2475   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2476   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2477 }
2478
2479 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2480 SDValue
2481 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2482                                                  SelectionDAG &DAG) const {
2483   SDLoc dl(GA);
2484   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2485   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486   MachineFunction &MF = DAG.getMachineFunction();
2487   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2488   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2489   ARMConstantPoolValue *CPV =
2490     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2491                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2492   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2494   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2495                          MachinePointerInfo::getConstantPool(),
2496                          false, false, false, 0);
2497   SDValue Chain = Argument.getValue(1);
2498
2499   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2500   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2501
2502   // call __tls_get_addr.
2503   ArgListTy Args;
2504   ArgListEntry Entry;
2505   Entry.Node = Argument;
2506   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2507   Args.push_back(Entry);
2508
2509   // FIXME: is there useful debug info available here?
2510   TargetLowering::CallLoweringInfo CLI(DAG);
2511   CLI.setDebugLoc(dl).setChain(Chain)
2512     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2513                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2514                0);
2515
2516   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2517   return CallResult.first;
2518 }
2519
2520 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2521 // "local exec" model.
2522 SDValue
2523 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2524                                         SelectionDAG &DAG,
2525                                         TLSModel::Model model) const {
2526   const GlobalValue *GV = GA->getGlobal();
2527   SDLoc dl(GA);
2528   SDValue Offset;
2529   SDValue Chain = DAG.getEntryNode();
2530   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2531   // Get the Thread Pointer
2532   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2533
2534   if (model == TLSModel::InitialExec) {
2535     MachineFunction &MF = DAG.getMachineFunction();
2536     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2537     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2538     // Initial exec model.
2539     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2540     ARMConstantPoolValue *CPV =
2541       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2542                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2543                                       true);
2544     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2545     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2546     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2547                          MachinePointerInfo::getConstantPool(),
2548                          false, false, false, 0);
2549     Chain = Offset.getValue(1);
2550
2551     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2552     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2553
2554     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2555                          MachinePointerInfo::getConstantPool(),
2556                          false, false, false, 0);
2557   } else {
2558     // local exec model
2559     assert(model == TLSModel::LocalExec);
2560     ARMConstantPoolValue *CPV =
2561       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2562     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2564     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2565                          MachinePointerInfo::getConstantPool(),
2566                          false, false, false, 0);
2567   }
2568
2569   // The address of the thread local variable is the add of the thread
2570   // pointer with the offset of the variable.
2571   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2572 }
2573
2574 SDValue
2575 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2576   // TODO: implement the "local dynamic" model
2577   assert(Subtarget->isTargetELF() &&
2578          "TLS not implemented for non-ELF targets");
2579   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2580   if (DAG.getTarget().Options.EmulatedTLS)
2581     return LowerToTLSEmulatedModel(GA, DAG);
2582
2583   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2584
2585   switch (model) {
2586     case TLSModel::GeneralDynamic:
2587     case TLSModel::LocalDynamic:
2588       return LowerToTLSGeneralDynamicModel(GA, DAG);
2589     case TLSModel::InitialExec:
2590     case TLSModel::LocalExec:
2591       return LowerToTLSExecModels(GA, DAG, model);
2592   }
2593   llvm_unreachable("bogus TLS model");
2594 }
2595
2596 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2597                                                  SelectionDAG &DAG) const {
2598   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2599   SDLoc dl(Op);
2600   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2601   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2602     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2603     ARMConstantPoolValue *CPV =
2604       ARMConstantPoolConstant::Create(GV,
2605                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2606     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2607     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2608     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2609                                  CPAddr,
2610                                  MachinePointerInfo::getConstantPool(),
2611                                  false, false, false, 0);
2612     SDValue Chain = Result.getValue(1);
2613     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2614     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2615     if (!UseGOTOFF)
2616       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2617                            MachinePointerInfo::getGOT(),
2618                            false, false, false, 0);
2619     return Result;
2620   }
2621
2622   // If we have T2 ops, we can materialize the address directly via movt/movw
2623   // pair. This is always cheaper.
2624   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2625     ++NumMovwMovt;
2626     // FIXME: Once remat is capable of dealing with instructions with register
2627     // operands, expand this into two nodes.
2628     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2629                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2630   } else {
2631     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2632     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2633     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2634                        MachinePointerInfo::getConstantPool(),
2635                        false, false, false, 0);
2636   }
2637 }
2638
2639 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2640                                                     SelectionDAG &DAG) const {
2641   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2642   SDLoc dl(Op);
2643   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2644   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2645
2646   if (Subtarget->useMovt(DAG.getMachineFunction()))
2647     ++NumMovwMovt;
2648
2649   // FIXME: Once remat is capable of dealing with instructions with register
2650   // operands, expand this into multiple nodes
2651   unsigned Wrapper =
2652       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2653
2654   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2655   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2656
2657   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2658     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2659                          MachinePointerInfo::getGOT(), false, false, false, 0);
2660   return Result;
2661 }
2662
2663 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2664                                                      SelectionDAG &DAG) const {
2665   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2666   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2667          "Windows on ARM expects to use movw/movt");
2668
2669   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2670   const ARMII::TOF TargetFlags =
2671     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2672   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2673   SDValue Result;
2674   SDLoc DL(Op);
2675
2676   ++NumMovwMovt;
2677
2678   // FIXME: Once remat is capable of dealing with instructions with register
2679   // operands, expand this into two nodes.
2680   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2681                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2682                                                   TargetFlags));
2683   if (GV->hasDLLImportStorageClass())
2684     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2685                          MachinePointerInfo::getGOT(), false, false, false, 0);
2686   return Result;
2687 }
2688
2689 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2690                                                     SelectionDAG &DAG) const {
2691   assert(Subtarget->isTargetELF() &&
2692          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2693   MachineFunction &MF = DAG.getMachineFunction();
2694   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2695   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2696   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2697   SDLoc dl(Op);
2698   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2699   ARMConstantPoolValue *CPV =
2700     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2701                                   ARMPCLabelIndex, PCAdj);
2702   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2703   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2704   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2705                                MachinePointerInfo::getConstantPool(),
2706                                false, false, false, 0);
2707   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2708   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2709 }
2710
2711 SDValue
2712 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2713   SDLoc dl(Op);
2714   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2715   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2716                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2717                      Op.getOperand(1), Val);
2718 }
2719
2720 SDValue
2721 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2722   SDLoc dl(Op);
2723   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2724                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2725 }
2726
2727 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2728                                                       SelectionDAG &DAG) const {
2729   SDLoc dl(Op);
2730   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2731                      Op.getOperand(0));
2732 }
2733
2734 SDValue
2735 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2736                                           const ARMSubtarget *Subtarget) const {
2737   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2738   SDLoc dl(Op);
2739   switch (IntNo) {
2740   default: return SDValue();    // Don't custom lower most intrinsics.
2741   case Intrinsic::arm_rbit: {
2742     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2743            "RBIT intrinsic must have i32 type!");
2744     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2745   }
2746   case Intrinsic::arm_thread_pointer: {
2747     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2748     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2749   }
2750   case Intrinsic::eh_sjlj_lsda: {
2751     MachineFunction &MF = DAG.getMachineFunction();
2752     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2753     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2754     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2755     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2756     SDValue CPAddr;
2757     unsigned PCAdj = (RelocM != Reloc::PIC_)
2758       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2759     ARMConstantPoolValue *CPV =
2760       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2761                                       ARMCP::CPLSDA, PCAdj);
2762     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2763     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2764     SDValue Result =
2765       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2766                   MachinePointerInfo::getConstantPool(),
2767                   false, false, false, 0);
2768
2769     if (RelocM == Reloc::PIC_) {
2770       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2771       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2772     }
2773     return Result;
2774   }
2775   case Intrinsic::arm_neon_vmulls:
2776   case Intrinsic::arm_neon_vmullu: {
2777     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2778       ? ARMISD::VMULLs : ARMISD::VMULLu;
2779     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2780                        Op.getOperand(1), Op.getOperand(2));
2781   }
2782   }
2783 }
2784
2785 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2786                                  const ARMSubtarget *Subtarget) {
2787   // FIXME: handle "fence singlethread" more efficiently.
2788   SDLoc dl(Op);
2789   if (!Subtarget->hasDataBarrier()) {
2790     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2791     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2792     // here.
2793     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2794            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2795     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2796                        DAG.getConstant(0, dl, MVT::i32));
2797   }
2798
2799   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2800   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2801   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2802   if (Subtarget->isMClass()) {
2803     // Only a full system barrier exists in the M-class architectures.
2804     Domain = ARM_MB::SY;
2805   } else if (Subtarget->isSwift() && Ord == Release) {
2806     // Swift happens to implement ISHST barriers in a way that's compatible with
2807     // Release semantics but weaker than ISH so we'd be fools not to use
2808     // it. Beware: other processors probably don't!
2809     Domain = ARM_MB::ISHST;
2810   }
2811
2812   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2813                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2814                      DAG.getConstant(Domain, dl, MVT::i32));
2815 }
2816
2817 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2818                              const ARMSubtarget *Subtarget) {
2819   // ARM pre v5TE and Thumb1 does not have preload instructions.
2820   if (!(Subtarget->isThumb2() ||
2821         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2822     // Just preserve the chain.
2823     return Op.getOperand(0);
2824
2825   SDLoc dl(Op);
2826   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2827   if (!isRead &&
2828       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2829     // ARMv7 with MP extension has PLDW.
2830     return Op.getOperand(0);
2831
2832   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2833   if (Subtarget->isThumb()) {
2834     // Invert the bits.
2835     isRead = ~isRead & 1;
2836     isData = ~isData & 1;
2837   }
2838
2839   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2840                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2841                      DAG.getConstant(isData, dl, MVT::i32));
2842 }
2843
2844 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2845   MachineFunction &MF = DAG.getMachineFunction();
2846   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2847
2848   // vastart just stores the address of the VarArgsFrameIndex slot into the
2849   // memory location argument.
2850   SDLoc dl(Op);
2851   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2852   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2853   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2854   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2855                       MachinePointerInfo(SV), false, false, 0);
2856 }
2857
2858 SDValue
2859 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2860                                         SDValue &Root, SelectionDAG &DAG,
2861                                         SDLoc dl) const {
2862   MachineFunction &MF = DAG.getMachineFunction();
2863   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2864
2865   const TargetRegisterClass *RC;
2866   if (AFI->isThumb1OnlyFunction())
2867     RC = &ARM::tGPRRegClass;
2868   else
2869     RC = &ARM::GPRRegClass;
2870
2871   // Transform the arguments stored in physical registers into virtual ones.
2872   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2873   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2874
2875   SDValue ArgValue2;
2876   if (NextVA.isMemLoc()) {
2877     MachineFrameInfo *MFI = MF.getFrameInfo();
2878     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2879
2880     // Create load node to retrieve arguments from the stack.
2881     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2882     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2883                             MachinePointerInfo::getFixedStack(FI),
2884                             false, false, false, 0);
2885   } else {
2886     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2887     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2888   }
2889   if (!Subtarget->isLittle())
2890     std::swap (ArgValue, ArgValue2);
2891   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2892 }
2893
2894 // The remaining GPRs hold either the beginning of variable-argument
2895 // data, or the beginning of an aggregate passed by value (usually
2896 // byval).  Either way, we allocate stack slots adjacent to the data
2897 // provided by our caller, and store the unallocated registers there.
2898 // If this is a variadic function, the va_list pointer will begin with
2899 // these values; otherwise, this reassembles a (byval) structure that
2900 // was split between registers and memory.
2901 // Return: The frame index registers were stored into.
2902 int
2903 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2904                                   SDLoc dl, SDValue &Chain,
2905                                   const Value *OrigArg,
2906                                   unsigned InRegsParamRecordIdx,
2907                                   int ArgOffset,
2908                                   unsigned ArgSize) const {
2909   // Currently, two use-cases possible:
2910   // Case #1. Non-var-args function, and we meet first byval parameter.
2911   //          Setup first unallocated register as first byval register;
2912   //          eat all remained registers
2913   //          (these two actions are performed by HandleByVal method).
2914   //          Then, here, we initialize stack frame with
2915   //          "store-reg" instructions.
2916   // Case #2. Var-args function, that doesn't contain byval parameters.
2917   //          The same: eat all remained unallocated registers,
2918   //          initialize stack frame.
2919
2920   MachineFunction &MF = DAG.getMachineFunction();
2921   MachineFrameInfo *MFI = MF.getFrameInfo();
2922   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2923   unsigned RBegin, REnd;
2924   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2925     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2926   } else {
2927     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2928     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2929     REnd = ARM::R4;
2930   }
2931
2932   if (REnd != RBegin)
2933     ArgOffset = -4 * (ARM::R4 - RBegin);
2934
2935   auto PtrVT = getPointerTy(DAG.getDataLayout());
2936   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2937   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2938
2939   SmallVector<SDValue, 4> MemOps;
2940   const TargetRegisterClass *RC =
2941       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2942
2943   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2944     unsigned VReg = MF.addLiveIn(Reg, RC);
2945     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2946     SDValue Store =
2947         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2948                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2949     MemOps.push_back(Store);
2950     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2951   }
2952
2953   if (!MemOps.empty())
2954     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2955   return FrameIndex;
2956 }
2957
2958 // Setup stack frame, the va_list pointer will start from.
2959 void
2960 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2961                                         SDLoc dl, SDValue &Chain,
2962                                         unsigned ArgOffset,
2963                                         unsigned TotalArgRegsSaveSize,
2964                                         bool ForceMutable) const {
2965   MachineFunction &MF = DAG.getMachineFunction();
2966   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2967
2968   // Try to store any remaining integer argument regs
2969   // to their spots on the stack so that they may be loaded by deferencing
2970   // the result of va_next.
2971   // If there is no regs to be stored, just point address after last
2972   // argument passed via stack.
2973   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2974                                   CCInfo.getInRegsParamsCount(),
2975                                   CCInfo.getNextStackOffset(), 4);
2976   AFI->setVarArgsFrameIndex(FrameIndex);
2977 }
2978
2979 SDValue
2980 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2981                                         CallingConv::ID CallConv, bool isVarArg,
2982                                         const SmallVectorImpl<ISD::InputArg>
2983                                           &Ins,
2984                                         SDLoc dl, SelectionDAG &DAG,
2985                                         SmallVectorImpl<SDValue> &InVals)
2986                                           const {
2987   MachineFunction &MF = DAG.getMachineFunction();
2988   MachineFrameInfo *MFI = MF.getFrameInfo();
2989
2990   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2991
2992   // Assign locations to all of the incoming arguments.
2993   SmallVector<CCValAssign, 16> ArgLocs;
2994   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2995                     *DAG.getContext(), Prologue);
2996   CCInfo.AnalyzeFormalArguments(Ins,
2997                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2998                                                   isVarArg));
2999
3000   SmallVector<SDValue, 16> ArgValues;
3001   SDValue ArgValue;
3002   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3003   unsigned CurArgIdx = 0;
3004
3005   // Initially ArgRegsSaveSize is zero.
3006   // Then we increase this value each time we meet byval parameter.
3007   // We also increase this value in case of varargs function.
3008   AFI->setArgRegsSaveSize(0);
3009
3010   // Calculate the amount of stack space that we need to allocate to store
3011   // byval and variadic arguments that are passed in registers.
3012   // We need to know this before we allocate the first byval or variadic
3013   // argument, as they will be allocated a stack slot below the CFA (Canonical
3014   // Frame Address, the stack pointer at entry to the function).
3015   unsigned ArgRegBegin = ARM::R4;
3016   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3017     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3018       break;
3019
3020     CCValAssign &VA = ArgLocs[i];
3021     unsigned Index = VA.getValNo();
3022     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3023     if (!Flags.isByVal())
3024       continue;
3025
3026     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3027     unsigned RBegin, REnd;
3028     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3029     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3030
3031     CCInfo.nextInRegsParam();
3032   }
3033   CCInfo.rewindByValRegsInfo();
3034
3035   int lastInsIndex = -1;
3036   if (isVarArg && MFI->hasVAStart()) {
3037     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3038     if (RegIdx != array_lengthof(GPRArgRegs))
3039       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3040   }
3041
3042   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3043   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3044   auto PtrVT = getPointerTy(DAG.getDataLayout());
3045
3046   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3047     CCValAssign &VA = ArgLocs[i];
3048     if (Ins[VA.getValNo()].isOrigArg()) {
3049       std::advance(CurOrigArg,
3050                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3051       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3052     }
3053     // Arguments stored in registers.
3054     if (VA.isRegLoc()) {
3055       EVT RegVT = VA.getLocVT();
3056
3057       if (VA.needsCustom()) {
3058         // f64 and vector types are split up into multiple registers or
3059         // combinations of registers and stack slots.
3060         if (VA.getLocVT() == MVT::v2f64) {
3061           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3062                                                    Chain, DAG, dl);
3063           VA = ArgLocs[++i]; // skip ahead to next loc
3064           SDValue ArgValue2;
3065           if (VA.isMemLoc()) {
3066             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3067             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3068             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3069                                     MachinePointerInfo::getFixedStack(FI),
3070                                     false, false, false, 0);
3071           } else {
3072             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3073                                              Chain, DAG, dl);
3074           }
3075           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3076           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3077                                  ArgValue, ArgValue1,
3078                                  DAG.getIntPtrConstant(0, dl));
3079           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3080                                  ArgValue, ArgValue2,
3081                                  DAG.getIntPtrConstant(1, dl));
3082         } else
3083           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3084
3085       } else {
3086         const TargetRegisterClass *RC;
3087
3088         if (RegVT == MVT::f32)
3089           RC = &ARM::SPRRegClass;
3090         else if (RegVT == MVT::f64)
3091           RC = &ARM::DPRRegClass;
3092         else if (RegVT == MVT::v2f64)
3093           RC = &ARM::QPRRegClass;
3094         else if (RegVT == MVT::i32)
3095           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3096                                            : &ARM::GPRRegClass;
3097         else
3098           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3099
3100         // Transform the arguments in physical registers into virtual ones.
3101         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3102         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3103       }
3104
3105       // If this is an 8 or 16-bit value, it is really passed promoted
3106       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3107       // truncate to the right size.
3108       switch (VA.getLocInfo()) {
3109       default: llvm_unreachable("Unknown loc info!");
3110       case CCValAssign::Full: break;
3111       case CCValAssign::BCvt:
3112         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3113         break;
3114       case CCValAssign::SExt:
3115         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3116                                DAG.getValueType(VA.getValVT()));
3117         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3118         break;
3119       case CCValAssign::ZExt:
3120         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3121                                DAG.getValueType(VA.getValVT()));
3122         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3123         break;
3124       }
3125
3126       InVals.push_back(ArgValue);
3127
3128     } else { // VA.isRegLoc()
3129
3130       // sanity check
3131       assert(VA.isMemLoc());
3132       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3133
3134       int index = VA.getValNo();
3135
3136       // Some Ins[] entries become multiple ArgLoc[] entries.
3137       // Process them only once.
3138       if (index != lastInsIndex)
3139         {
3140           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3141           // FIXME: For now, all byval parameter objects are marked mutable.
3142           // This can be changed with more analysis.
3143           // In case of tail call optimization mark all arguments mutable.
3144           // Since they could be overwritten by lowering of arguments in case of
3145           // a tail call.
3146           if (Flags.isByVal()) {
3147             assert(Ins[index].isOrigArg() &&
3148                    "Byval arguments cannot be implicit");
3149             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3150
3151             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3152                                             CurByValIndex, VA.getLocMemOffset(),
3153                                             Flags.getByValSize());
3154             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3155             CCInfo.nextInRegsParam();
3156           } else {
3157             unsigned FIOffset = VA.getLocMemOffset();
3158             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3159                                             FIOffset, true);
3160
3161             // Create load nodes to retrieve arguments from the stack.
3162             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3163             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3164                                          MachinePointerInfo::getFixedStack(FI),
3165                                          false, false, false, 0));
3166           }
3167           lastInsIndex = index;
3168         }
3169     }
3170   }
3171
3172   // varargs
3173   if (isVarArg && MFI->hasVAStart())
3174     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3175                          CCInfo.getNextStackOffset(),
3176                          TotalArgRegsSaveSize);
3177
3178   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3179
3180   return Chain;
3181 }
3182
3183 /// isFloatingPointZero - Return true if this is +0.0.
3184 static bool isFloatingPointZero(SDValue Op) {
3185   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3186     return CFP->getValueAPF().isPosZero();
3187   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3188     // Maybe this has already been legalized into the constant pool?
3189     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3190       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3191       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3192         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3193           return CFP->getValueAPF().isPosZero();
3194     }
3195   } else if (Op->getOpcode() == ISD::BITCAST &&
3196              Op->getValueType(0) == MVT::f64) {
3197     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3198     // created by LowerConstantFP().
3199     SDValue BitcastOp = Op->getOperand(0);
3200     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3201       SDValue MoveOp = BitcastOp->getOperand(0);
3202       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3203           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3204         return true;
3205       }
3206     }
3207   }
3208   return false;
3209 }
3210
3211 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3212 /// the given operands.
3213 SDValue
3214 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3215                              SDValue &ARMcc, SelectionDAG &DAG,
3216                              SDLoc dl) const {
3217   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3218     unsigned C = RHSC->getZExtValue();
3219     if (!isLegalICmpImmediate(C)) {
3220       // Constant does not fit, try adjusting it by one?
3221       switch (CC) {
3222       default: break;
3223       case ISD::SETLT:
3224       case ISD::SETGE:
3225         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3226           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3227           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3228         }
3229         break;
3230       case ISD::SETULT:
3231       case ISD::SETUGE:
3232         if (C != 0 && isLegalICmpImmediate(C-1)) {
3233           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3234           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3235         }
3236         break;
3237       case ISD::SETLE:
3238       case ISD::SETGT:
3239         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3240           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3241           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3242         }
3243         break;
3244       case ISD::SETULE:
3245       case ISD::SETUGT:
3246         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3247           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3248           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3249         }
3250         break;
3251       }
3252     }
3253   }
3254
3255   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3256   ARMISD::NodeType CompareType;
3257   switch (CondCode) {
3258   default:
3259     CompareType = ARMISD::CMP;
3260     break;
3261   case ARMCC::EQ:
3262   case ARMCC::NE:
3263     // Uses only Z Flag
3264     CompareType = ARMISD::CMPZ;
3265     break;
3266   }
3267   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3268   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3269 }
3270
3271 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3272 SDValue
3273 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3274                              SDLoc dl) const {
3275   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3276   SDValue Cmp;
3277   if (!isFloatingPointZero(RHS))
3278     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3279   else
3280     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3281   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3282 }
3283
3284 /// duplicateCmp - Glue values can have only one use, so this function
3285 /// duplicates a comparison node.
3286 SDValue
3287 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3288   unsigned Opc = Cmp.getOpcode();
3289   SDLoc DL(Cmp);
3290   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3291     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3292
3293   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3294   Cmp = Cmp.getOperand(0);
3295   Opc = Cmp.getOpcode();
3296   if (Opc == ARMISD::CMPFP)
3297     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3298   else {
3299     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3300     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3301   }
3302   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3303 }
3304
3305 std::pair<SDValue, SDValue>
3306 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3307                                  SDValue &ARMcc) const {
3308   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3309
3310   SDValue Value, OverflowCmp;
3311   SDValue LHS = Op.getOperand(0);
3312   SDValue RHS = Op.getOperand(1);
3313   SDLoc dl(Op);
3314
3315   // FIXME: We are currently always generating CMPs because we don't support
3316   // generating CMN through the backend. This is not as good as the natural
3317   // CMP case because it causes a register dependency and cannot be folded
3318   // later.
3319
3320   switch (Op.getOpcode()) {
3321   default:
3322     llvm_unreachable("Unknown overflow instruction!");
3323   case ISD::SADDO:
3324     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3325     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3326     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3327     break;
3328   case ISD::UADDO:
3329     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3330     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3331     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3332     break;
3333   case ISD::SSUBO:
3334     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3335     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3336     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3337     break;
3338   case ISD::USUBO:
3339     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3340     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3341     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3342     break;
3343   } // switch (...)
3344
3345   return std::make_pair(Value, OverflowCmp);
3346 }
3347
3348
3349 SDValue
3350 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3351   // Let legalize expand this if it isn't a legal type yet.
3352   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3353     return SDValue();
3354
3355   SDValue Value, OverflowCmp;
3356   SDValue ARMcc;
3357   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3358   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3359   SDLoc dl(Op);
3360   // We use 0 and 1 as false and true values.
3361   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3362   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3363   EVT VT = Op.getValueType();
3364
3365   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3366                                  ARMcc, CCR, OverflowCmp);
3367
3368   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3369   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3370 }
3371
3372
3373 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3374   SDValue Cond = Op.getOperand(0);
3375   SDValue SelectTrue = Op.getOperand(1);
3376   SDValue SelectFalse = Op.getOperand(2);
3377   SDLoc dl(Op);
3378   unsigned Opc = Cond.getOpcode();
3379
3380   if (Cond.getResNo() == 1 &&
3381       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3382        Opc == ISD::USUBO)) {
3383     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3384       return SDValue();
3385
3386     SDValue Value, OverflowCmp;
3387     SDValue ARMcc;
3388     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3389     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3390     EVT VT = Op.getValueType();
3391
3392     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3393                    OverflowCmp, DAG);
3394   }
3395
3396   // Convert:
3397   //
3398   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3399   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3400   //
3401   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3402     const ConstantSDNode *CMOVTrue =
3403       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3404     const ConstantSDNode *CMOVFalse =
3405       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3406
3407     if (CMOVTrue && CMOVFalse) {
3408       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3409       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3410
3411       SDValue True;
3412       SDValue False;
3413       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3414         True = SelectTrue;
3415         False = SelectFalse;
3416       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3417         True = SelectFalse;
3418         False = SelectTrue;
3419       }
3420
3421       if (True.getNode() && False.getNode()) {
3422         EVT VT = Op.getValueType();
3423         SDValue ARMcc = Cond.getOperand(2);
3424         SDValue CCR = Cond.getOperand(3);
3425         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3426         assert(True.getValueType() == VT);
3427         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3428       }
3429     }
3430   }
3431
3432   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3433   // undefined bits before doing a full-word comparison with zero.
3434   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3435                      DAG.getConstant(1, dl, Cond.getValueType()));
3436
3437   return DAG.getSelectCC(dl, Cond,
3438                          DAG.getConstant(0, dl, Cond.getValueType()),
3439                          SelectTrue, SelectFalse, ISD::SETNE);
3440 }
3441
3442 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3443                                  bool &swpCmpOps, bool &swpVselOps) {
3444   // Start by selecting the GE condition code for opcodes that return true for
3445   // 'equality'
3446   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3447       CC == ISD::SETULE)
3448     CondCode = ARMCC::GE;
3449
3450   // and GT for opcodes that return false for 'equality'.
3451   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3452            CC == ISD::SETULT)
3453     CondCode = ARMCC::GT;
3454
3455   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3456   // to swap the compare operands.
3457   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3458       CC == ISD::SETULT)
3459     swpCmpOps = true;
3460
3461   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3462   // If we have an unordered opcode, we need to swap the operands to the VSEL
3463   // instruction (effectively negating the condition).
3464   //
3465   // This also has the effect of swapping which one of 'less' or 'greater'
3466   // returns true, so we also swap the compare operands. It also switches
3467   // whether we return true for 'equality', so we compensate by picking the
3468   // opposite condition code to our original choice.
3469   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3470       CC == ISD::SETUGT) {
3471     swpCmpOps = !swpCmpOps;
3472     swpVselOps = !swpVselOps;
3473     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3474   }
3475
3476   // 'ordered' is 'anything but unordered', so use the VS condition code and
3477   // swap the VSEL operands.
3478   if (CC == ISD::SETO) {
3479     CondCode = ARMCC::VS;
3480     swpVselOps = true;
3481   }
3482
3483   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3484   // code and swap the VSEL operands.
3485   if (CC == ISD::SETUNE) {
3486     CondCode = ARMCC::EQ;
3487     swpVselOps = true;
3488   }
3489 }
3490
3491 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3492                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3493                                    SDValue Cmp, SelectionDAG &DAG) const {
3494   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3495     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3496                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3497     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3498                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3499
3500     SDValue TrueLow = TrueVal.getValue(0);
3501     SDValue TrueHigh = TrueVal.getValue(1);
3502     SDValue FalseLow = FalseVal.getValue(0);
3503     SDValue FalseHigh = FalseVal.getValue(1);
3504
3505     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3506                               ARMcc, CCR, Cmp);
3507     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3508                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3509
3510     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3511   } else {
3512     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3513                        Cmp);
3514   }
3515 }
3516
3517 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3518   EVT VT = Op.getValueType();
3519   SDValue LHS = Op.getOperand(0);
3520   SDValue RHS = Op.getOperand(1);
3521   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3522   SDValue TrueVal = Op.getOperand(2);
3523   SDValue FalseVal = Op.getOperand(3);
3524   SDLoc dl(Op);
3525
3526   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3527     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3528                                                     dl);
3529
3530     // If softenSetCCOperands only returned one value, we should compare it to
3531     // zero.
3532     if (!RHS.getNode()) {
3533       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3534       CC = ISD::SETNE;
3535     }
3536   }
3537
3538   if (LHS.getValueType() == MVT::i32) {
3539     // Try to generate VSEL on ARMv8.
3540     // The VSEL instruction can't use all the usual ARM condition
3541     // codes: it only has two bits to select the condition code, so it's
3542     // constrained to use only GE, GT, VS and EQ.
3543     //
3544     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3545     // swap the operands of the previous compare instruction (effectively
3546     // inverting the compare condition, swapping 'less' and 'greater') and
3547     // sometimes need to swap the operands to the VSEL (which inverts the
3548     // condition in the sense of firing whenever the previous condition didn't)
3549     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3550                                     TrueVal.getValueType() == MVT::f64)) {
3551       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3552       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3553           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3554         CC = ISD::getSetCCInverse(CC, true);
3555         std::swap(TrueVal, FalseVal);
3556       }
3557     }
3558
3559     SDValue ARMcc;
3560     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3561     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3562     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3563   }
3564
3565   ARMCC::CondCodes CondCode, CondCode2;
3566   FPCCToARMCC(CC, CondCode, CondCode2);
3567
3568   // Try to generate VMAXNM/VMINNM on ARMv8.
3569   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3570                                   TrueVal.getValueType() == MVT::f64)) {
3571     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3572     // same operands, as follows:
3573     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3574     //   select c, a, b
3575     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3576     bool swapSides = false;
3577     if (!getTargetMachine().Options.NoNaNsFPMath) {
3578       // transformability may depend on which way around we compare
3579       switch (CC) {
3580       default:
3581         break;
3582       case ISD::SETOGT:
3583       case ISD::SETOGE:
3584       case ISD::SETOLT:
3585       case ISD::SETOLE:
3586         // the non-NaN should be RHS
3587         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3588         break;
3589       case ISD::SETUGT:
3590       case ISD::SETUGE:
3591       case ISD::SETULT:
3592       case ISD::SETULE:
3593         // the non-NaN should be LHS
3594         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3595         break;
3596       }
3597     }
3598     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3599     if (swapSides) {
3600       CC = ISD::getSetCCSwappedOperands(CC);
3601       std::swap(LHS, RHS);
3602     }
3603     if (LHS == TrueVal && RHS == FalseVal) {
3604       bool canTransform = true;
3605       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3606       if (!getTargetMachine().Options.UnsafeFPMath &&
3607           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3608         const ConstantFPSDNode *Zero;
3609         switch (CC) {
3610         default:
3611           break;
3612         case ISD::SETOGT:
3613         case ISD::SETUGT:
3614         case ISD::SETGT:
3615           // RHS must not be -0
3616           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3617                          !Zero->isNegative();
3618           break;
3619         case ISD::SETOGE:
3620         case ISD::SETUGE:
3621         case ISD::SETGE:
3622           // LHS must not be -0
3623           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3624                          !Zero->isNegative();
3625           break;
3626         case ISD::SETOLT:
3627         case ISD::SETULT:
3628         case ISD::SETLT:
3629           // RHS must not be +0
3630           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3631                           Zero->isNegative();
3632           break;
3633         case ISD::SETOLE:
3634         case ISD::SETULE:
3635         case ISD::SETLE:
3636           // LHS must not be +0
3637           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3638                           Zero->isNegative();
3639           break;
3640         }
3641       }
3642       if (canTransform) {
3643         // Note: If one of the elements in a pair is a number and the other
3644         // element is NaN, the corresponding result element is the number.
3645         // This is consistent with the IEEE 754-2008 standard.
3646         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3647         switch (CC) {
3648         default:
3649           break;
3650         case ISD::SETOGT:
3651         case ISD::SETOGE:
3652           if (!DAG.isKnownNeverNaN(RHS))
3653             break;
3654           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3655         case ISD::SETUGT:
3656         case ISD::SETUGE:
3657           if (!DAG.isKnownNeverNaN(LHS))
3658             break;
3659         case ISD::SETGT:
3660         case ISD::SETGE:
3661           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3662         case ISD::SETOLT:
3663         case ISD::SETOLE:
3664           if (!DAG.isKnownNeverNaN(RHS))
3665             break;
3666           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3667         case ISD::SETULT:
3668         case ISD::SETULE:
3669           if (!DAG.isKnownNeverNaN(LHS))
3670             break;
3671         case ISD::SETLT:
3672         case ISD::SETLE:
3673           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3674         }
3675       }
3676     }
3677
3678     bool swpCmpOps = false;
3679     bool swpVselOps = false;
3680     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3681
3682     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3683         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3684       if (swpCmpOps)
3685         std::swap(LHS, RHS);
3686       if (swpVselOps)
3687         std::swap(TrueVal, FalseVal);
3688     }
3689   }
3690
3691   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3692   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3693   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3694   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3695   if (CondCode2 != ARMCC::AL) {
3696     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3697     // FIXME: Needs another CMP because flag can have but one use.
3698     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3699     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3700   }
3701   return Result;
3702 }
3703
3704 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3705 /// to morph to an integer compare sequence.
3706 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3707                            const ARMSubtarget *Subtarget) {
3708   SDNode *N = Op.getNode();
3709   if (!N->hasOneUse())
3710     // Otherwise it requires moving the value from fp to integer registers.
3711     return false;
3712   if (!N->getNumValues())
3713     return false;
3714   EVT VT = Op.getValueType();
3715   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3716     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3717     // vmrs are very slow, e.g. cortex-a8.
3718     return false;
3719
3720   if (isFloatingPointZero(Op)) {
3721     SeenZero = true;
3722     return true;
3723   }
3724   return ISD::isNormalLoad(N);
3725 }
3726
3727 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3728   if (isFloatingPointZero(Op))
3729     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3730
3731   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3732     return DAG.getLoad(MVT::i32, SDLoc(Op),
3733                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3734                        Ld->isVolatile(), Ld->isNonTemporal(),
3735                        Ld->isInvariant(), Ld->getAlignment());
3736
3737   llvm_unreachable("Unknown VFP cmp argument!");
3738 }
3739
3740 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3741                            SDValue &RetVal1, SDValue &RetVal2) {
3742   SDLoc dl(Op);
3743
3744   if (isFloatingPointZero(Op)) {
3745     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3746     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3747     return;
3748   }
3749
3750   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3751     SDValue Ptr = Ld->getBasePtr();
3752     RetVal1 = DAG.getLoad(MVT::i32, dl,
3753                           Ld->getChain(), Ptr,
3754                           Ld->getPointerInfo(),
3755                           Ld->isVolatile(), Ld->isNonTemporal(),
3756                           Ld->isInvariant(), Ld->getAlignment());
3757
3758     EVT PtrType = Ptr.getValueType();
3759     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3760     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3761                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3762     RetVal2 = DAG.getLoad(MVT::i32, dl,
3763                           Ld->getChain(), NewPtr,
3764                           Ld->getPointerInfo().getWithOffset(4),
3765                           Ld->isVolatile(), Ld->isNonTemporal(),
3766                           Ld->isInvariant(), NewAlign);
3767     return;
3768   }
3769
3770   llvm_unreachable("Unknown VFP cmp argument!");
3771 }
3772
3773 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3774 /// f32 and even f64 comparisons to integer ones.
3775 SDValue
3776 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3777   SDValue Chain = Op.getOperand(0);
3778   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3779   SDValue LHS = Op.getOperand(2);
3780   SDValue RHS = Op.getOperand(3);
3781   SDValue Dest = Op.getOperand(4);
3782   SDLoc dl(Op);
3783
3784   bool LHSSeenZero = false;
3785   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3786   bool RHSSeenZero = false;
3787   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3788   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3789     // If unsafe fp math optimization is enabled and there are no other uses of
3790     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3791     // to an integer comparison.
3792     if (CC == ISD::SETOEQ)
3793       CC = ISD::SETEQ;
3794     else if (CC == ISD::SETUNE)
3795       CC = ISD::SETNE;
3796
3797     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3798     SDValue ARMcc;
3799     if (LHS.getValueType() == MVT::f32) {
3800       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3801                         bitcastf32Toi32(LHS, DAG), Mask);
3802       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3803                         bitcastf32Toi32(RHS, DAG), Mask);
3804       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3805       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3806       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3807                          Chain, Dest, ARMcc, CCR, Cmp);
3808     }
3809
3810     SDValue LHS1, LHS2;
3811     SDValue RHS1, RHS2;
3812     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3813     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3814     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3815     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3816     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3817     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3818     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3819     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3820     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3821   }
3822
3823   return SDValue();
3824 }
3825
3826 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3827   SDValue Chain = Op.getOperand(0);
3828   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3829   SDValue LHS = Op.getOperand(2);
3830   SDValue RHS = Op.getOperand(3);
3831   SDValue Dest = Op.getOperand(4);
3832   SDLoc dl(Op);
3833
3834   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3835     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3836                                                     dl);
3837
3838     // If softenSetCCOperands only returned one value, we should compare it to
3839     // zero.
3840     if (!RHS.getNode()) {
3841       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3842       CC = ISD::SETNE;
3843     }
3844   }
3845
3846   if (LHS.getValueType() == MVT::i32) {
3847     SDValue ARMcc;
3848     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3849     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3850     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3851                        Chain, Dest, ARMcc, CCR, Cmp);
3852   }
3853
3854   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3855
3856   if (getTargetMachine().Options.UnsafeFPMath &&
3857       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3858        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3859     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3860     if (Result.getNode())
3861       return Result;
3862   }
3863
3864   ARMCC::CondCodes CondCode, CondCode2;
3865   FPCCToARMCC(CC, CondCode, CondCode2);
3866
3867   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3868   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3869   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3870   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3871   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3872   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3873   if (CondCode2 != ARMCC::AL) {
3874     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3875     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3876     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3877   }
3878   return Res;
3879 }
3880
3881 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3882   SDValue Chain = Op.getOperand(0);
3883   SDValue Table = Op.getOperand(1);
3884   SDValue Index = Op.getOperand(2);
3885   SDLoc dl(Op);
3886
3887   EVT PTy = getPointerTy(DAG.getDataLayout());
3888   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3889   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3890   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3891   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3892   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3893   if (Subtarget->isThumb2()) {
3894     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3895     // which does another jump to the destination. This also makes it easier
3896     // to translate it to TBB / TBH later.
3897     // FIXME: This might not work if the function is extremely large.
3898     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3899                        Addr, Op.getOperand(2), JTI);
3900   }
3901   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3902     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3903                        MachinePointerInfo::getJumpTable(),
3904                        false, false, false, 0);
3905     Chain = Addr.getValue(1);
3906     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3907     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3908   } else {
3909     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3910                        MachinePointerInfo::getJumpTable(),
3911                        false, false, false, 0);
3912     Chain = Addr.getValue(1);
3913     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3914   }
3915 }
3916
3917 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3918   EVT VT = Op.getValueType();
3919   SDLoc dl(Op);
3920
3921   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3922     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3923       return Op;
3924     return DAG.UnrollVectorOp(Op.getNode());
3925   }
3926
3927   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3928          "Invalid type for custom lowering!");
3929   if (VT != MVT::v4i16)
3930     return DAG.UnrollVectorOp(Op.getNode());
3931
3932   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3933   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3934 }
3935
3936 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3937   EVT VT = Op.getValueType();
3938   if (VT.isVector())
3939     return LowerVectorFP_TO_INT(Op, DAG);
3940   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3941     RTLIB::Libcall LC;
3942     if (Op.getOpcode() == ISD::FP_TO_SINT)
3943       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3944                               Op.getValueType());
3945     else
3946       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3947                               Op.getValueType());
3948     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3949                        /*isSigned*/ false, SDLoc(Op)).first;
3950   }
3951
3952   return Op;
3953 }
3954
3955 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3956   EVT VT = Op.getValueType();
3957   SDLoc dl(Op);
3958
3959   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3960     if (VT.getVectorElementType() == MVT::f32)
3961       return Op;
3962     return DAG.UnrollVectorOp(Op.getNode());
3963   }
3964
3965   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3966          "Invalid type for custom lowering!");
3967   if (VT != MVT::v4f32)
3968     return DAG.UnrollVectorOp(Op.getNode());
3969
3970   unsigned CastOpc;
3971   unsigned Opc;
3972   switch (Op.getOpcode()) {
3973   default: llvm_unreachable("Invalid opcode!");
3974   case ISD::SINT_TO_FP:
3975     CastOpc = ISD::SIGN_EXTEND;
3976     Opc = ISD::SINT_TO_FP;
3977     break;
3978   case ISD::UINT_TO_FP:
3979     CastOpc = ISD::ZERO_EXTEND;
3980     Opc = ISD::UINT_TO_FP;
3981     break;
3982   }
3983
3984   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3985   return DAG.getNode(Opc, dl, VT, Op);
3986 }
3987
3988 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3989   EVT VT = Op.getValueType();
3990   if (VT.isVector())
3991     return LowerVectorINT_TO_FP(Op, DAG);
3992   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3993     RTLIB::Libcall LC;
3994     if (Op.getOpcode() == ISD::SINT_TO_FP)
3995       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3996                               Op.getValueType());
3997     else
3998       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3999                               Op.getValueType());
4000     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4001                        /*isSigned*/ false, SDLoc(Op)).first;
4002   }
4003
4004   return Op;
4005 }
4006
4007 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4008   // Implement fcopysign with a fabs and a conditional fneg.
4009   SDValue Tmp0 = Op.getOperand(0);
4010   SDValue Tmp1 = Op.getOperand(1);
4011   SDLoc dl(Op);
4012   EVT VT = Op.getValueType();
4013   EVT SrcVT = Tmp1.getValueType();
4014   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4015     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4016   bool UseNEON = !InGPR && Subtarget->hasNEON();
4017
4018   if (UseNEON) {
4019     // Use VBSL to copy the sign bit.
4020     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4021     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4022                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4023     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4024     if (VT == MVT::f64)
4025       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4026                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4027                          DAG.getConstant(32, dl, MVT::i32));
4028     else /*if (VT == MVT::f32)*/
4029       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4030     if (SrcVT == MVT::f32) {
4031       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4032       if (VT == MVT::f64)
4033         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4034                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4035                            DAG.getConstant(32, dl, MVT::i32));
4036     } else if (VT == MVT::f32)
4037       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4038                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4039                          DAG.getConstant(32, dl, MVT::i32));
4040     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4041     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4042
4043     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4044                                             dl, MVT::i32);
4045     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4046     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4047                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4048
4049     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4050                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4051                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4052     if (VT == MVT::f32) {
4053       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4054       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4055                         DAG.getConstant(0, dl, MVT::i32));
4056     } else {
4057       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4058     }
4059
4060     return Res;
4061   }
4062
4063   // Bitcast operand 1 to i32.
4064   if (SrcVT == MVT::f64)
4065     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4066                        Tmp1).getValue(1);
4067   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4068
4069   // Or in the signbit with integer operations.
4070   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4071   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4072   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4073   if (VT == MVT::f32) {
4074     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4075                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4076     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4077                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4078   }
4079
4080   // f64: Or the high part with signbit and then combine two parts.
4081   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4082                      Tmp0);
4083   SDValue Lo = Tmp0.getValue(0);
4084   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4085   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4086   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4087 }
4088
4089 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4090   MachineFunction &MF = DAG.getMachineFunction();
4091   MachineFrameInfo *MFI = MF.getFrameInfo();
4092   MFI->setReturnAddressIsTaken(true);
4093
4094   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4095     return SDValue();
4096
4097   EVT VT = Op.getValueType();
4098   SDLoc dl(Op);
4099   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4100   if (Depth) {
4101     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4102     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4103     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4104                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4105                        MachinePointerInfo(), false, false, false, 0);
4106   }
4107
4108   // Return LR, which contains the return address. Mark it an implicit live-in.
4109   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4110   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4111 }
4112
4113 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4114   const ARMBaseRegisterInfo &ARI =
4115     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4116   MachineFunction &MF = DAG.getMachineFunction();
4117   MachineFrameInfo *MFI = MF.getFrameInfo();
4118   MFI->setFrameAddressIsTaken(true);
4119
4120   EVT VT = Op.getValueType();
4121   SDLoc dl(Op);  // FIXME probably not meaningful
4122   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4123   unsigned FrameReg = ARI.getFrameRegister(MF);
4124   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4125   while (Depth--)
4126     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4127                             MachinePointerInfo(),
4128                             false, false, false, 0);
4129   return FrameAddr;
4130 }
4131
4132 // FIXME? Maybe this could be a TableGen attribute on some registers and
4133 // this table could be generated automatically from RegInfo.
4134 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4135                                               SelectionDAG &DAG) const {
4136   unsigned Reg = StringSwitch<unsigned>(RegName)
4137                        .Case("sp", ARM::SP)
4138                        .Default(0);
4139   if (Reg)
4140     return Reg;
4141   report_fatal_error(Twine("Invalid register name \""
4142                               + StringRef(RegName)  + "\"."));
4143 }
4144
4145 // Result is 64 bit value so split into two 32 bit values and return as a
4146 // pair of values.
4147 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4148                                 SelectionDAG &DAG) {
4149   SDLoc DL(N);
4150
4151   // This function is only supposed to be called for i64 type destination.
4152   assert(N->getValueType(0) == MVT::i64
4153           && "ExpandREAD_REGISTER called for non-i64 type result.");
4154
4155   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4156                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4157                              N->getOperand(0),
4158                              N->getOperand(1));
4159
4160   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4161                     Read.getValue(1)));
4162   Results.push_back(Read.getOperand(0));
4163 }
4164
4165 /// ExpandBITCAST - If the target supports VFP, this function is called to
4166 /// expand a bit convert where either the source or destination type is i64 to
4167 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4168 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4169 /// vectors), since the legalizer won't know what to do with that.
4170 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172   SDLoc dl(N);
4173   SDValue Op = N->getOperand(0);
4174
4175   // This function is only supposed to be called for i64 types, either as the
4176   // source or destination of the bit convert.
4177   EVT SrcVT = Op.getValueType();
4178   EVT DstVT = N->getValueType(0);
4179   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4180          "ExpandBITCAST called for non-i64 type");
4181
4182   // Turn i64->f64 into VMOVDRR.
4183   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4184     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4185                              DAG.getConstant(0, dl, MVT::i32));
4186     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4187                              DAG.getConstant(1, dl, MVT::i32));
4188     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4189                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4190   }
4191
4192   // Turn f64->i64 into VMOVRRD.
4193   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4194     SDValue Cvt;
4195     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4196         SrcVT.getVectorNumElements() > 1)
4197       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4198                         DAG.getVTList(MVT::i32, MVT::i32),
4199                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4200     else
4201       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4202                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4203     // Merge the pieces into a single i64 value.
4204     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4205   }
4206
4207   return SDValue();
4208 }
4209
4210 /// getZeroVector - Returns a vector of specified type with all zero elements.
4211 /// Zero vectors are used to represent vector negation and in those cases
4212 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4213 /// not support i64 elements, so sometimes the zero vectors will need to be
4214 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4215 /// zero vector.
4216 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4217   assert(VT.isVector() && "Expected a vector type");
4218   // The canonical modified immediate encoding of a zero vector is....0!
4219   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4220   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4221   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4222   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4223 }
4224
4225 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4226 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4227 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4228                                                 SelectionDAG &DAG) const {
4229   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4230   EVT VT = Op.getValueType();
4231   unsigned VTBits = VT.getSizeInBits();
4232   SDLoc dl(Op);
4233   SDValue ShOpLo = Op.getOperand(0);
4234   SDValue ShOpHi = Op.getOperand(1);
4235   SDValue ShAmt  = Op.getOperand(2);
4236   SDValue ARMcc;
4237   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4238
4239   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4240
4241   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4242                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4243   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4244   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4245                                    DAG.getConstant(VTBits, dl, MVT::i32));
4246   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4247   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4248   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4249
4250   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4251   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4252                           ISD::SETGE, ARMcc, DAG, dl);
4253   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4254   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4255                            CCR, Cmp);
4256
4257   SDValue Ops[2] = { Lo, Hi };
4258   return DAG.getMergeValues(Ops, dl);
4259 }
4260
4261 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4262 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4263 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4264                                                SelectionDAG &DAG) const {
4265   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4266   EVT VT = Op.getValueType();
4267   unsigned VTBits = VT.getSizeInBits();
4268   SDLoc dl(Op);
4269   SDValue ShOpLo = Op.getOperand(0);
4270   SDValue ShOpHi = Op.getOperand(1);
4271   SDValue ShAmt  = Op.getOperand(2);
4272   SDValue ARMcc;
4273
4274   assert(Op.getOpcode() == ISD::SHL_PARTS);
4275   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4276                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4277   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4278   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4279                                    DAG.getConstant(VTBits, dl, MVT::i32));
4280   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4281   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4282
4283   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4284   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4285   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4286                           ISD::SETGE, ARMcc, DAG, dl);
4287   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4288   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4289                            CCR, Cmp);
4290
4291   SDValue Ops[2] = { Lo, Hi };
4292   return DAG.getMergeValues(Ops, dl);
4293 }
4294
4295 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4296                                             SelectionDAG &DAG) const {
4297   // The rounding mode is in bits 23:22 of the FPSCR.
4298   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4299   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4300   // so that the shift + and get folded into a bitfield extract.
4301   SDLoc dl(Op);
4302   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4303                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4304                                               MVT::i32));
4305   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4306                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4307   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4308                               DAG.getConstant(22, dl, MVT::i32));
4309   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4310                      DAG.getConstant(3, dl, MVT::i32));
4311 }
4312
4313 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4314                          const ARMSubtarget *ST) {
4315   SDLoc dl(N);
4316   EVT VT = N->getValueType(0);
4317   if (VT.isVector()) {
4318     assert(ST->hasNEON());
4319
4320     // Compute the least significant set bit: LSB = X & -X
4321     SDValue X = N->getOperand(0);
4322     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4323     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4324
4325     EVT ElemTy = VT.getVectorElementType();
4326
4327     if (ElemTy == MVT::i8) {
4328       // Compute with: cttz(x) = ctpop(lsb - 1)
4329       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4330                                 DAG.getTargetConstant(1, dl, ElemTy));
4331       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4332       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4333     }
4334
4335     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4336         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4337       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4338       unsigned NumBits = ElemTy.getSizeInBits();
4339       SDValue WidthMinus1 =
4340           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4341                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4342       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4343       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4344     }
4345
4346     // Compute with: cttz(x) = ctpop(lsb - 1)
4347
4348     // Since we can only compute the number of bits in a byte with vcnt.8, we
4349     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4350     // and i64.
4351
4352     // Compute LSB - 1.
4353     SDValue Bits;
4354     if (ElemTy == MVT::i64) {
4355       // Load constant 0xffff'ffff'ffff'ffff to register.
4356       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4357                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4358       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4359     } else {
4360       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4361                                 DAG.getTargetConstant(1, dl, ElemTy));
4362       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4363     }
4364
4365     // Count #bits with vcnt.8.
4366     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4367     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4368     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4369
4370     // Gather the #bits with vpaddl (pairwise add.)
4371     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4372     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4373         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4374         Cnt8);
4375     if (ElemTy == MVT::i16)
4376       return Cnt16;
4377
4378     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4379     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4380         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4381         Cnt16);
4382     if (ElemTy == MVT::i32)
4383       return Cnt32;
4384
4385     assert(ElemTy == MVT::i64);
4386     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4387         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4388         Cnt32);
4389     return Cnt64;
4390   }
4391
4392   if (!ST->hasV6T2Ops())
4393     return SDValue();
4394
4395   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4396   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4397 }
4398
4399 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4400 /// for each 16-bit element from operand, repeated.  The basic idea is to
4401 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4402 ///
4403 /// Trace for v4i16:
4404 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4405 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4406 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4407 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4408 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4409 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4410 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4411 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4412 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4413   EVT VT = N->getValueType(0);
4414   SDLoc DL(N);
4415
4416   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4417   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4418   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4419   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4420   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4421   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4422 }
4423
4424 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4425 /// bit-count for each 16-bit element from the operand.  We need slightly
4426 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4427 /// 64/128-bit registers.
4428 ///
4429 /// Trace for v4i16:
4430 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4431 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4432 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4433 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4434 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4435   EVT VT = N->getValueType(0);
4436   SDLoc DL(N);
4437
4438   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4439   if (VT.is64BitVector()) {
4440     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4441     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4442                        DAG.getIntPtrConstant(0, DL));
4443   } else {
4444     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4445                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4446     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4447   }
4448 }
4449
4450 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4451 /// bit-count for each 32-bit element from the operand.  The idea here is
4452 /// to split the vector into 16-bit elements, leverage the 16-bit count
4453 /// routine, and then combine the results.
4454 ///
4455 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4456 /// input    = [v0    v1    ] (vi: 32-bit elements)
4457 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4458 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4459 /// vrev: N0 = [k1 k0 k3 k2 ]
4460 ///            [k0 k1 k2 k3 ]
4461 ///       N1 =+[k1 k0 k3 k2 ]
4462 ///            [k0 k2 k1 k3 ]
4463 ///       N2 =+[k1 k3 k0 k2 ]
4464 ///            [k0    k2    k1    k3    ]
4465 /// Extended =+[k1    k3    k0    k2    ]
4466 ///            [k0    k2    ]
4467 /// Extracted=+[k1    k3    ]
4468 ///
4469 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4470   EVT VT = N->getValueType(0);
4471   SDLoc DL(N);
4472
4473   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4474
4475   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4476   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4477   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4478   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4479   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4480
4481   if (VT.is64BitVector()) {
4482     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4483     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4484                        DAG.getIntPtrConstant(0, DL));
4485   } else {
4486     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4487                                     DAG.getIntPtrConstant(0, DL));
4488     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4489   }
4490 }
4491
4492 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4493                           const ARMSubtarget *ST) {
4494   EVT VT = N->getValueType(0);
4495
4496   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4497   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4498           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4499          "Unexpected type for custom ctpop lowering");
4500
4501   if (VT.getVectorElementType() == MVT::i32)
4502     return lowerCTPOP32BitElements(N, DAG);
4503   else
4504     return lowerCTPOP16BitElements(N, DAG);
4505 }
4506
4507 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4508                           const ARMSubtarget *ST) {
4509   EVT VT = N->getValueType(0);
4510   SDLoc dl(N);
4511
4512   if (!VT.isVector())
4513     return SDValue();
4514
4515   // Lower vector shifts on NEON to use VSHL.
4516   assert(ST->hasNEON() && "unexpected vector shift");
4517
4518   // Left shifts translate directly to the vshiftu intrinsic.
4519   if (N->getOpcode() == ISD::SHL)
4520     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4521                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4522                                        MVT::i32),
4523                        N->getOperand(0), N->getOperand(1));
4524
4525   assert((N->getOpcode() == ISD::SRA ||
4526           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4527
4528   // NEON uses the same intrinsics for both left and right shifts.  For
4529   // right shifts, the shift amounts are negative, so negate the vector of
4530   // shift amounts.
4531   EVT ShiftVT = N->getOperand(1).getValueType();
4532   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4533                                      getZeroVector(ShiftVT, DAG, dl),
4534                                      N->getOperand(1));
4535   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4536                              Intrinsic::arm_neon_vshifts :
4537                              Intrinsic::arm_neon_vshiftu);
4538   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4539                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4540                      N->getOperand(0), NegatedCount);
4541 }
4542
4543 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4544                                 const ARMSubtarget *ST) {
4545   EVT VT = N->getValueType(0);
4546   SDLoc dl(N);
4547
4548   // We can get here for a node like i32 = ISD::SHL i32, i64
4549   if (VT != MVT::i64)
4550     return SDValue();
4551
4552   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4553          "Unknown shift to lower!");
4554
4555   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4556   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4557       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4558     return SDValue();
4559
4560   // If we are in thumb mode, we don't have RRX.
4561   if (ST->isThumb1Only()) return SDValue();
4562
4563   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4564   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4565                            DAG.getConstant(0, dl, MVT::i32));
4566   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4567                            DAG.getConstant(1, dl, MVT::i32));
4568
4569   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4570   // captures the result into a carry flag.
4571   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4572   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4573
4574   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4575   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4576
4577   // Merge the pieces into a single i64 value.
4578  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4579 }
4580
4581 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4582   SDValue TmpOp0, TmpOp1;
4583   bool Invert = false;
4584   bool Swap = false;
4585   unsigned Opc = 0;
4586
4587   SDValue Op0 = Op.getOperand(0);
4588   SDValue Op1 = Op.getOperand(1);
4589   SDValue CC = Op.getOperand(2);
4590   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4591   EVT VT = Op.getValueType();
4592   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4593   SDLoc dl(Op);
4594
4595   if (Op1.getValueType().isFloatingPoint()) {
4596     switch (SetCCOpcode) {
4597     default: llvm_unreachable("Illegal FP comparison");
4598     case ISD::SETUNE:
4599     case ISD::SETNE:  Invert = true; // Fallthrough
4600     case ISD::SETOEQ:
4601     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4602     case ISD::SETOLT:
4603     case ISD::SETLT: Swap = true; // Fallthrough
4604     case ISD::SETOGT:
4605     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4606     case ISD::SETOLE:
4607     case ISD::SETLE:  Swap = true; // Fallthrough
4608     case ISD::SETOGE:
4609     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4610     case ISD::SETUGE: Swap = true; // Fallthrough
4611     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4612     case ISD::SETUGT: Swap = true; // Fallthrough
4613     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4614     case ISD::SETUEQ: Invert = true; // Fallthrough
4615     case ISD::SETONE:
4616       // Expand this to (OLT | OGT).
4617       TmpOp0 = Op0;
4618       TmpOp1 = Op1;
4619       Opc = ISD::OR;
4620       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4621       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4622       break;
4623     case ISD::SETUO: Invert = true; // Fallthrough
4624     case ISD::SETO:
4625       // Expand this to (OLT | OGE).
4626       TmpOp0 = Op0;
4627       TmpOp1 = Op1;
4628       Opc = ISD::OR;
4629       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4630       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4631       break;
4632     }
4633   } else {
4634     // Integer comparisons.
4635     switch (SetCCOpcode) {
4636     default: llvm_unreachable("Illegal integer comparison");
4637     case ISD::SETNE:  Invert = true;
4638     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4639     case ISD::SETLT:  Swap = true;
4640     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4641     case ISD::SETLE:  Swap = true;
4642     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4643     case ISD::SETULT: Swap = true;
4644     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4645     case ISD::SETULE: Swap = true;
4646     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4647     }
4648
4649     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4650     if (Opc == ARMISD::VCEQ) {
4651
4652       SDValue AndOp;
4653       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4654         AndOp = Op0;
4655       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4656         AndOp = Op1;
4657
4658       // Ignore bitconvert.
4659       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4660         AndOp = AndOp.getOperand(0);
4661
4662       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4663         Opc = ARMISD::VTST;
4664         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4665         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4666         Invert = !Invert;
4667       }
4668     }
4669   }
4670
4671   if (Swap)
4672     std::swap(Op0, Op1);
4673
4674   // If one of the operands is a constant vector zero, attempt to fold the
4675   // comparison to a specialized compare-against-zero form.
4676   SDValue SingleOp;
4677   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4678     SingleOp = Op0;
4679   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4680     if (Opc == ARMISD::VCGE)
4681       Opc = ARMISD::VCLEZ;
4682     else if (Opc == ARMISD::VCGT)
4683       Opc = ARMISD::VCLTZ;
4684     SingleOp = Op1;
4685   }
4686
4687   SDValue Result;
4688   if (SingleOp.getNode()) {
4689     switch (Opc) {
4690     case ARMISD::VCEQ:
4691       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4692     case ARMISD::VCGE:
4693       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4694     case ARMISD::VCLEZ:
4695       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4696     case ARMISD::VCGT:
4697       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4698     case ARMISD::VCLTZ:
4699       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4700     default:
4701       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4702     }
4703   } else {
4704      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4705   }
4706
4707   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4708
4709   if (Invert)
4710     Result = DAG.getNOT(dl, Result, VT);
4711
4712   return Result;
4713 }
4714
4715 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4716 /// valid vector constant for a NEON instruction with a "modified immediate"
4717 /// operand (e.g., VMOV).  If so, return the encoded value.
4718 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4719                                  unsigned SplatBitSize, SelectionDAG &DAG,
4720                                  SDLoc dl, EVT &VT, bool is128Bits,
4721                                  NEONModImmType type) {
4722   unsigned OpCmode, Imm;
4723
4724   // SplatBitSize is set to the smallest size that splats the vector, so a
4725   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4726   // immediate instructions others than VMOV do not support the 8-bit encoding
4727   // of a zero vector, and the default encoding of zero is supposed to be the
4728   // 32-bit version.
4729   if (SplatBits == 0)
4730     SplatBitSize = 32;
4731
4732   switch (SplatBitSize) {
4733   case 8:
4734     if (type != VMOVModImm)
4735       return SDValue();
4736     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4737     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4738     OpCmode = 0xe;
4739     Imm = SplatBits;
4740     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4741     break;
4742
4743   case 16:
4744     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4745     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4746     if ((SplatBits & ~0xff) == 0) {
4747       // Value = 0x00nn: Op=x, Cmode=100x.
4748       OpCmode = 0x8;
4749       Imm = SplatBits;
4750       break;
4751     }
4752     if ((SplatBits & ~0xff00) == 0) {
4753       // Value = 0xnn00: Op=x, Cmode=101x.
4754       OpCmode = 0xa;
4755       Imm = SplatBits >> 8;
4756       break;
4757     }
4758     return SDValue();
4759
4760   case 32:
4761     // NEON's 32-bit VMOV supports splat values where:
4762     // * only one byte is nonzero, or
4763     // * the least significant byte is 0xff and the second byte is nonzero, or
4764     // * the least significant 2 bytes are 0xff and the third is nonzero.
4765     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4766     if ((SplatBits & ~0xff) == 0) {
4767       // Value = 0x000000nn: Op=x, Cmode=000x.
4768       OpCmode = 0;
4769       Imm = SplatBits;
4770       break;
4771     }
4772     if ((SplatBits & ~0xff00) == 0) {
4773       // Value = 0x0000nn00: Op=x, Cmode=001x.
4774       OpCmode = 0x2;
4775       Imm = SplatBits >> 8;
4776       break;
4777     }
4778     if ((SplatBits & ~0xff0000) == 0) {
4779       // Value = 0x00nn0000: Op=x, Cmode=010x.
4780       OpCmode = 0x4;
4781       Imm = SplatBits >> 16;
4782       break;
4783     }
4784     if ((SplatBits & ~0xff000000) == 0) {
4785       // Value = 0xnn000000: Op=x, Cmode=011x.
4786       OpCmode = 0x6;
4787       Imm = SplatBits >> 24;
4788       break;
4789     }
4790
4791     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4792     if (type == OtherModImm) return SDValue();
4793
4794     if ((SplatBits & ~0xffff) == 0 &&
4795         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4796       // Value = 0x0000nnff: Op=x, Cmode=1100.
4797       OpCmode = 0xc;
4798       Imm = SplatBits >> 8;
4799       break;
4800     }
4801
4802     if ((SplatBits & ~0xffffff) == 0 &&
4803         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4804       // Value = 0x00nnffff: Op=x, Cmode=1101.
4805       OpCmode = 0xd;
4806       Imm = SplatBits >> 16;
4807       break;
4808     }
4809
4810     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4811     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4812     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4813     // and fall through here to test for a valid 64-bit splat.  But, then the
4814     // caller would also need to check and handle the change in size.
4815     return SDValue();
4816
4817   case 64: {
4818     if (type != VMOVModImm)
4819       return SDValue();
4820     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4821     uint64_t BitMask = 0xff;
4822     uint64_t Val = 0;
4823     unsigned ImmMask = 1;
4824     Imm = 0;
4825     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4826       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4827         Val |= BitMask;
4828         Imm |= ImmMask;
4829       } else if ((SplatBits & BitMask) != 0) {
4830         return SDValue();
4831       }
4832       BitMask <<= 8;
4833       ImmMask <<= 1;
4834     }
4835
4836     if (DAG.getDataLayout().isBigEndian())
4837       // swap higher and lower 32 bit word
4838       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4839
4840     // Op=1, Cmode=1110.
4841     OpCmode = 0x1e;
4842     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4843     break;
4844   }
4845
4846   default:
4847     llvm_unreachable("unexpected size for isNEONModifiedImm");
4848   }
4849
4850   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4851   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4852 }
4853
4854 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4855                                            const ARMSubtarget *ST) const {
4856   if (!ST->hasVFP3())
4857     return SDValue();
4858
4859   bool IsDouble = Op.getValueType() == MVT::f64;
4860   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4861
4862   // Use the default (constant pool) lowering for double constants when we have
4863   // an SP-only FPU
4864   if (IsDouble && Subtarget->isFPOnlySP())
4865     return SDValue();
4866
4867   // Try splatting with a VMOV.f32...
4868   APFloat FPVal = CFP->getValueAPF();
4869   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4870
4871   if (ImmVal != -1) {
4872     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4873       // We have code in place to select a valid ConstantFP already, no need to
4874       // do any mangling.
4875       return Op;
4876     }
4877
4878     // It's a float and we are trying to use NEON operations where
4879     // possible. Lower it to a splat followed by an extract.
4880     SDLoc DL(Op);
4881     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4882     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4883                                       NewVal);
4884     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4885                        DAG.getConstant(0, DL, MVT::i32));
4886   }
4887
4888   // The rest of our options are NEON only, make sure that's allowed before
4889   // proceeding..
4890   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4891     return SDValue();
4892
4893   EVT VMovVT;
4894   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4895
4896   // It wouldn't really be worth bothering for doubles except for one very
4897   // important value, which does happen to match: 0.0. So make sure we don't do
4898   // anything stupid.
4899   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4900     return SDValue();
4901
4902   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4903   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4904                                      VMovVT, false, VMOVModImm);
4905   if (NewVal != SDValue()) {
4906     SDLoc DL(Op);
4907     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4908                                       NewVal);
4909     if (IsDouble)
4910       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4911
4912     // It's a float: cast and extract a vector element.
4913     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4914                                        VecConstant);
4915     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4916                        DAG.getConstant(0, DL, MVT::i32));
4917   }
4918
4919   // Finally, try a VMVN.i32
4920   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4921                              false, VMVNModImm);
4922   if (NewVal != SDValue()) {
4923     SDLoc DL(Op);
4924     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4925
4926     if (IsDouble)
4927       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4928
4929     // It's a float: cast and extract a vector element.
4930     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4931                                        VecConstant);
4932     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4933                        DAG.getConstant(0, DL, MVT::i32));
4934   }
4935
4936   return SDValue();
4937 }
4938
4939 // check if an VEXT instruction can handle the shuffle mask when the
4940 // vector sources of the shuffle are the same.
4941 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4942   unsigned NumElts = VT.getVectorNumElements();
4943
4944   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4945   if (M[0] < 0)
4946     return false;
4947
4948   Imm = M[0];
4949
4950   // If this is a VEXT shuffle, the immediate value is the index of the first
4951   // element.  The other shuffle indices must be the successive elements after
4952   // the first one.
4953   unsigned ExpectedElt = Imm;
4954   for (unsigned i = 1; i < NumElts; ++i) {
4955     // Increment the expected index.  If it wraps around, just follow it
4956     // back to index zero and keep going.
4957     ++ExpectedElt;
4958     if (ExpectedElt == NumElts)
4959       ExpectedElt = 0;
4960
4961     if (M[i] < 0) continue; // ignore UNDEF indices
4962     if (ExpectedElt != static_cast<unsigned>(M[i]))
4963       return false;
4964   }
4965
4966   return true;
4967 }
4968
4969
4970 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4971                        bool &ReverseVEXT, unsigned &Imm) {
4972   unsigned NumElts = VT.getVectorNumElements();
4973   ReverseVEXT = false;
4974
4975   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4976   if (M[0] < 0)
4977     return false;
4978
4979   Imm = M[0];
4980
4981   // If this is a VEXT shuffle, the immediate value is the index of the first
4982   // element.  The other shuffle indices must be the successive elements after
4983   // the first one.
4984   unsigned ExpectedElt = Imm;
4985   for (unsigned i = 1; i < NumElts; ++i) {
4986     // Increment the expected index.  If it wraps around, it may still be
4987     // a VEXT but the source vectors must be swapped.
4988     ExpectedElt += 1;
4989     if (ExpectedElt == NumElts * 2) {
4990       ExpectedElt = 0;
4991       ReverseVEXT = true;
4992     }
4993
4994     if (M[i] < 0) continue; // ignore UNDEF indices
4995     if (ExpectedElt != static_cast<unsigned>(M[i]))
4996       return false;
4997   }
4998
4999   // Adjust the index value if the source operands will be swapped.
5000   if (ReverseVEXT)
5001     Imm -= NumElts;
5002
5003   return true;
5004 }
5005
5006 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5007 /// instruction with the specified blocksize.  (The order of the elements
5008 /// within each block of the vector is reversed.)
5009 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5010   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5011          "Only possible block sizes for VREV are: 16, 32, 64");
5012
5013   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5014   if (EltSz == 64)
5015     return false;
5016
5017   unsigned NumElts = VT.getVectorNumElements();
5018   unsigned BlockElts = M[0] + 1;
5019   // If the first shuffle index is UNDEF, be optimistic.
5020   if (M[0] < 0)
5021     BlockElts = BlockSize / EltSz;
5022
5023   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5024     return false;
5025
5026   for (unsigned i = 0; i < NumElts; ++i) {
5027     if (M[i] < 0) continue; // ignore UNDEF indices
5028     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5029       return false;
5030   }
5031
5032   return true;
5033 }
5034
5035 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5036   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5037   // range, then 0 is placed into the resulting vector. So pretty much any mask
5038   // of 8 elements can work here.
5039   return VT == MVT::v8i8 && M.size() == 8;
5040 }
5041
5042 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5043 // checking that pairs of elements in the shuffle mask represent the same index
5044 // in each vector, incrementing the expected index by 2 at each step.
5045 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5046 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5047 //  v2={e,f,g,h}
5048 // WhichResult gives the offset for each element in the mask based on which
5049 // of the two results it belongs to.
5050 //
5051 // The transpose can be represented either as:
5052 // result1 = shufflevector v1, v2, result1_shuffle_mask
5053 // result2 = shufflevector v1, v2, result2_shuffle_mask
5054 // where v1/v2 and the shuffle masks have the same number of elements
5055 // (here WhichResult (see below) indicates which result is being checked)
5056 //
5057 // or as:
5058 // results = shufflevector v1, v2, shuffle_mask
5059 // where both results are returned in one vector and the shuffle mask has twice
5060 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5061 // want to check the low half and high half of the shuffle mask as if it were
5062 // the other case
5063 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5064   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5065   if (EltSz == 64)
5066     return false;
5067
5068   unsigned NumElts = VT.getVectorNumElements();
5069   if (M.size() != NumElts && M.size() != NumElts*2)
5070     return false;
5071
5072   // If the mask is twice as long as the result then we need to check the upper
5073   // and lower parts of the mask
5074   for (unsigned i = 0; i < M.size(); i += NumElts) {
5075     WhichResult = M[i] == 0 ? 0 : 1;
5076     for (unsigned j = 0; j < NumElts; j += 2) {
5077       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5078           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5079         return false;
5080     }
5081   }
5082
5083   if (M.size() == NumElts*2)
5084     WhichResult = 0;
5085
5086   return true;
5087 }
5088
5089 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5090 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5091 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5092 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5093   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5094   if (EltSz == 64)
5095     return false;
5096
5097   unsigned NumElts = VT.getVectorNumElements();
5098   if (M.size() != NumElts && M.size() != NumElts*2)
5099     return false;
5100
5101   for (unsigned i = 0; i < M.size(); i += NumElts) {
5102     WhichResult = M[i] == 0 ? 0 : 1;
5103     for (unsigned j = 0; j < NumElts; j += 2) {
5104       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5105           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5106         return false;
5107     }
5108   }
5109
5110   if (M.size() == NumElts*2)
5111     WhichResult = 0;
5112
5113   return true;
5114 }
5115
5116 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5117 // that the mask elements are either all even and in steps of size 2 or all odd
5118 // and in steps of size 2.
5119 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5120 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5121 //  v2={e,f,g,h}
5122 // Requires similar checks to that of isVTRNMask with
5123 // respect the how results are returned.
5124 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5125   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5126   if (EltSz == 64)
5127     return false;
5128
5129   unsigned NumElts = VT.getVectorNumElements();
5130   if (M.size() != NumElts && M.size() != NumElts*2)
5131     return false;
5132
5133   for (unsigned i = 0; i < M.size(); i += NumElts) {
5134     WhichResult = M[i] == 0 ? 0 : 1;
5135     for (unsigned j = 0; j < NumElts; ++j) {
5136       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5137         return false;
5138     }
5139   }
5140
5141   if (M.size() == NumElts*2)
5142     WhichResult = 0;
5143
5144   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5145   if (VT.is64BitVector() && EltSz == 32)
5146     return false;
5147
5148   return true;
5149 }
5150
5151 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5152 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5153 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5154 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5155   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5156   if (EltSz == 64)
5157     return false;
5158
5159   unsigned NumElts = VT.getVectorNumElements();
5160   if (M.size() != NumElts && M.size() != NumElts*2)
5161     return false;
5162
5163   unsigned Half = NumElts / 2;
5164   for (unsigned i = 0; i < M.size(); i += NumElts) {
5165     WhichResult = M[i] == 0 ? 0 : 1;
5166     for (unsigned j = 0; j < NumElts; j += Half) {
5167       unsigned Idx = WhichResult;
5168       for (unsigned k = 0; k < Half; ++k) {
5169         int MIdx = M[i + j + k];
5170         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5171           return false;
5172         Idx += 2;
5173       }
5174     }
5175   }
5176
5177   if (M.size() == NumElts*2)
5178     WhichResult = 0;
5179
5180   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5181   if (VT.is64BitVector() && EltSz == 32)
5182     return false;
5183
5184   return true;
5185 }
5186
5187 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5188 // that pairs of elements of the shufflemask represent the same index in each
5189 // vector incrementing sequentially through the vectors.
5190 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5191 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5192 //  v2={e,f,g,h}
5193 // Requires similar checks to that of isVTRNMask with respect the how results
5194 // are returned.
5195 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5196   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5197   if (EltSz == 64)
5198     return false;
5199
5200   unsigned NumElts = VT.getVectorNumElements();
5201   if (M.size() != NumElts && M.size() != NumElts*2)
5202     return false;
5203
5204   for (unsigned i = 0; i < M.size(); i += NumElts) {
5205     WhichResult = M[i] == 0 ? 0 : 1;
5206     unsigned Idx = WhichResult * NumElts / 2;
5207     for (unsigned j = 0; j < NumElts; j += 2) {
5208       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5209           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5210         return false;
5211       Idx += 1;
5212     }
5213   }
5214
5215   if (M.size() == NumElts*2)
5216     WhichResult = 0;
5217
5218   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5219   if (VT.is64BitVector() && EltSz == 32)
5220     return false;
5221
5222   return true;
5223 }
5224
5225 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5226 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5227 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5228 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5229   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5230   if (EltSz == 64)
5231     return false;
5232
5233   unsigned NumElts = VT.getVectorNumElements();
5234   if (M.size() != NumElts && M.size() != NumElts*2)
5235     return false;
5236
5237   for (unsigned i = 0; i < M.size(); i += NumElts) {
5238     WhichResult = M[i] == 0 ? 0 : 1;
5239     unsigned Idx = WhichResult * NumElts / 2;
5240     for (unsigned j = 0; j < NumElts; j += 2) {
5241       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5242           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5243         return false;
5244       Idx += 1;
5245     }
5246   }
5247
5248   if (M.size() == NumElts*2)
5249     WhichResult = 0;
5250
5251   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5252   if (VT.is64BitVector() && EltSz == 32)
5253     return false;
5254
5255   return true;
5256 }
5257
5258 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5259 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5260 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5261                                            unsigned &WhichResult,
5262                                            bool &isV_UNDEF) {
5263   isV_UNDEF = false;
5264   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5265     return ARMISD::VTRN;
5266   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5267     return ARMISD::VUZP;
5268   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5269     return ARMISD::VZIP;
5270
5271   isV_UNDEF = true;
5272   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5273     return ARMISD::VTRN;
5274   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5275     return ARMISD::VUZP;
5276   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5277     return ARMISD::VZIP;
5278
5279   return 0;
5280 }
5281
5282 /// \return true if this is a reverse operation on an vector.
5283 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5284   unsigned NumElts = VT.getVectorNumElements();
5285   // Make sure the mask has the right size.
5286   if (NumElts != M.size())
5287       return false;
5288
5289   // Look for <15, ..., 3, -1, 1, 0>.
5290   for (unsigned i = 0; i != NumElts; ++i)
5291     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5292       return false;
5293
5294   return true;
5295 }
5296
5297 // If N is an integer constant that can be moved into a register in one
5298 // instruction, return an SDValue of such a constant (will become a MOV
5299 // instruction).  Otherwise return null.
5300 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5301                                      const ARMSubtarget *ST, SDLoc dl) {
5302   uint64_t Val;
5303   if (!isa<ConstantSDNode>(N))
5304     return SDValue();
5305   Val = cast<ConstantSDNode>(N)->getZExtValue();
5306
5307   if (ST->isThumb1Only()) {
5308     if (Val <= 255 || ~Val <= 255)
5309       return DAG.getConstant(Val, dl, MVT::i32);
5310   } else {
5311     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5312       return DAG.getConstant(Val, dl, MVT::i32);
5313   }
5314   return SDValue();
5315 }
5316
5317 // If this is a case we can't handle, return null and let the default
5318 // expansion code take care of it.
5319 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5320                                              const ARMSubtarget *ST) const {
5321   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5322   SDLoc dl(Op);
5323   EVT VT = Op.getValueType();
5324
5325   APInt SplatBits, SplatUndef;
5326   unsigned SplatBitSize;
5327   bool HasAnyUndefs;
5328   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5329     if (SplatBitSize <= 64) {
5330       // Check if an immediate VMOV works.
5331       EVT VmovVT;
5332       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5333                                       SplatUndef.getZExtValue(), SplatBitSize,
5334                                       DAG, dl, VmovVT, VT.is128BitVector(),
5335                                       VMOVModImm);
5336       if (Val.getNode()) {
5337         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5338         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5339       }
5340
5341       // Try an immediate VMVN.
5342       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5343       Val = isNEONModifiedImm(NegatedImm,
5344                                       SplatUndef.getZExtValue(), SplatBitSize,
5345                                       DAG, dl, VmovVT, VT.is128BitVector(),
5346                                       VMVNModImm);
5347       if (Val.getNode()) {
5348         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5349         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5350       }
5351
5352       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5353       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5354         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5355         if (ImmVal != -1) {
5356           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5357           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5358         }
5359       }
5360     }
5361   }
5362
5363   // Scan through the operands to see if only one value is used.
5364   //
5365   // As an optimisation, even if more than one value is used it may be more
5366   // profitable to splat with one value then change some lanes.
5367   //
5368   // Heuristically we decide to do this if the vector has a "dominant" value,
5369   // defined as splatted to more than half of the lanes.
5370   unsigned NumElts = VT.getVectorNumElements();
5371   bool isOnlyLowElement = true;
5372   bool usesOnlyOneValue = true;
5373   bool hasDominantValue = false;
5374   bool isConstant = true;
5375
5376   // Map of the number of times a particular SDValue appears in the
5377   // element list.
5378   DenseMap<SDValue, unsigned> ValueCounts;
5379   SDValue Value;
5380   for (unsigned i = 0; i < NumElts; ++i) {
5381     SDValue V = Op.getOperand(i);
5382     if (V.getOpcode() == ISD::UNDEF)
5383       continue;
5384     if (i > 0)
5385       isOnlyLowElement = false;
5386     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5387       isConstant = false;
5388
5389     ValueCounts.insert(std::make_pair(V, 0));
5390     unsigned &Count = ValueCounts[V];
5391
5392     // Is this value dominant? (takes up more than half of the lanes)
5393     if (++Count > (NumElts / 2)) {
5394       hasDominantValue = true;
5395       Value = V;
5396     }
5397   }
5398   if (ValueCounts.size() != 1)
5399     usesOnlyOneValue = false;
5400   if (!Value.getNode() && ValueCounts.size() > 0)
5401     Value = ValueCounts.begin()->first;
5402
5403   if (ValueCounts.size() == 0)
5404     return DAG.getUNDEF(VT);
5405
5406   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5407   // Keep going if we are hitting this case.
5408   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5409     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5410
5411   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5412
5413   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5414   // i32 and try again.
5415   if (hasDominantValue && EltSize <= 32) {
5416     if (!isConstant) {
5417       SDValue N;
5418
5419       // If we are VDUPing a value that comes directly from a vector, that will
5420       // cause an unnecessary move to and from a GPR, where instead we could
5421       // just use VDUPLANE. We can only do this if the lane being extracted
5422       // is at a constant index, as the VDUP from lane instructions only have
5423       // constant-index forms.
5424       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5425           isa<ConstantSDNode>(Value->getOperand(1))) {
5426         // We need to create a new undef vector to use for the VDUPLANE if the
5427         // size of the vector from which we get the value is different than the
5428         // size of the vector that we need to create. We will insert the element
5429         // such that the register coalescer will remove unnecessary copies.
5430         if (VT != Value->getOperand(0).getValueType()) {
5431           ConstantSDNode *constIndex;
5432           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5433           assert(constIndex && "The index is not a constant!");
5434           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5435                              VT.getVectorNumElements();
5436           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5437                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5438                         Value, DAG.getConstant(index, dl, MVT::i32)),
5439                            DAG.getConstant(index, dl, MVT::i32));
5440         } else
5441           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5442                         Value->getOperand(0), Value->getOperand(1));
5443       } else
5444         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5445
5446       if (!usesOnlyOneValue) {
5447         // The dominant value was splatted as 'N', but we now have to insert
5448         // all differing elements.
5449         for (unsigned I = 0; I < NumElts; ++I) {
5450           if (Op.getOperand(I) == Value)
5451             continue;
5452           SmallVector<SDValue, 3> Ops;
5453           Ops.push_back(N);
5454           Ops.push_back(Op.getOperand(I));
5455           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5456           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5457         }
5458       }
5459       return N;
5460     }
5461     if (VT.getVectorElementType().isFloatingPoint()) {
5462       SmallVector<SDValue, 8> Ops;
5463       for (unsigned i = 0; i < NumElts; ++i)
5464         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5465                                   Op.getOperand(i)));
5466       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5467       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5468       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5469       if (Val.getNode())
5470         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5471     }
5472     if (usesOnlyOneValue) {
5473       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5474       if (isConstant && Val.getNode())
5475         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5476     }
5477   }
5478
5479   // If all elements are constants and the case above didn't get hit, fall back
5480   // to the default expansion, which will generate a load from the constant
5481   // pool.
5482   if (isConstant)
5483     return SDValue();
5484
5485   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5486   if (NumElts >= 4) {
5487     SDValue shuffle = ReconstructShuffle(Op, DAG);
5488     if (shuffle != SDValue())
5489       return shuffle;
5490   }
5491
5492   // Vectors with 32- or 64-bit elements can be built by directly assigning
5493   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5494   // will be legalized.
5495   if (EltSize >= 32) {
5496     // Do the expansion with floating-point types, since that is what the VFP
5497     // registers are defined to use, and since i64 is not legal.
5498     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5499     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5500     SmallVector<SDValue, 8> Ops;
5501     for (unsigned i = 0; i < NumElts; ++i)
5502       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5503     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5504     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5505   }
5506
5507   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5508   // know the default expansion would otherwise fall back on something even
5509   // worse. For a vector with one or two non-undef values, that's
5510   // scalar_to_vector for the elements followed by a shuffle (provided the
5511   // shuffle is valid for the target) and materialization element by element
5512   // on the stack followed by a load for everything else.
5513   if (!isConstant && !usesOnlyOneValue) {
5514     SDValue Vec = DAG.getUNDEF(VT);
5515     for (unsigned i = 0 ; i < NumElts; ++i) {
5516       SDValue V = Op.getOperand(i);
5517       if (V.getOpcode() == ISD::UNDEF)
5518         continue;
5519       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5520       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5521     }
5522     return Vec;
5523   }
5524
5525   return SDValue();
5526 }
5527
5528 // Gather data to see if the operation can be modelled as a
5529 // shuffle in combination with VEXTs.
5530 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5531                                               SelectionDAG &DAG) const {
5532   SDLoc dl(Op);
5533   EVT VT = Op.getValueType();
5534   unsigned NumElts = VT.getVectorNumElements();
5535
5536   SmallVector<SDValue, 2> SourceVecs;
5537   SmallVector<unsigned, 2> MinElts;
5538   SmallVector<unsigned, 2> MaxElts;
5539
5540   for (unsigned i = 0; i < NumElts; ++i) {
5541     SDValue V = Op.getOperand(i);
5542     if (V.getOpcode() == ISD::UNDEF)
5543       continue;
5544     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5545       // A shuffle can only come from building a vector from various
5546       // elements of other vectors.
5547       return SDValue();
5548     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5549                VT.getVectorElementType()) {
5550       // This code doesn't know how to handle shuffles where the vector
5551       // element types do not match (this happens because type legalization
5552       // promotes the return type of EXTRACT_VECTOR_ELT).
5553       // FIXME: It might be appropriate to extend this code to handle
5554       // mismatched types.
5555       return SDValue();
5556     }
5557
5558     // Record this extraction against the appropriate vector if possible...
5559     SDValue SourceVec = V.getOperand(0);
5560     // If the element number isn't a constant, we can't effectively
5561     // analyze what's going on.
5562     if (!isa<ConstantSDNode>(V.getOperand(1)))
5563       return SDValue();
5564     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5565     bool FoundSource = false;
5566     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5567       if (SourceVecs[j] == SourceVec) {
5568         if (MinElts[j] > EltNo)
5569           MinElts[j] = EltNo;
5570         if (MaxElts[j] < EltNo)
5571           MaxElts[j] = EltNo;
5572         FoundSource = true;
5573         break;
5574       }
5575     }
5576
5577     // Or record a new source if not...
5578     if (!FoundSource) {
5579       SourceVecs.push_back(SourceVec);
5580       MinElts.push_back(EltNo);
5581       MaxElts.push_back(EltNo);
5582     }
5583   }
5584
5585   // Currently only do something sane when at most two source vectors
5586   // involved.
5587   if (SourceVecs.size() > 2)
5588     return SDValue();
5589
5590   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5591   int VEXTOffsets[2] = {0, 0};
5592
5593   // This loop extracts the usage patterns of the source vectors
5594   // and prepares appropriate SDValues for a shuffle if possible.
5595   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5596     if (SourceVecs[i].getValueType() == VT) {
5597       // No VEXT necessary
5598       ShuffleSrcs[i] = SourceVecs[i];
5599       VEXTOffsets[i] = 0;
5600       continue;
5601     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5602       // It probably isn't worth padding out a smaller vector just to
5603       // break it down again in a shuffle.
5604       return SDValue();
5605     }
5606
5607     // Since only 64-bit and 128-bit vectors are legal on ARM and
5608     // we've eliminated the other cases...
5609     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5610            "unexpected vector sizes in ReconstructShuffle");
5611
5612     if (MaxElts[i] - MinElts[i] >= NumElts) {
5613       // Span too large for a VEXT to cope
5614       return SDValue();
5615     }
5616
5617     if (MinElts[i] >= NumElts) {
5618       // The extraction can just take the second half
5619       VEXTOffsets[i] = NumElts;
5620       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5621                                    SourceVecs[i],
5622                                    DAG.getIntPtrConstant(NumElts, dl));
5623     } else if (MaxElts[i] < NumElts) {
5624       // The extraction can just take the first half
5625       VEXTOffsets[i] = 0;
5626       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5627                                    SourceVecs[i],
5628                                    DAG.getIntPtrConstant(0, dl));
5629     } else {
5630       // An actual VEXT is needed
5631       VEXTOffsets[i] = MinElts[i];
5632       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5633                                      SourceVecs[i],
5634                                      DAG.getIntPtrConstant(0, dl));
5635       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5636                                      SourceVecs[i],
5637                                      DAG.getIntPtrConstant(NumElts, dl));
5638       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5639                                    DAG.getConstant(VEXTOffsets[i], dl,
5640                                                    MVT::i32));
5641     }
5642   }
5643
5644   SmallVector<int, 8> Mask;
5645
5646   for (unsigned i = 0; i < NumElts; ++i) {
5647     SDValue Entry = Op.getOperand(i);
5648     if (Entry.getOpcode() == ISD::UNDEF) {
5649       Mask.push_back(-1);
5650       continue;
5651     }
5652
5653     SDValue ExtractVec = Entry.getOperand(0);
5654     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5655                                           .getOperand(1))->getSExtValue();
5656     if (ExtractVec == SourceVecs[0]) {
5657       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5658     } else {
5659       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5660     }
5661   }
5662
5663   // Final check before we try to produce nonsense...
5664   if (isShuffleMaskLegal(Mask, VT))
5665     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5666                                 &Mask[0]);
5667
5668   return SDValue();
5669 }
5670
5671 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5672 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5673 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5674 /// are assumed to be legal.
5675 bool
5676 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5677                                       EVT VT) const {
5678   if (VT.getVectorNumElements() == 4 &&
5679       (VT.is128BitVector() || VT.is64BitVector())) {
5680     unsigned PFIndexes[4];
5681     for (unsigned i = 0; i != 4; ++i) {
5682       if (M[i] < 0)
5683         PFIndexes[i] = 8;
5684       else
5685         PFIndexes[i] = M[i];
5686     }
5687
5688     // Compute the index in the perfect shuffle table.
5689     unsigned PFTableIndex =
5690       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5691     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5692     unsigned Cost = (PFEntry >> 30);
5693
5694     if (Cost <= 4)
5695       return true;
5696   }
5697
5698   bool ReverseVEXT, isV_UNDEF;
5699   unsigned Imm, WhichResult;
5700
5701   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5702   return (EltSize >= 32 ||
5703           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5704           isVREVMask(M, VT, 64) ||
5705           isVREVMask(M, VT, 32) ||
5706           isVREVMask(M, VT, 16) ||
5707           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5708           isVTBLMask(M, VT) ||
5709           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5710           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5711 }
5712
5713 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5714 /// the specified operations to build the shuffle.
5715 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5716                                       SDValue RHS, SelectionDAG &DAG,
5717                                       SDLoc dl) {
5718   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5719   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5720   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5721
5722   enum {
5723     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5724     OP_VREV,
5725     OP_VDUP0,
5726     OP_VDUP1,
5727     OP_VDUP2,
5728     OP_VDUP3,
5729     OP_VEXT1,
5730     OP_VEXT2,
5731     OP_VEXT3,
5732     OP_VUZPL, // VUZP, left result
5733     OP_VUZPR, // VUZP, right result
5734     OP_VZIPL, // VZIP, left result
5735     OP_VZIPR, // VZIP, right result
5736     OP_VTRNL, // VTRN, left result
5737     OP_VTRNR  // VTRN, right result
5738   };
5739
5740   if (OpNum == OP_COPY) {
5741     if (LHSID == (1*9+2)*9+3) return LHS;
5742     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5743     return RHS;
5744   }
5745
5746   SDValue OpLHS, OpRHS;
5747   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5748   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5749   EVT VT = OpLHS.getValueType();
5750
5751   switch (OpNum) {
5752   default: llvm_unreachable("Unknown shuffle opcode!");
5753   case OP_VREV:
5754     // VREV divides the vector in half and swaps within the half.
5755     if (VT.getVectorElementType() == MVT::i32 ||
5756         VT.getVectorElementType() == MVT::f32)
5757       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5758     // vrev <4 x i16> -> VREV32
5759     if (VT.getVectorElementType() == MVT::i16)
5760       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5761     // vrev <4 x i8> -> VREV16
5762     assert(VT.getVectorElementType() == MVT::i8);
5763     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5764   case OP_VDUP0:
5765   case OP_VDUP1:
5766   case OP_VDUP2:
5767   case OP_VDUP3:
5768     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5769                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5770   case OP_VEXT1:
5771   case OP_VEXT2:
5772   case OP_VEXT3:
5773     return DAG.getNode(ARMISD::VEXT, dl, VT,
5774                        OpLHS, OpRHS,
5775                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5776   case OP_VUZPL:
5777   case OP_VUZPR:
5778     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5779                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5780   case OP_VZIPL:
5781   case OP_VZIPR:
5782     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5783                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5784   case OP_VTRNL:
5785   case OP_VTRNR:
5786     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5787                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5788   }
5789 }
5790
5791 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5792                                        ArrayRef<int> ShuffleMask,
5793                                        SelectionDAG &DAG) {
5794   // Check to see if we can use the VTBL instruction.
5795   SDValue V1 = Op.getOperand(0);
5796   SDValue V2 = Op.getOperand(1);
5797   SDLoc DL(Op);
5798
5799   SmallVector<SDValue, 8> VTBLMask;
5800   for (ArrayRef<int>::iterator
5801          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5802     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5803
5804   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5805     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5806                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5807
5808   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5809                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5810 }
5811
5812 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5813                                                       SelectionDAG &DAG) {
5814   SDLoc DL(Op);
5815   SDValue OpLHS = Op.getOperand(0);
5816   EVT VT = OpLHS.getValueType();
5817
5818   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5819          "Expect an v8i16/v16i8 type");
5820   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5821   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5822   // extract the first 8 bytes into the top double word and the last 8 bytes
5823   // into the bottom double word. The v8i16 case is similar.
5824   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5825   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5826                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5827 }
5828
5829 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5830   SDValue V1 = Op.getOperand(0);
5831   SDValue V2 = Op.getOperand(1);
5832   SDLoc dl(Op);
5833   EVT VT = Op.getValueType();
5834   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5835
5836   // Convert shuffles that are directly supported on NEON to target-specific
5837   // DAG nodes, instead of keeping them as shuffles and matching them again
5838   // during code selection.  This is more efficient and avoids the possibility
5839   // of inconsistencies between legalization and selection.
5840   // FIXME: floating-point vectors should be canonicalized to integer vectors
5841   // of the same time so that they get CSEd properly.
5842   ArrayRef<int> ShuffleMask = SVN->getMask();
5843
5844   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5845   if (EltSize <= 32) {
5846     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5847       int Lane = SVN->getSplatIndex();
5848       // If this is undef splat, generate it via "just" vdup, if possible.
5849       if (Lane == -1) Lane = 0;
5850
5851       // Test if V1 is a SCALAR_TO_VECTOR.
5852       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5853         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5854       }
5855       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5856       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5857       // reaches it).
5858       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5859           !isa<ConstantSDNode>(V1.getOperand(0))) {
5860         bool IsScalarToVector = true;
5861         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5862           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5863             IsScalarToVector = false;
5864             break;
5865           }
5866         if (IsScalarToVector)
5867           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5868       }
5869       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5870                          DAG.getConstant(Lane, dl, MVT::i32));
5871     }
5872
5873     bool ReverseVEXT;
5874     unsigned Imm;
5875     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5876       if (ReverseVEXT)
5877         std::swap(V1, V2);
5878       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5879                          DAG.getConstant(Imm, dl, MVT::i32));
5880     }
5881
5882     if (isVREVMask(ShuffleMask, VT, 64))
5883       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5884     if (isVREVMask(ShuffleMask, VT, 32))
5885       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5886     if (isVREVMask(ShuffleMask, VT, 16))
5887       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5888
5889     if (V2->getOpcode() == ISD::UNDEF &&
5890         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5891       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5892                          DAG.getConstant(Imm, dl, MVT::i32));
5893     }
5894
5895     // Check for Neon shuffles that modify both input vectors in place.
5896     // If both results are used, i.e., if there are two shuffles with the same
5897     // source operands and with masks corresponding to both results of one of
5898     // these operations, DAG memoization will ensure that a single node is
5899     // used for both shuffles.
5900     unsigned WhichResult;
5901     bool isV_UNDEF;
5902     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5903             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5904       if (isV_UNDEF)
5905         V2 = V1;
5906       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5907           .getValue(WhichResult);
5908     }
5909
5910     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5911     // shuffles that produce a result larger than their operands with:
5912     //   shuffle(concat(v1, undef), concat(v2, undef))
5913     // ->
5914     //   shuffle(concat(v1, v2), undef)
5915     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5916     //
5917     // This is useful in the general case, but there are special cases where
5918     // native shuffles produce larger results: the two-result ops.
5919     //
5920     // Look through the concat when lowering them:
5921     //   shuffle(concat(v1, v2), undef)
5922     // ->
5923     //   concat(VZIP(v1, v2):0, :1)
5924     //
5925     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5926         V2->getOpcode() == ISD::UNDEF) {
5927       SDValue SubV1 = V1->getOperand(0);
5928       SDValue SubV2 = V1->getOperand(1);
5929       EVT SubVT = SubV1.getValueType();
5930
5931       // We expect these to have been canonicalized to -1.
5932       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5933         return i < (int)VT.getVectorNumElements();
5934       }) && "Unexpected shuffle index into UNDEF operand!");
5935
5936       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5937               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5938         if (isV_UNDEF)
5939           SubV2 = SubV1;
5940         assert((WhichResult == 0) &&
5941                "In-place shuffle of concat can only have one result!");
5942         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5943                                   SubV1, SubV2);
5944         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5945                            Res.getValue(1));
5946       }
5947     }
5948   }
5949
5950   // If the shuffle is not directly supported and it has 4 elements, use
5951   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5952   unsigned NumElts = VT.getVectorNumElements();
5953   if (NumElts == 4) {
5954     unsigned PFIndexes[4];
5955     for (unsigned i = 0; i != 4; ++i) {
5956       if (ShuffleMask[i] < 0)
5957         PFIndexes[i] = 8;
5958       else
5959         PFIndexes[i] = ShuffleMask[i];
5960     }
5961
5962     // Compute the index in the perfect shuffle table.
5963     unsigned PFTableIndex =
5964       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5965     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5966     unsigned Cost = (PFEntry >> 30);
5967
5968     if (Cost <= 4)
5969       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5970   }
5971
5972   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5973   if (EltSize >= 32) {
5974     // Do the expansion with floating-point types, since that is what the VFP
5975     // registers are defined to use, and since i64 is not legal.
5976     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5977     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5978     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5979     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5980     SmallVector<SDValue, 8> Ops;
5981     for (unsigned i = 0; i < NumElts; ++i) {
5982       if (ShuffleMask[i] < 0)
5983         Ops.push_back(DAG.getUNDEF(EltVT));
5984       else
5985         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5986                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5987                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5988                                                   dl, MVT::i32)));
5989     }
5990     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5991     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5992   }
5993
5994   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5995     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5996
5997   if (VT == MVT::v8i8) {
5998     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5999     if (NewOp.getNode())
6000       return NewOp;
6001   }
6002
6003   return SDValue();
6004 }
6005
6006 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6007   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6008   SDValue Lane = Op.getOperand(2);
6009   if (!isa<ConstantSDNode>(Lane))
6010     return SDValue();
6011
6012   return Op;
6013 }
6014
6015 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6016   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6017   SDValue Lane = Op.getOperand(1);
6018   if (!isa<ConstantSDNode>(Lane))
6019     return SDValue();
6020
6021   SDValue Vec = Op.getOperand(0);
6022   if (Op.getValueType() == MVT::i32 &&
6023       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6024     SDLoc dl(Op);
6025     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6026   }
6027
6028   return Op;
6029 }
6030
6031 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6032   // The only time a CONCAT_VECTORS operation can have legal types is when
6033   // two 64-bit vectors are concatenated to a 128-bit vector.
6034   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6035          "unexpected CONCAT_VECTORS");
6036   SDLoc dl(Op);
6037   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6038   SDValue Op0 = Op.getOperand(0);
6039   SDValue Op1 = Op.getOperand(1);
6040   if (Op0.getOpcode() != ISD::UNDEF)
6041     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6042                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6043                       DAG.getIntPtrConstant(0, dl));
6044   if (Op1.getOpcode() != ISD::UNDEF)
6045     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6046                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6047                       DAG.getIntPtrConstant(1, dl));
6048   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6049 }
6050
6051 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6052 /// element has been zero/sign-extended, depending on the isSigned parameter,
6053 /// from an integer type half its size.
6054 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6055                                    bool isSigned) {
6056   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6057   EVT VT = N->getValueType(0);
6058   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6059     SDNode *BVN = N->getOperand(0).getNode();
6060     if (BVN->getValueType(0) != MVT::v4i32 ||
6061         BVN->getOpcode() != ISD::BUILD_VECTOR)
6062       return false;
6063     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6064     unsigned HiElt = 1 - LoElt;
6065     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6066     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6067     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6068     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6069     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6070       return false;
6071     if (isSigned) {
6072       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6073           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6074         return true;
6075     } else {
6076       if (Hi0->isNullValue() && Hi1->isNullValue())
6077         return true;
6078     }
6079     return false;
6080   }
6081
6082   if (N->getOpcode() != ISD::BUILD_VECTOR)
6083     return false;
6084
6085   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6086     SDNode *Elt = N->getOperand(i).getNode();
6087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6088       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6089       unsigned HalfSize = EltSize / 2;
6090       if (isSigned) {
6091         if (!isIntN(HalfSize, C->getSExtValue()))
6092           return false;
6093       } else {
6094         if (!isUIntN(HalfSize, C->getZExtValue()))
6095           return false;
6096       }
6097       continue;
6098     }
6099     return false;
6100   }
6101
6102   return true;
6103 }
6104
6105 /// isSignExtended - Check if a node is a vector value that is sign-extended
6106 /// or a constant BUILD_VECTOR with sign-extended elements.
6107 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6108   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6109     return true;
6110   if (isExtendedBUILD_VECTOR(N, DAG, true))
6111     return true;
6112   return false;
6113 }
6114
6115 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6116 /// or a constant BUILD_VECTOR with zero-extended elements.
6117 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6118   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6119     return true;
6120   if (isExtendedBUILD_VECTOR(N, DAG, false))
6121     return true;
6122   return false;
6123 }
6124
6125 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6126   if (OrigVT.getSizeInBits() >= 64)
6127     return OrigVT;
6128
6129   assert(OrigVT.isSimple() && "Expecting a simple value type");
6130
6131   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6132   switch (OrigSimpleTy) {
6133   default: llvm_unreachable("Unexpected Vector Type");
6134   case MVT::v2i8:
6135   case MVT::v2i16:
6136      return MVT::v2i32;
6137   case MVT::v4i8:
6138     return  MVT::v4i16;
6139   }
6140 }
6141
6142 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6143 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6144 /// We insert the required extension here to get the vector to fill a D register.
6145 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6146                                             const EVT &OrigTy,
6147                                             const EVT &ExtTy,
6148                                             unsigned ExtOpcode) {
6149   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6150   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6151   // 64-bits we need to insert a new extension so that it will be 64-bits.
6152   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6153   if (OrigTy.getSizeInBits() >= 64)
6154     return N;
6155
6156   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6157   EVT NewVT = getExtensionTo64Bits(OrigTy);
6158
6159   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6160 }
6161
6162 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6163 /// does not do any sign/zero extension. If the original vector is less
6164 /// than 64 bits, an appropriate extension will be added after the load to
6165 /// reach a total size of 64 bits. We have to add the extension separately
6166 /// because ARM does not have a sign/zero extending load for vectors.
6167 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6168   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6169
6170   // The load already has the right type.
6171   if (ExtendedTy == LD->getMemoryVT())
6172     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6173                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6174                 LD->isNonTemporal(), LD->isInvariant(),
6175                 LD->getAlignment());
6176
6177   // We need to create a zextload/sextload. We cannot just create a load
6178   // followed by a zext/zext node because LowerMUL is also run during normal
6179   // operation legalization where we can't create illegal types.
6180   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6181                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6182                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6183                         LD->isNonTemporal(), LD->getAlignment());
6184 }
6185
6186 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6187 /// extending load, or BUILD_VECTOR with extended elements, return the
6188 /// unextended value. The unextended vector should be 64 bits so that it can
6189 /// be used as an operand to a VMULL instruction. If the original vector size
6190 /// before extension is less than 64 bits we add a an extension to resize
6191 /// the vector to 64 bits.
6192 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6193   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6194     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6195                                         N->getOperand(0)->getValueType(0),
6196                                         N->getValueType(0),
6197                                         N->getOpcode());
6198
6199   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6200     return SkipLoadExtensionForVMULL(LD, DAG);
6201
6202   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6203   // have been legalized as a BITCAST from v4i32.
6204   if (N->getOpcode() == ISD::BITCAST) {
6205     SDNode *BVN = N->getOperand(0).getNode();
6206     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6207            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6208     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6209     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6210                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6211   }
6212   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6213   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6214   EVT VT = N->getValueType(0);
6215   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6216   unsigned NumElts = VT.getVectorNumElements();
6217   MVT TruncVT = MVT::getIntegerVT(EltSize);
6218   SmallVector<SDValue, 8> Ops;
6219   SDLoc dl(N);
6220   for (unsigned i = 0; i != NumElts; ++i) {
6221     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6222     const APInt &CInt = C->getAPIntValue();
6223     // Element types smaller than 32 bits are not legal, so use i32 elements.
6224     // The values are implicitly truncated so sext vs. zext doesn't matter.
6225     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6226   }
6227   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6228                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6229 }
6230
6231 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6232   unsigned Opcode = N->getOpcode();
6233   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6234     SDNode *N0 = N->getOperand(0).getNode();
6235     SDNode *N1 = N->getOperand(1).getNode();
6236     return N0->hasOneUse() && N1->hasOneUse() &&
6237       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6238   }
6239   return false;
6240 }
6241
6242 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6243   unsigned Opcode = N->getOpcode();
6244   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6245     SDNode *N0 = N->getOperand(0).getNode();
6246     SDNode *N1 = N->getOperand(1).getNode();
6247     return N0->hasOneUse() && N1->hasOneUse() &&
6248       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6249   }
6250   return false;
6251 }
6252
6253 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6254   // Multiplications are only custom-lowered for 128-bit vectors so that
6255   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6256   EVT VT = Op.getValueType();
6257   assert(VT.is128BitVector() && VT.isInteger() &&
6258          "unexpected type for custom-lowering ISD::MUL");
6259   SDNode *N0 = Op.getOperand(0).getNode();
6260   SDNode *N1 = Op.getOperand(1).getNode();
6261   unsigned NewOpc = 0;
6262   bool isMLA = false;
6263   bool isN0SExt = isSignExtended(N0, DAG);
6264   bool isN1SExt = isSignExtended(N1, DAG);
6265   if (isN0SExt && isN1SExt)
6266     NewOpc = ARMISD::VMULLs;
6267   else {
6268     bool isN0ZExt = isZeroExtended(N0, DAG);
6269     bool isN1ZExt = isZeroExtended(N1, DAG);
6270     if (isN0ZExt && isN1ZExt)
6271       NewOpc = ARMISD::VMULLu;
6272     else if (isN1SExt || isN1ZExt) {
6273       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6274       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6275       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6276         NewOpc = ARMISD::VMULLs;
6277         isMLA = true;
6278       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6279         NewOpc = ARMISD::VMULLu;
6280         isMLA = true;
6281       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6282         std::swap(N0, N1);
6283         NewOpc = ARMISD::VMULLu;
6284         isMLA = true;
6285       }
6286     }
6287
6288     if (!NewOpc) {
6289       if (VT == MVT::v2i64)
6290         // Fall through to expand this.  It is not legal.
6291         return SDValue();
6292       else
6293         // Other vector multiplications are legal.
6294         return Op;
6295     }
6296   }
6297
6298   // Legalize to a VMULL instruction.
6299   SDLoc DL(Op);
6300   SDValue Op0;
6301   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6302   if (!isMLA) {
6303     Op0 = SkipExtensionForVMULL(N0, DAG);
6304     assert(Op0.getValueType().is64BitVector() &&
6305            Op1.getValueType().is64BitVector() &&
6306            "unexpected types for extended operands to VMULL");
6307     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6308   }
6309
6310   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6311   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6312   //   vmull q0, d4, d6
6313   //   vmlal q0, d5, d6
6314   // is faster than
6315   //   vaddl q0, d4, d5
6316   //   vmovl q1, d6
6317   //   vmul  q0, q0, q1
6318   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6319   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6320   EVT Op1VT = Op1.getValueType();
6321   return DAG.getNode(N0->getOpcode(), DL, VT,
6322                      DAG.getNode(NewOpc, DL, VT,
6323                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6324                      DAG.getNode(NewOpc, DL, VT,
6325                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6326 }
6327
6328 static SDValue
6329 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6330   // Convert to float
6331   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6332   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6333   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6334   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6335   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6336   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6337   // Get reciprocal estimate.
6338   // float4 recip = vrecpeq_f32(yf);
6339   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6340                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6341                    Y);
6342   // Because char has a smaller range than uchar, we can actually get away
6343   // without any newton steps.  This requires that we use a weird bias
6344   // of 0xb000, however (again, this has been exhaustively tested).
6345   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6346   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6347   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6348   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6349   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6350   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6351   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6352   // Convert back to short.
6353   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6354   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6355   return X;
6356 }
6357
6358 static SDValue
6359 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6360   SDValue N2;
6361   // Convert to float.
6362   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6363   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6364   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6365   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6366   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6367   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6368
6369   // Use reciprocal estimate and one refinement step.
6370   // float4 recip = vrecpeq_f32(yf);
6371   // recip *= vrecpsq_f32(yf, recip);
6372   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6373                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6374                    N1);
6375   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6376                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6377                    N1, N2);
6378   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6379   // Because short has a smaller range than ushort, we can actually get away
6380   // with only a single newton step.  This requires that we use a weird bias
6381   // of 89, however (again, this has been exhaustively tested).
6382   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6383   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6384   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6385   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6386   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6387   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6388   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6389   // Convert back to integer and return.
6390   // return vmovn_s32(vcvt_s32_f32(result));
6391   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6392   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6393   return N0;
6394 }
6395
6396 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6397   EVT VT = Op.getValueType();
6398   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6399          "unexpected type for custom-lowering ISD::SDIV");
6400
6401   SDLoc dl(Op);
6402   SDValue N0 = Op.getOperand(0);
6403   SDValue N1 = Op.getOperand(1);
6404   SDValue N2, N3;
6405
6406   if (VT == MVT::v8i8) {
6407     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6408     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6409
6410     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6411                      DAG.getIntPtrConstant(4, dl));
6412     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6413                      DAG.getIntPtrConstant(4, dl));
6414     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6415                      DAG.getIntPtrConstant(0, dl));
6416     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6417                      DAG.getIntPtrConstant(0, dl));
6418
6419     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6420     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6421
6422     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6423     N0 = LowerCONCAT_VECTORS(N0, DAG);
6424
6425     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6426     return N0;
6427   }
6428   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6429 }
6430
6431 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6432   EVT VT = Op.getValueType();
6433   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6434          "unexpected type for custom-lowering ISD::UDIV");
6435
6436   SDLoc dl(Op);
6437   SDValue N0 = Op.getOperand(0);
6438   SDValue N1 = Op.getOperand(1);
6439   SDValue N2, N3;
6440
6441   if (VT == MVT::v8i8) {
6442     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6443     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6444
6445     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6446                      DAG.getIntPtrConstant(4, dl));
6447     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6448                      DAG.getIntPtrConstant(4, dl));
6449     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6450                      DAG.getIntPtrConstant(0, dl));
6451     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6452                      DAG.getIntPtrConstant(0, dl));
6453
6454     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6455     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6456
6457     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6458     N0 = LowerCONCAT_VECTORS(N0, DAG);
6459
6460     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6461                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6462                                      MVT::i32),
6463                      N0);
6464     return N0;
6465   }
6466
6467   // v4i16 sdiv ... Convert to float.
6468   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6469   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6470   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6471   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6472   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6473   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6474
6475   // Use reciprocal estimate and two refinement steps.
6476   // float4 recip = vrecpeq_f32(yf);
6477   // recip *= vrecpsq_f32(yf, recip);
6478   // recip *= vrecpsq_f32(yf, recip);
6479   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6480                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6481                    BN1);
6482   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6483                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6484                    BN1, N2);
6485   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6486   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6487                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6488                    BN1, N2);
6489   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6490   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6491   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6492   // and that it will never cause us to return an answer too large).
6493   // float4 result = as_float4(as_int4(xf*recip) + 2);
6494   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6495   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6496   N1 = DAG.getConstant(2, dl, MVT::i32);
6497   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6498   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6499   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6500   // Convert back to integer and return.
6501   // return vmovn_u32(vcvt_s32_f32(result));
6502   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6503   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6504   return N0;
6505 }
6506
6507 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6508   EVT VT = Op.getNode()->getValueType(0);
6509   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6510
6511   unsigned Opc;
6512   bool ExtraOp = false;
6513   switch (Op.getOpcode()) {
6514   default: llvm_unreachable("Invalid code");
6515   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6516   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6517   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6518   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6519   }
6520
6521   if (!ExtraOp)
6522     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6523                        Op.getOperand(1));
6524   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6525                      Op.getOperand(1), Op.getOperand(2));
6526 }
6527
6528 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6529   assert(Subtarget->isTargetDarwin());
6530
6531   // For iOS, we want to call an alternative entry point: __sincos_stret,
6532   // return values are passed via sret.
6533   SDLoc dl(Op);
6534   SDValue Arg = Op.getOperand(0);
6535   EVT ArgVT = Arg.getValueType();
6536   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6537   auto PtrVT = getPointerTy(DAG.getDataLayout());
6538
6539   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6540
6541   // Pair of floats / doubles used to pass the result.
6542   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6543
6544   // Create stack object for sret.
6545   auto &DL = DAG.getDataLayout();
6546   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6547   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6548   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6549   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6550
6551   ArgListTy Args;
6552   ArgListEntry Entry;
6553
6554   Entry.Node = SRet;
6555   Entry.Ty = RetTy->getPointerTo();
6556   Entry.isSExt = false;
6557   Entry.isZExt = false;
6558   Entry.isSRet = true;
6559   Args.push_back(Entry);
6560
6561   Entry.Node = Arg;
6562   Entry.Ty = ArgTy;
6563   Entry.isSExt = false;
6564   Entry.isZExt = false;
6565   Args.push_back(Entry);
6566
6567   const char *LibcallName  = (ArgVT == MVT::f64)
6568   ? "__sincos_stret" : "__sincosf_stret";
6569   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6570
6571   TargetLowering::CallLoweringInfo CLI(DAG);
6572   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6573     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6574                std::move(Args), 0)
6575     .setDiscardResult();
6576
6577   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6578
6579   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6580                                 MachinePointerInfo(), false, false, false, 0);
6581
6582   // Address of cos field.
6583   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6584                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6585   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6586                                 MachinePointerInfo(), false, false, false, 0);
6587
6588   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6589   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6590                      LoadSin.getValue(0), LoadCos.getValue(0));
6591 }
6592
6593 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6594   // Monotonic load/store is legal for all targets
6595   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6596     return Op;
6597
6598   // Acquire/Release load/store is not legal for targets without a
6599   // dmb or equivalent available.
6600   return SDValue();
6601 }
6602
6603 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6604                                     SmallVectorImpl<SDValue> &Results,
6605                                     SelectionDAG &DAG,
6606                                     const ARMSubtarget *Subtarget) {
6607   SDLoc DL(N);
6608   SDValue Cycles32, OutChain;
6609
6610   if (Subtarget->hasPerfMon()) {
6611     // Under Power Management extensions, the cycle-count is:
6612     //    mrc p15, #0, <Rt>, c9, c13, #0
6613     SDValue Ops[] = { N->getOperand(0), // Chain
6614                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6615                       DAG.getConstant(15, DL, MVT::i32),
6616                       DAG.getConstant(0, DL, MVT::i32),
6617                       DAG.getConstant(9, DL, MVT::i32),
6618                       DAG.getConstant(13, DL, MVT::i32),
6619                       DAG.getConstant(0, DL, MVT::i32)
6620     };
6621
6622     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6623                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6624     OutChain = Cycles32.getValue(1);
6625   } else {
6626     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6627     // there are older ARM CPUs that have implementation-specific ways of
6628     // obtaining this information (FIXME!).
6629     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6630     OutChain = DAG.getEntryNode();
6631   }
6632
6633
6634   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6635                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6636   Results.push_back(Cycles64);
6637   Results.push_back(OutChain);
6638 }
6639
6640 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6641   switch (Op.getOpcode()) {
6642   default: llvm_unreachable("Don't know how to custom lower this!");
6643   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6644   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6645   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6646   case ISD::GlobalAddress:
6647     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6648     default: llvm_unreachable("unknown object format");
6649     case Triple::COFF:
6650       return LowerGlobalAddressWindows(Op, DAG);
6651     case Triple::ELF:
6652       return LowerGlobalAddressELF(Op, DAG);
6653     case Triple::MachO:
6654       return LowerGlobalAddressDarwin(Op, DAG);
6655     }
6656   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6657   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6658   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6659   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6660   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6661   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6662   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6663   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6664   case ISD::SINT_TO_FP:
6665   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6666   case ISD::FP_TO_SINT:
6667   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6668   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6669   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6670   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6671   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6672   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6673   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6674   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6675   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6676                                                                Subtarget);
6677   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6678   case ISD::SHL:
6679   case ISD::SRL:
6680   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6681   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6682   case ISD::SRL_PARTS:
6683   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6684   case ISD::CTTZ:
6685   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6686   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6687   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6688   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6689   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6690   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6691   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6692   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6693   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6694   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6695   case ISD::MUL:           return LowerMUL(Op, DAG);
6696   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6697   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6698   case ISD::ADDC:
6699   case ISD::ADDE:
6700   case ISD::SUBC:
6701   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6702   case ISD::SADDO:
6703   case ISD::UADDO:
6704   case ISD::SSUBO:
6705   case ISD::USUBO:
6706     return LowerXALUO(Op, DAG);
6707   case ISD::ATOMIC_LOAD:
6708   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6709   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6710   case ISD::SDIVREM:
6711   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6712   case ISD::DYNAMIC_STACKALLOC:
6713     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6714       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6715     llvm_unreachable("Don't know how to custom lower this!");
6716   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6717   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6718   }
6719 }
6720
6721 /// ReplaceNodeResults - Replace the results of node with an illegal result
6722 /// type with new values built out of custom code.
6723 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6724                                            SmallVectorImpl<SDValue>&Results,
6725                                            SelectionDAG &DAG) const {
6726   SDValue Res;
6727   switch (N->getOpcode()) {
6728   default:
6729     llvm_unreachable("Don't know how to custom expand this!");
6730   case ISD::READ_REGISTER:
6731     ExpandREAD_REGISTER(N, Results, DAG);
6732     break;
6733   case ISD::BITCAST:
6734     Res = ExpandBITCAST(N, DAG);
6735     break;
6736   case ISD::SRL:
6737   case ISD::SRA:
6738     Res = Expand64BitShift(N, DAG, Subtarget);
6739     break;
6740   case ISD::READCYCLECOUNTER:
6741     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6742     return;
6743   }
6744   if (Res.getNode())
6745     Results.push_back(Res);
6746 }
6747
6748 //===----------------------------------------------------------------------===//
6749 //                           ARM Scheduler Hooks
6750 //===----------------------------------------------------------------------===//
6751
6752 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6753 /// registers the function context.
6754 void ARMTargetLowering::
6755 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6756                        MachineBasicBlock *DispatchBB, int FI) const {
6757   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6758   DebugLoc dl = MI->getDebugLoc();
6759   MachineFunction *MF = MBB->getParent();
6760   MachineRegisterInfo *MRI = &MF->getRegInfo();
6761   MachineConstantPool *MCP = MF->getConstantPool();
6762   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6763   const Function *F = MF->getFunction();
6764
6765   bool isThumb = Subtarget->isThumb();
6766   bool isThumb2 = Subtarget->isThumb2();
6767
6768   unsigned PCLabelId = AFI->createPICLabelUId();
6769   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6770   ARMConstantPoolValue *CPV =
6771     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6772   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6773
6774   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6775                                            : &ARM::GPRRegClass;
6776
6777   // Grab constant pool and fixed stack memory operands.
6778   MachineMemOperand *CPMMO =
6779     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6780                              MachineMemOperand::MOLoad, 4, 4);
6781
6782   MachineMemOperand *FIMMOSt =
6783     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6784                              MachineMemOperand::MOStore, 4, 4);
6785
6786   // Load the address of the dispatch MBB into the jump buffer.
6787   if (isThumb2) {
6788     // Incoming value: jbuf
6789     //   ldr.n  r5, LCPI1_1
6790     //   orr    r5, r5, #1
6791     //   add    r5, pc
6792     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6793     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6794     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6795                    .addConstantPoolIndex(CPI)
6796                    .addMemOperand(CPMMO));
6797     // Set the low bit because of thumb mode.
6798     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6799     AddDefaultCC(
6800       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6801                      .addReg(NewVReg1, RegState::Kill)
6802                      .addImm(0x01)));
6803     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6804     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6805       .addReg(NewVReg2, RegState::Kill)
6806       .addImm(PCLabelId);
6807     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6808                    .addReg(NewVReg3, RegState::Kill)
6809                    .addFrameIndex(FI)
6810                    .addImm(36)  // &jbuf[1] :: pc
6811                    .addMemOperand(FIMMOSt));
6812   } else if (isThumb) {
6813     // Incoming value: jbuf
6814     //   ldr.n  r1, LCPI1_4
6815     //   add    r1, pc
6816     //   mov    r2, #1
6817     //   orrs   r1, r2
6818     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6819     //   str    r1, [r2]
6820     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6821     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6822                    .addConstantPoolIndex(CPI)
6823                    .addMemOperand(CPMMO));
6824     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6825     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6826       .addReg(NewVReg1, RegState::Kill)
6827       .addImm(PCLabelId);
6828     // Set the low bit because of thumb mode.
6829     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6830     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6831                    .addReg(ARM::CPSR, RegState::Define)
6832                    .addImm(1));
6833     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6834     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6835                    .addReg(ARM::CPSR, RegState::Define)
6836                    .addReg(NewVReg2, RegState::Kill)
6837                    .addReg(NewVReg3, RegState::Kill));
6838     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6839     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6840             .addFrameIndex(FI)
6841             .addImm(36); // &jbuf[1] :: pc
6842     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6843                    .addReg(NewVReg4, RegState::Kill)
6844                    .addReg(NewVReg5, RegState::Kill)
6845                    .addImm(0)
6846                    .addMemOperand(FIMMOSt));
6847   } else {
6848     // Incoming value: jbuf
6849     //   ldr  r1, LCPI1_1
6850     //   add  r1, pc, r1
6851     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6852     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6853     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6854                    .addConstantPoolIndex(CPI)
6855                    .addImm(0)
6856                    .addMemOperand(CPMMO));
6857     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6858     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6859                    .addReg(NewVReg1, RegState::Kill)
6860                    .addImm(PCLabelId));
6861     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6862                    .addReg(NewVReg2, RegState::Kill)
6863                    .addFrameIndex(FI)
6864                    .addImm(36)  // &jbuf[1] :: pc
6865                    .addMemOperand(FIMMOSt));
6866   }
6867 }
6868
6869 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6870                                               MachineBasicBlock *MBB) const {
6871   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6872   DebugLoc dl = MI->getDebugLoc();
6873   MachineFunction *MF = MBB->getParent();
6874   MachineRegisterInfo *MRI = &MF->getRegInfo();
6875   MachineFrameInfo *MFI = MF->getFrameInfo();
6876   int FI = MFI->getFunctionContextIndex();
6877
6878   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6879                                                         : &ARM::GPRnopcRegClass;
6880
6881   // Get a mapping of the call site numbers to all of the landing pads they're
6882   // associated with.
6883   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6884   unsigned MaxCSNum = 0;
6885   MachineModuleInfo &MMI = MF->getMMI();
6886   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6887        ++BB) {
6888     if (!BB->isLandingPad()) continue;
6889
6890     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6891     // pad.
6892     for (MachineBasicBlock::iterator
6893            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6894       if (!II->isEHLabel()) continue;
6895
6896       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6897       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6898
6899       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6900       for (SmallVectorImpl<unsigned>::iterator
6901              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6902            CSI != CSE; ++CSI) {
6903         CallSiteNumToLPad[*CSI].push_back(BB);
6904         MaxCSNum = std::max(MaxCSNum, *CSI);
6905       }
6906       break;
6907     }
6908   }
6909
6910   // Get an ordered list of the machine basic blocks for the jump table.
6911   std::vector<MachineBasicBlock*> LPadList;
6912   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6913   LPadList.reserve(CallSiteNumToLPad.size());
6914   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6915     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6916     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6917            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6918       LPadList.push_back(*II);
6919       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6920     }
6921   }
6922
6923   assert(!LPadList.empty() &&
6924          "No landing pad destinations for the dispatch jump table!");
6925
6926   // Create the jump table and associated information.
6927   MachineJumpTableInfo *JTI =
6928     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6929   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6930   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6931
6932   // Create the MBBs for the dispatch code.
6933
6934   // Shove the dispatch's address into the return slot in the function context.
6935   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6936   DispatchBB->setIsLandingPad();
6937
6938   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6939   unsigned trap_opcode;
6940   if (Subtarget->isThumb())
6941     trap_opcode = ARM::tTRAP;
6942   else
6943     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6944
6945   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6946   DispatchBB->addSuccessor(TrapBB);
6947
6948   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6949   DispatchBB->addSuccessor(DispContBB);
6950
6951   // Insert and MBBs.
6952   MF->insert(MF->end(), DispatchBB);
6953   MF->insert(MF->end(), DispContBB);
6954   MF->insert(MF->end(), TrapBB);
6955
6956   // Insert code into the entry block that creates and registers the function
6957   // context.
6958   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6959
6960   MachineMemOperand *FIMMOLd =
6961     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6962                              MachineMemOperand::MOLoad |
6963                              MachineMemOperand::MOVolatile, 4, 4);
6964
6965   MachineInstrBuilder MIB;
6966   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6967
6968   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6969   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6970
6971   // Add a register mask with no preserved registers.  This results in all
6972   // registers being marked as clobbered.
6973   MIB.addRegMask(RI.getNoPreservedMask());
6974
6975   unsigned NumLPads = LPadList.size();
6976   if (Subtarget->isThumb2()) {
6977     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6978     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6979                    .addFrameIndex(FI)
6980                    .addImm(4)
6981                    .addMemOperand(FIMMOLd));
6982
6983     if (NumLPads < 256) {
6984       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6985                      .addReg(NewVReg1)
6986                      .addImm(LPadList.size()));
6987     } else {
6988       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6989       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6990                      .addImm(NumLPads & 0xFFFF));
6991
6992       unsigned VReg2 = VReg1;
6993       if ((NumLPads & 0xFFFF0000) != 0) {
6994         VReg2 = MRI->createVirtualRegister(TRC);
6995         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6996                        .addReg(VReg1)
6997                        .addImm(NumLPads >> 16));
6998       }
6999
7000       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7001                      .addReg(NewVReg1)
7002                      .addReg(VReg2));
7003     }
7004
7005     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7006       .addMBB(TrapBB)
7007       .addImm(ARMCC::HI)
7008       .addReg(ARM::CPSR);
7009
7010     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7011     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7012                    .addJumpTableIndex(MJTI));
7013
7014     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7015     AddDefaultCC(
7016       AddDefaultPred(
7017         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7018         .addReg(NewVReg3, RegState::Kill)
7019         .addReg(NewVReg1)
7020         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7021
7022     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7023       .addReg(NewVReg4, RegState::Kill)
7024       .addReg(NewVReg1)
7025       .addJumpTableIndex(MJTI);
7026   } else if (Subtarget->isThumb()) {
7027     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7028     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7029                    .addFrameIndex(FI)
7030                    .addImm(1)
7031                    .addMemOperand(FIMMOLd));
7032
7033     if (NumLPads < 256) {
7034       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7035                      .addReg(NewVReg1)
7036                      .addImm(NumLPads));
7037     } else {
7038       MachineConstantPool *ConstantPool = MF->getConstantPool();
7039       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7040       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7041
7042       // MachineConstantPool wants an explicit alignment.
7043       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7044       if (Align == 0)
7045         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7046       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7047
7048       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7049       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7050                      .addReg(VReg1, RegState::Define)
7051                      .addConstantPoolIndex(Idx));
7052       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7053                      .addReg(NewVReg1)
7054                      .addReg(VReg1));
7055     }
7056
7057     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7058       .addMBB(TrapBB)
7059       .addImm(ARMCC::HI)
7060       .addReg(ARM::CPSR);
7061
7062     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7063     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7064                    .addReg(ARM::CPSR, RegState::Define)
7065                    .addReg(NewVReg1)
7066                    .addImm(2));
7067
7068     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7069     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7070                    .addJumpTableIndex(MJTI));
7071
7072     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7073     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7074                    .addReg(ARM::CPSR, RegState::Define)
7075                    .addReg(NewVReg2, RegState::Kill)
7076                    .addReg(NewVReg3));
7077
7078     MachineMemOperand *JTMMOLd =
7079       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7080                                MachineMemOperand::MOLoad, 4, 4);
7081
7082     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7083     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7084                    .addReg(NewVReg4, RegState::Kill)
7085                    .addImm(0)
7086                    .addMemOperand(JTMMOLd));
7087
7088     unsigned NewVReg6 = NewVReg5;
7089     if (RelocM == Reloc::PIC_) {
7090       NewVReg6 = MRI->createVirtualRegister(TRC);
7091       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7092                      .addReg(ARM::CPSR, RegState::Define)
7093                      .addReg(NewVReg5, RegState::Kill)
7094                      .addReg(NewVReg3));
7095     }
7096
7097     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7098       .addReg(NewVReg6, RegState::Kill)
7099       .addJumpTableIndex(MJTI);
7100   } else {
7101     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7102     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7103                    .addFrameIndex(FI)
7104                    .addImm(4)
7105                    .addMemOperand(FIMMOLd));
7106
7107     if (NumLPads < 256) {
7108       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7109                      .addReg(NewVReg1)
7110                      .addImm(NumLPads));
7111     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7112       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7113       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7114                      .addImm(NumLPads & 0xFFFF));
7115
7116       unsigned VReg2 = VReg1;
7117       if ((NumLPads & 0xFFFF0000) != 0) {
7118         VReg2 = MRI->createVirtualRegister(TRC);
7119         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7120                        .addReg(VReg1)
7121                        .addImm(NumLPads >> 16));
7122       }
7123
7124       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7125                      .addReg(NewVReg1)
7126                      .addReg(VReg2));
7127     } else {
7128       MachineConstantPool *ConstantPool = MF->getConstantPool();
7129       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7130       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7131
7132       // MachineConstantPool wants an explicit alignment.
7133       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7134       if (Align == 0)
7135         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7136       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7137
7138       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7139       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7140                      .addReg(VReg1, RegState::Define)
7141                      .addConstantPoolIndex(Idx)
7142                      .addImm(0));
7143       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7144                      .addReg(NewVReg1)
7145                      .addReg(VReg1, RegState::Kill));
7146     }
7147
7148     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7149       .addMBB(TrapBB)
7150       .addImm(ARMCC::HI)
7151       .addReg(ARM::CPSR);
7152
7153     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7154     AddDefaultCC(
7155       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7156                      .addReg(NewVReg1)
7157                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7158     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7159     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7160                    .addJumpTableIndex(MJTI));
7161
7162     MachineMemOperand *JTMMOLd =
7163       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7164                                MachineMemOperand::MOLoad, 4, 4);
7165     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7166     AddDefaultPred(
7167       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7168       .addReg(NewVReg3, RegState::Kill)
7169       .addReg(NewVReg4)
7170       .addImm(0)
7171       .addMemOperand(JTMMOLd));
7172
7173     if (RelocM == Reloc::PIC_) {
7174       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7175         .addReg(NewVReg5, RegState::Kill)
7176         .addReg(NewVReg4)
7177         .addJumpTableIndex(MJTI);
7178     } else {
7179       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7180         .addReg(NewVReg5, RegState::Kill)
7181         .addJumpTableIndex(MJTI);
7182     }
7183   }
7184
7185   // Add the jump table entries as successors to the MBB.
7186   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7187   for (std::vector<MachineBasicBlock*>::iterator
7188          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7189     MachineBasicBlock *CurMBB = *I;
7190     if (SeenMBBs.insert(CurMBB).second)
7191       DispContBB->addSuccessor(CurMBB);
7192   }
7193
7194   // N.B. the order the invoke BBs are processed in doesn't matter here.
7195   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7196   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7197   for (MachineBasicBlock *BB : InvokeBBs) {
7198
7199     // Remove the landing pad successor from the invoke block and replace it
7200     // with the new dispatch block.
7201     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7202                                                   BB->succ_end());
7203     while (!Successors.empty()) {
7204       MachineBasicBlock *SMBB = Successors.pop_back_val();
7205       if (SMBB->isLandingPad()) {
7206         BB->removeSuccessor(SMBB);
7207         MBBLPads.push_back(SMBB);
7208       }
7209     }
7210
7211     BB->addSuccessor(DispatchBB);
7212
7213     // Find the invoke call and mark all of the callee-saved registers as
7214     // 'implicit defined' so that they're spilled. This prevents code from
7215     // moving instructions to before the EH block, where they will never be
7216     // executed.
7217     for (MachineBasicBlock::reverse_iterator
7218            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7219       if (!II->isCall()) continue;
7220
7221       DenseMap<unsigned, bool> DefRegs;
7222       for (MachineInstr::mop_iterator
7223              OI = II->operands_begin(), OE = II->operands_end();
7224            OI != OE; ++OI) {
7225         if (!OI->isReg()) continue;
7226         DefRegs[OI->getReg()] = true;
7227       }
7228
7229       MachineInstrBuilder MIB(*MF, &*II);
7230
7231       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7232         unsigned Reg = SavedRegs[i];
7233         if (Subtarget->isThumb2() &&
7234             !ARM::tGPRRegClass.contains(Reg) &&
7235             !ARM::hGPRRegClass.contains(Reg))
7236           continue;
7237         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7238           continue;
7239         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7240           continue;
7241         if (!DefRegs[Reg])
7242           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7243       }
7244
7245       break;
7246     }
7247   }
7248
7249   // Mark all former landing pads as non-landing pads. The dispatch is the only
7250   // landing pad now.
7251   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7252          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7253     (*I)->setIsLandingPad(false);
7254
7255   // The instruction is gone now.
7256   MI->eraseFromParent();
7257 }
7258
7259 static
7260 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7261   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7262        E = MBB->succ_end(); I != E; ++I)
7263     if (*I != Succ)
7264       return *I;
7265   llvm_unreachable("Expecting a BB with two successors!");
7266 }
7267
7268 /// Return the load opcode for a given load size. If load size >= 8,
7269 /// neon opcode will be returned.
7270 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7271   if (LdSize >= 8)
7272     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7273                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7274   if (IsThumb1)
7275     return LdSize == 4 ? ARM::tLDRi
7276                        : LdSize == 2 ? ARM::tLDRHi
7277                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7278   if (IsThumb2)
7279     return LdSize == 4 ? ARM::t2LDR_POST
7280                        : LdSize == 2 ? ARM::t2LDRH_POST
7281                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7282   return LdSize == 4 ? ARM::LDR_POST_IMM
7283                      : LdSize == 2 ? ARM::LDRH_POST
7284                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7285 }
7286
7287 /// Return the store opcode for a given store size. If store size >= 8,
7288 /// neon opcode will be returned.
7289 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7290   if (StSize >= 8)
7291     return StSize == 16 ? ARM::VST1q32wb_fixed
7292                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7293   if (IsThumb1)
7294     return StSize == 4 ? ARM::tSTRi
7295                        : StSize == 2 ? ARM::tSTRHi
7296                                      : StSize == 1 ? ARM::tSTRBi : 0;
7297   if (IsThumb2)
7298     return StSize == 4 ? ARM::t2STR_POST
7299                        : StSize == 2 ? ARM::t2STRH_POST
7300                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7301   return StSize == 4 ? ARM::STR_POST_IMM
7302                      : StSize == 2 ? ARM::STRH_POST
7303                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7304 }
7305
7306 /// Emit a post-increment load operation with given size. The instructions
7307 /// will be added to BB at Pos.
7308 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7309                        const TargetInstrInfo *TII, DebugLoc dl,
7310                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7311                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7312   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7313   assert(LdOpc != 0 && "Should have a load opcode");
7314   if (LdSize >= 8) {
7315     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7316                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7317                        .addImm(0));
7318   } else if (IsThumb1) {
7319     // load + update AddrIn
7320     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7321                        .addReg(AddrIn).addImm(0));
7322     MachineInstrBuilder MIB =
7323         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7324     MIB = AddDefaultT1CC(MIB);
7325     MIB.addReg(AddrIn).addImm(LdSize);
7326     AddDefaultPred(MIB);
7327   } else if (IsThumb2) {
7328     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7329                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7330                        .addImm(LdSize));
7331   } else { // arm
7332     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7333                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7334                        .addReg(0).addImm(LdSize));
7335   }
7336 }
7337
7338 /// Emit a post-increment store operation with given size. The instructions
7339 /// will be added to BB at Pos.
7340 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7341                        const TargetInstrInfo *TII, DebugLoc dl,
7342                        unsigned StSize, unsigned Data, unsigned AddrIn,
7343                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7344   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7345   assert(StOpc != 0 && "Should have a store opcode");
7346   if (StSize >= 8) {
7347     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7348                        .addReg(AddrIn).addImm(0).addReg(Data));
7349   } else if (IsThumb1) {
7350     // store + update AddrIn
7351     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7352                        .addReg(AddrIn).addImm(0));
7353     MachineInstrBuilder MIB =
7354         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7355     MIB = AddDefaultT1CC(MIB);
7356     MIB.addReg(AddrIn).addImm(StSize);
7357     AddDefaultPred(MIB);
7358   } else if (IsThumb2) {
7359     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7360                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7361   } else { // arm
7362     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7363                        .addReg(Data).addReg(AddrIn).addReg(0)
7364                        .addImm(StSize));
7365   }
7366 }
7367
7368 MachineBasicBlock *
7369 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7370                                    MachineBasicBlock *BB) const {
7371   // This pseudo instruction has 3 operands: dst, src, size
7372   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7373   // Otherwise, we will generate unrolled scalar copies.
7374   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7375   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7376   MachineFunction::iterator It = BB;
7377   ++It;
7378
7379   unsigned dest = MI->getOperand(0).getReg();
7380   unsigned src = MI->getOperand(1).getReg();
7381   unsigned SizeVal = MI->getOperand(2).getImm();
7382   unsigned Align = MI->getOperand(3).getImm();
7383   DebugLoc dl = MI->getDebugLoc();
7384
7385   MachineFunction *MF = BB->getParent();
7386   MachineRegisterInfo &MRI = MF->getRegInfo();
7387   unsigned UnitSize = 0;
7388   const TargetRegisterClass *TRC = nullptr;
7389   const TargetRegisterClass *VecTRC = nullptr;
7390
7391   bool IsThumb1 = Subtarget->isThumb1Only();
7392   bool IsThumb2 = Subtarget->isThumb2();
7393
7394   if (Align & 1) {
7395     UnitSize = 1;
7396   } else if (Align & 2) {
7397     UnitSize = 2;
7398   } else {
7399     // Check whether we can use NEON instructions.
7400     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7401         Subtarget->hasNEON()) {
7402       if ((Align % 16 == 0) && SizeVal >= 16)
7403         UnitSize = 16;
7404       else if ((Align % 8 == 0) && SizeVal >= 8)
7405         UnitSize = 8;
7406     }
7407     // Can't use NEON instructions.
7408     if (UnitSize == 0)
7409       UnitSize = 4;
7410   }
7411
7412   // Select the correct opcode and register class for unit size load/store
7413   bool IsNeon = UnitSize >= 8;
7414   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7415   if (IsNeon)
7416     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7417                             : UnitSize == 8 ? &ARM::DPRRegClass
7418                                             : nullptr;
7419
7420   unsigned BytesLeft = SizeVal % UnitSize;
7421   unsigned LoopSize = SizeVal - BytesLeft;
7422
7423   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7424     // Use LDR and STR to copy.
7425     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7426     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7427     unsigned srcIn = src;
7428     unsigned destIn = dest;
7429     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7430       unsigned srcOut = MRI.createVirtualRegister(TRC);
7431       unsigned destOut = MRI.createVirtualRegister(TRC);
7432       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7433       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7434                  IsThumb1, IsThumb2);
7435       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7436                  IsThumb1, IsThumb2);
7437       srcIn = srcOut;
7438       destIn = destOut;
7439     }
7440
7441     // Handle the leftover bytes with LDRB and STRB.
7442     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7443     // [destOut] = STRB_POST(scratch, destIn, 1)
7444     for (unsigned i = 0; i < BytesLeft; i++) {
7445       unsigned srcOut = MRI.createVirtualRegister(TRC);
7446       unsigned destOut = MRI.createVirtualRegister(TRC);
7447       unsigned scratch = MRI.createVirtualRegister(TRC);
7448       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7449                  IsThumb1, IsThumb2);
7450       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7451                  IsThumb1, IsThumb2);
7452       srcIn = srcOut;
7453       destIn = destOut;
7454     }
7455     MI->eraseFromParent();   // The instruction is gone now.
7456     return BB;
7457   }
7458
7459   // Expand the pseudo op to a loop.
7460   // thisMBB:
7461   //   ...
7462   //   movw varEnd, # --> with thumb2
7463   //   movt varEnd, #
7464   //   ldrcp varEnd, idx --> without thumb2
7465   //   fallthrough --> loopMBB
7466   // loopMBB:
7467   //   PHI varPhi, varEnd, varLoop
7468   //   PHI srcPhi, src, srcLoop
7469   //   PHI destPhi, dst, destLoop
7470   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7471   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7472   //   subs varLoop, varPhi, #UnitSize
7473   //   bne loopMBB
7474   //   fallthrough --> exitMBB
7475   // exitMBB:
7476   //   epilogue to handle left-over bytes
7477   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7478   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7479   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7480   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7481   MF->insert(It, loopMBB);
7482   MF->insert(It, exitMBB);
7483
7484   // Transfer the remainder of BB and its successor edges to exitMBB.
7485   exitMBB->splice(exitMBB->begin(), BB,
7486                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7487   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7488
7489   // Load an immediate to varEnd.
7490   unsigned varEnd = MRI.createVirtualRegister(TRC);
7491   if (Subtarget->useMovt(*MF)) {
7492     unsigned Vtmp = varEnd;
7493     if ((LoopSize & 0xFFFF0000) != 0)
7494       Vtmp = MRI.createVirtualRegister(TRC);
7495     AddDefaultPred(BuildMI(BB, dl,
7496                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7497                            Vtmp).addImm(LoopSize & 0xFFFF));
7498
7499     if ((LoopSize & 0xFFFF0000) != 0)
7500       AddDefaultPred(BuildMI(BB, dl,
7501                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7502                              varEnd)
7503                          .addReg(Vtmp)
7504                          .addImm(LoopSize >> 16));
7505   } else {
7506     MachineConstantPool *ConstantPool = MF->getConstantPool();
7507     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7508     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7509
7510     // MachineConstantPool wants an explicit alignment.
7511     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7512     if (Align == 0)
7513       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7514     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7515
7516     if (IsThumb1)
7517       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7518           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7519     else
7520       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7521           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7522   }
7523   BB->addSuccessor(loopMBB);
7524
7525   // Generate the loop body:
7526   //   varPhi = PHI(varLoop, varEnd)
7527   //   srcPhi = PHI(srcLoop, src)
7528   //   destPhi = PHI(destLoop, dst)
7529   MachineBasicBlock *entryBB = BB;
7530   BB = loopMBB;
7531   unsigned varLoop = MRI.createVirtualRegister(TRC);
7532   unsigned varPhi = MRI.createVirtualRegister(TRC);
7533   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7534   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7535   unsigned destLoop = MRI.createVirtualRegister(TRC);
7536   unsigned destPhi = MRI.createVirtualRegister(TRC);
7537
7538   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7539     .addReg(varLoop).addMBB(loopMBB)
7540     .addReg(varEnd).addMBB(entryBB);
7541   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7542     .addReg(srcLoop).addMBB(loopMBB)
7543     .addReg(src).addMBB(entryBB);
7544   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7545     .addReg(destLoop).addMBB(loopMBB)
7546     .addReg(dest).addMBB(entryBB);
7547
7548   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7549   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7550   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7551   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7552              IsThumb1, IsThumb2);
7553   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7554              IsThumb1, IsThumb2);
7555
7556   // Decrement loop variable by UnitSize.
7557   if (IsThumb1) {
7558     MachineInstrBuilder MIB =
7559         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7560     MIB = AddDefaultT1CC(MIB);
7561     MIB.addReg(varPhi).addImm(UnitSize);
7562     AddDefaultPred(MIB);
7563   } else {
7564     MachineInstrBuilder MIB =
7565         BuildMI(*BB, BB->end(), dl,
7566                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7567     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7568     MIB->getOperand(5).setReg(ARM::CPSR);
7569     MIB->getOperand(5).setIsDef(true);
7570   }
7571   BuildMI(*BB, BB->end(), dl,
7572           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7573       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7574
7575   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7576   BB->addSuccessor(loopMBB);
7577   BB->addSuccessor(exitMBB);
7578
7579   // Add epilogue to handle BytesLeft.
7580   BB = exitMBB;
7581   MachineInstr *StartOfExit = exitMBB->begin();
7582
7583   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7584   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7585   unsigned srcIn = srcLoop;
7586   unsigned destIn = destLoop;
7587   for (unsigned i = 0; i < BytesLeft; i++) {
7588     unsigned srcOut = MRI.createVirtualRegister(TRC);
7589     unsigned destOut = MRI.createVirtualRegister(TRC);
7590     unsigned scratch = MRI.createVirtualRegister(TRC);
7591     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7592                IsThumb1, IsThumb2);
7593     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7594                IsThumb1, IsThumb2);
7595     srcIn = srcOut;
7596     destIn = destOut;
7597   }
7598
7599   MI->eraseFromParent();   // The instruction is gone now.
7600   return BB;
7601 }
7602
7603 MachineBasicBlock *
7604 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7605                                        MachineBasicBlock *MBB) const {
7606   const TargetMachine &TM = getTargetMachine();
7607   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7608   DebugLoc DL = MI->getDebugLoc();
7609
7610   assert(Subtarget->isTargetWindows() &&
7611          "__chkstk is only supported on Windows");
7612   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7613
7614   // __chkstk takes the number of words to allocate on the stack in R4, and
7615   // returns the stack adjustment in number of bytes in R4.  This will not
7616   // clober any other registers (other than the obvious lr).
7617   //
7618   // Although, technically, IP should be considered a register which may be
7619   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7620   // thumb-2 environment, so there is no interworking required.  As a result, we
7621   // do not expect a veneer to be emitted by the linker, clobbering IP.
7622   //
7623   // Each module receives its own copy of __chkstk, so no import thunk is
7624   // required, again, ensuring that IP is not clobbered.
7625   //
7626   // Finally, although some linkers may theoretically provide a trampoline for
7627   // out of range calls (which is quite common due to a 32M range limitation of
7628   // branches for Thumb), we can generate the long-call version via
7629   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7630   // IP.
7631
7632   switch (TM.getCodeModel()) {
7633   case CodeModel::Small:
7634   case CodeModel::Medium:
7635   case CodeModel::Default:
7636   case CodeModel::Kernel:
7637     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7638       .addImm((unsigned)ARMCC::AL).addReg(0)
7639       .addExternalSymbol("__chkstk")
7640       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7641       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7642       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7643     break;
7644   case CodeModel::Large:
7645   case CodeModel::JITDefault: {
7646     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7647     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7648
7649     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7650       .addExternalSymbol("__chkstk");
7651     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7652       .addImm((unsigned)ARMCC::AL).addReg(0)
7653       .addReg(Reg, RegState::Kill)
7654       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7655       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7656       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7657     break;
7658   }
7659   }
7660
7661   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7662                                       ARM::SP)
7663                               .addReg(ARM::SP).addReg(ARM::R4)));
7664
7665   MI->eraseFromParent();
7666   return MBB;
7667 }
7668
7669 MachineBasicBlock *
7670 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7671                                                MachineBasicBlock *BB) const {
7672   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7673   DebugLoc dl = MI->getDebugLoc();
7674   bool isThumb2 = Subtarget->isThumb2();
7675   switch (MI->getOpcode()) {
7676   default: {
7677     MI->dump();
7678     llvm_unreachable("Unexpected instr type to insert");
7679   }
7680   // The Thumb2 pre-indexed stores have the same MI operands, they just
7681   // define them differently in the .td files from the isel patterns, so
7682   // they need pseudos.
7683   case ARM::t2STR_preidx:
7684     MI->setDesc(TII->get(ARM::t2STR_PRE));
7685     return BB;
7686   case ARM::t2STRB_preidx:
7687     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7688     return BB;
7689   case ARM::t2STRH_preidx:
7690     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7691     return BB;
7692
7693   case ARM::STRi_preidx:
7694   case ARM::STRBi_preidx: {
7695     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7696       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7697     // Decode the offset.
7698     unsigned Offset = MI->getOperand(4).getImm();
7699     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7700     Offset = ARM_AM::getAM2Offset(Offset);
7701     if (isSub)
7702       Offset = -Offset;
7703
7704     MachineMemOperand *MMO = *MI->memoperands_begin();
7705     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7706       .addOperand(MI->getOperand(0))  // Rn_wb
7707       .addOperand(MI->getOperand(1))  // Rt
7708       .addOperand(MI->getOperand(2))  // Rn
7709       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7710       .addOperand(MI->getOperand(5))  // pred
7711       .addOperand(MI->getOperand(6))
7712       .addMemOperand(MMO);
7713     MI->eraseFromParent();
7714     return BB;
7715   }
7716   case ARM::STRr_preidx:
7717   case ARM::STRBr_preidx:
7718   case ARM::STRH_preidx: {
7719     unsigned NewOpc;
7720     switch (MI->getOpcode()) {
7721     default: llvm_unreachable("unexpected opcode!");
7722     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7723     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7724     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7725     }
7726     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7727     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7728       MIB.addOperand(MI->getOperand(i));
7729     MI->eraseFromParent();
7730     return BB;
7731   }
7732
7733   case ARM::tMOVCCr_pseudo: {
7734     // To "insert" a SELECT_CC instruction, we actually have to insert the
7735     // diamond control-flow pattern.  The incoming instruction knows the
7736     // destination vreg to set, the condition code register to branch on, the
7737     // true/false values to select between, and a branch opcode to use.
7738     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7739     MachineFunction::iterator It = BB;
7740     ++It;
7741
7742     //  thisMBB:
7743     //  ...
7744     //   TrueVal = ...
7745     //   cmpTY ccX, r1, r2
7746     //   bCC copy1MBB
7747     //   fallthrough --> copy0MBB
7748     MachineBasicBlock *thisMBB  = BB;
7749     MachineFunction *F = BB->getParent();
7750     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7751     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7752     F->insert(It, copy0MBB);
7753     F->insert(It, sinkMBB);
7754
7755     // Transfer the remainder of BB and its successor edges to sinkMBB.
7756     sinkMBB->splice(sinkMBB->begin(), BB,
7757                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7758     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7759
7760     BB->addSuccessor(copy0MBB);
7761     BB->addSuccessor(sinkMBB);
7762
7763     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7764       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7765
7766     //  copy0MBB:
7767     //   %FalseValue = ...
7768     //   # fallthrough to sinkMBB
7769     BB = copy0MBB;
7770
7771     // Update machine-CFG edges
7772     BB->addSuccessor(sinkMBB);
7773
7774     //  sinkMBB:
7775     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7776     //  ...
7777     BB = sinkMBB;
7778     BuildMI(*BB, BB->begin(), dl,
7779             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7780       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7781       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7782
7783     MI->eraseFromParent();   // The pseudo instruction is gone now.
7784     return BB;
7785   }
7786
7787   case ARM::BCCi64:
7788   case ARM::BCCZi64: {
7789     // If there is an unconditional branch to the other successor, remove it.
7790     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7791
7792     // Compare both parts that make up the double comparison separately for
7793     // equality.
7794     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7795
7796     unsigned LHS1 = MI->getOperand(1).getReg();
7797     unsigned LHS2 = MI->getOperand(2).getReg();
7798     if (RHSisZero) {
7799       AddDefaultPred(BuildMI(BB, dl,
7800                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7801                      .addReg(LHS1).addImm(0));
7802       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7803         .addReg(LHS2).addImm(0)
7804         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7805     } else {
7806       unsigned RHS1 = MI->getOperand(3).getReg();
7807       unsigned RHS2 = MI->getOperand(4).getReg();
7808       AddDefaultPred(BuildMI(BB, dl,
7809                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7810                      .addReg(LHS1).addReg(RHS1));
7811       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7812         .addReg(LHS2).addReg(RHS2)
7813         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7814     }
7815
7816     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7817     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7818     if (MI->getOperand(0).getImm() == ARMCC::NE)
7819       std::swap(destMBB, exitMBB);
7820
7821     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7822       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7823     if (isThumb2)
7824       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7825     else
7826       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7827
7828     MI->eraseFromParent();   // The pseudo instruction is gone now.
7829     return BB;
7830   }
7831
7832   case ARM::Int_eh_sjlj_setjmp:
7833   case ARM::Int_eh_sjlj_setjmp_nofp:
7834   case ARM::tInt_eh_sjlj_setjmp:
7835   case ARM::t2Int_eh_sjlj_setjmp:
7836   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7837     return BB;
7838
7839   case ARM::Int_eh_sjlj_setup_dispatch:
7840     EmitSjLjDispatchBlock(MI, BB);
7841     return BB;
7842
7843   case ARM::ABS:
7844   case ARM::t2ABS: {
7845     // To insert an ABS instruction, we have to insert the
7846     // diamond control-flow pattern.  The incoming instruction knows the
7847     // source vreg to test against 0, the destination vreg to set,
7848     // the condition code register to branch on, the
7849     // true/false values to select between, and a branch opcode to use.
7850     // It transforms
7851     //     V1 = ABS V0
7852     // into
7853     //     V2 = MOVS V0
7854     //     BCC                      (branch to SinkBB if V0 >= 0)
7855     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7856     //     SinkBB: V1 = PHI(V2, V3)
7857     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7858     MachineFunction::iterator BBI = BB;
7859     ++BBI;
7860     MachineFunction *Fn = BB->getParent();
7861     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7862     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7863     Fn->insert(BBI, RSBBB);
7864     Fn->insert(BBI, SinkBB);
7865
7866     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7867     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7868     bool ABSSrcKIll = MI->getOperand(1).isKill();
7869     bool isThumb2 = Subtarget->isThumb2();
7870     MachineRegisterInfo &MRI = Fn->getRegInfo();
7871     // In Thumb mode S must not be specified if source register is the SP or
7872     // PC and if destination register is the SP, so restrict register class
7873     unsigned NewRsbDstReg =
7874       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7875
7876     // Transfer the remainder of BB and its successor edges to sinkMBB.
7877     SinkBB->splice(SinkBB->begin(), BB,
7878                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7879     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7880
7881     BB->addSuccessor(RSBBB);
7882     BB->addSuccessor(SinkBB);
7883
7884     // fall through to SinkMBB
7885     RSBBB->addSuccessor(SinkBB);
7886
7887     // insert a cmp at the end of BB
7888     AddDefaultPred(BuildMI(BB, dl,
7889                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7890                    .addReg(ABSSrcReg).addImm(0));
7891
7892     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7893     BuildMI(BB, dl,
7894       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7895       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7896
7897     // insert rsbri in RSBBB
7898     // Note: BCC and rsbri will be converted into predicated rsbmi
7899     // by if-conversion pass
7900     BuildMI(*RSBBB, RSBBB->begin(), dl,
7901       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7902       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7903       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7904
7905     // insert PHI in SinkBB,
7906     // reuse ABSDstReg to not change uses of ABS instruction
7907     BuildMI(*SinkBB, SinkBB->begin(), dl,
7908       TII->get(ARM::PHI), ABSDstReg)
7909       .addReg(NewRsbDstReg).addMBB(RSBBB)
7910       .addReg(ABSSrcReg).addMBB(BB);
7911
7912     // remove ABS instruction
7913     MI->eraseFromParent();
7914
7915     // return last added BB
7916     return SinkBB;
7917   }
7918   case ARM::COPY_STRUCT_BYVAL_I32:
7919     ++NumLoopByVals;
7920     return EmitStructByval(MI, BB);
7921   case ARM::WIN__CHKSTK:
7922     return EmitLowered__chkstk(MI, BB);
7923   }
7924 }
7925
7926 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7927                                                       SDNode *Node) const {
7928   const MCInstrDesc *MCID = &MI->getDesc();
7929   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7930   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7931   // operand is still set to noreg. If needed, set the optional operand's
7932   // register to CPSR, and remove the redundant implicit def.
7933   //
7934   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7935
7936   // Rename pseudo opcodes.
7937   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7938   if (NewOpc) {
7939     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7940     MCID = &TII->get(NewOpc);
7941
7942     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7943            "converted opcode should be the same except for cc_out");
7944
7945     MI->setDesc(*MCID);
7946
7947     // Add the optional cc_out operand
7948     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7949   }
7950   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7951
7952   // Any ARM instruction that sets the 's' bit should specify an optional
7953   // "cc_out" operand in the last operand position.
7954   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7955     assert(!NewOpc && "Optional cc_out operand required");
7956     return;
7957   }
7958   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7959   // since we already have an optional CPSR def.
7960   bool definesCPSR = false;
7961   bool deadCPSR = false;
7962   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7963        i != e; ++i) {
7964     const MachineOperand &MO = MI->getOperand(i);
7965     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7966       definesCPSR = true;
7967       if (MO.isDead())
7968         deadCPSR = true;
7969       MI->RemoveOperand(i);
7970       break;
7971     }
7972   }
7973   if (!definesCPSR) {
7974     assert(!NewOpc && "Optional cc_out operand required");
7975     return;
7976   }
7977   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7978   if (deadCPSR) {
7979     assert(!MI->getOperand(ccOutIdx).getReg() &&
7980            "expect uninitialized optional cc_out operand");
7981     return;
7982   }
7983
7984   // If this instruction was defined with an optional CPSR def and its dag node
7985   // had a live implicit CPSR def, then activate the optional CPSR def.
7986   MachineOperand &MO = MI->getOperand(ccOutIdx);
7987   MO.setReg(ARM::CPSR);
7988   MO.setIsDef(true);
7989 }
7990
7991 //===----------------------------------------------------------------------===//
7992 //                           ARM Optimization Hooks
7993 //===----------------------------------------------------------------------===//
7994
7995 // Helper function that checks if N is a null or all ones constant.
7996 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7997   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7998   if (!C)
7999     return false;
8000   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8001 }
8002
8003 // Return true if N is conditionally 0 or all ones.
8004 // Detects these expressions where cc is an i1 value:
8005 //
8006 //   (select cc 0, y)   [AllOnes=0]
8007 //   (select cc y, 0)   [AllOnes=0]
8008 //   (zext cc)          [AllOnes=0]
8009 //   (sext cc)          [AllOnes=0/1]
8010 //   (select cc -1, y)  [AllOnes=1]
8011 //   (select cc y, -1)  [AllOnes=1]
8012 //
8013 // Invert is set when N is the null/all ones constant when CC is false.
8014 // OtherOp is set to the alternative value of N.
8015 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8016                                        SDValue &CC, bool &Invert,
8017                                        SDValue &OtherOp,
8018                                        SelectionDAG &DAG) {
8019   switch (N->getOpcode()) {
8020   default: return false;
8021   case ISD::SELECT: {
8022     CC = N->getOperand(0);
8023     SDValue N1 = N->getOperand(1);
8024     SDValue N2 = N->getOperand(2);
8025     if (isZeroOrAllOnes(N1, AllOnes)) {
8026       Invert = false;
8027       OtherOp = N2;
8028       return true;
8029     }
8030     if (isZeroOrAllOnes(N2, AllOnes)) {
8031       Invert = true;
8032       OtherOp = N1;
8033       return true;
8034     }
8035     return false;
8036   }
8037   case ISD::ZERO_EXTEND:
8038     // (zext cc) can never be the all ones value.
8039     if (AllOnes)
8040       return false;
8041     // Fall through.
8042   case ISD::SIGN_EXTEND: {
8043     SDLoc dl(N);
8044     EVT VT = N->getValueType(0);
8045     CC = N->getOperand(0);
8046     if (CC.getValueType() != MVT::i1)
8047       return false;
8048     Invert = !AllOnes;
8049     if (AllOnes)
8050       // When looking for an AllOnes constant, N is an sext, and the 'other'
8051       // value is 0.
8052       OtherOp = DAG.getConstant(0, dl, VT);
8053     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8054       // When looking for a 0 constant, N can be zext or sext.
8055       OtherOp = DAG.getConstant(1, dl, VT);
8056     else
8057       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8058                                 VT);
8059     return true;
8060   }
8061   }
8062 }
8063
8064 // Combine a constant select operand into its use:
8065 //
8066 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8067 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8068 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8069 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8070 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8071 //
8072 // The transform is rejected if the select doesn't have a constant operand that
8073 // is null, or all ones when AllOnes is set.
8074 //
8075 // Also recognize sext/zext from i1:
8076 //
8077 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8078 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8079 //
8080 // These transformations eventually create predicated instructions.
8081 //
8082 // @param N       The node to transform.
8083 // @param Slct    The N operand that is a select.
8084 // @param OtherOp The other N operand (x above).
8085 // @param DCI     Context.
8086 // @param AllOnes Require the select constant to be all ones instead of null.
8087 // @returns The new node, or SDValue() on failure.
8088 static
8089 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8090                             TargetLowering::DAGCombinerInfo &DCI,
8091                             bool AllOnes = false) {
8092   SelectionDAG &DAG = DCI.DAG;
8093   EVT VT = N->getValueType(0);
8094   SDValue NonConstantVal;
8095   SDValue CCOp;
8096   bool SwapSelectOps;
8097   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8098                                   NonConstantVal, DAG))
8099     return SDValue();
8100
8101   // Slct is now know to be the desired identity constant when CC is true.
8102   SDValue TrueVal = OtherOp;
8103   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8104                                  OtherOp, NonConstantVal);
8105   // Unless SwapSelectOps says CC should be false.
8106   if (SwapSelectOps)
8107     std::swap(TrueVal, FalseVal);
8108
8109   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8110                      CCOp, TrueVal, FalseVal);
8111 }
8112
8113 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8114 static
8115 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8116                                        TargetLowering::DAGCombinerInfo &DCI) {
8117   SDValue N0 = N->getOperand(0);
8118   SDValue N1 = N->getOperand(1);
8119   if (N0.getNode()->hasOneUse()) {
8120     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8121     if (Result.getNode())
8122       return Result;
8123   }
8124   if (N1.getNode()->hasOneUse()) {
8125     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8126     if (Result.getNode())
8127       return Result;
8128   }
8129   return SDValue();
8130 }
8131
8132 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8133 // (only after legalization).
8134 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8135                                  TargetLowering::DAGCombinerInfo &DCI,
8136                                  const ARMSubtarget *Subtarget) {
8137
8138   // Only perform optimization if after legalize, and if NEON is available. We
8139   // also expected both operands to be BUILD_VECTORs.
8140   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8141       || N0.getOpcode() != ISD::BUILD_VECTOR
8142       || N1.getOpcode() != ISD::BUILD_VECTOR)
8143     return SDValue();
8144
8145   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8146   EVT VT = N->getValueType(0);
8147   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8148     return SDValue();
8149
8150   // Check that the vector operands are of the right form.
8151   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8152   // operands, where N is the size of the formed vector.
8153   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8154   // index such that we have a pair wise add pattern.
8155
8156   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8157   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8158     return SDValue();
8159   SDValue Vec = N0->getOperand(0)->getOperand(0);
8160   SDNode *V = Vec.getNode();
8161   unsigned nextIndex = 0;
8162
8163   // For each operands to the ADD which are BUILD_VECTORs,
8164   // check to see if each of their operands are an EXTRACT_VECTOR with
8165   // the same vector and appropriate index.
8166   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8167     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8168         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8169
8170       SDValue ExtVec0 = N0->getOperand(i);
8171       SDValue ExtVec1 = N1->getOperand(i);
8172
8173       // First operand is the vector, verify its the same.
8174       if (V != ExtVec0->getOperand(0).getNode() ||
8175           V != ExtVec1->getOperand(0).getNode())
8176         return SDValue();
8177
8178       // Second is the constant, verify its correct.
8179       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8180       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8181
8182       // For the constant, we want to see all the even or all the odd.
8183       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8184           || C1->getZExtValue() != nextIndex+1)
8185         return SDValue();
8186
8187       // Increment index.
8188       nextIndex+=2;
8189     } else
8190       return SDValue();
8191   }
8192
8193   // Create VPADDL node.
8194   SelectionDAG &DAG = DCI.DAG;
8195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8196
8197   SDLoc dl(N);
8198
8199   // Build operand list.
8200   SmallVector<SDValue, 8> Ops;
8201   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8202                                 TLI.getPointerTy(DAG.getDataLayout())));
8203
8204   // Input is the vector.
8205   Ops.push_back(Vec);
8206
8207   // Get widened type and narrowed type.
8208   MVT widenType;
8209   unsigned numElem = VT.getVectorNumElements();
8210   
8211   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8212   switch (inputLaneType.getSimpleVT().SimpleTy) {
8213     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8214     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8215     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8216     default:
8217       llvm_unreachable("Invalid vector element type for padd optimization.");
8218   }
8219
8220   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8221   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8222   return DAG.getNode(ExtOp, dl, VT, tmp);
8223 }
8224
8225 static SDValue findMUL_LOHI(SDValue V) {
8226   if (V->getOpcode() == ISD::UMUL_LOHI ||
8227       V->getOpcode() == ISD::SMUL_LOHI)
8228     return V;
8229   return SDValue();
8230 }
8231
8232 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8233                                      TargetLowering::DAGCombinerInfo &DCI,
8234                                      const ARMSubtarget *Subtarget) {
8235
8236   if (Subtarget->isThumb1Only()) return SDValue();
8237
8238   // Only perform the checks after legalize when the pattern is available.
8239   if (DCI.isBeforeLegalize()) return SDValue();
8240
8241   // Look for multiply add opportunities.
8242   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8243   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8244   // a glue link from the first add to the second add.
8245   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8246   // a S/UMLAL instruction.
8247   //                  UMUL_LOHI
8248   //                 / :lo    \ :hi
8249   //                /          \          [no multiline comment]
8250   //    loAdd ->  ADDE         |
8251   //                 \ :glue  /
8252   //                  \      /
8253   //                    ADDC   <- hiAdd
8254   //
8255   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8256   SDValue AddcOp0 = AddcNode->getOperand(0);
8257   SDValue AddcOp1 = AddcNode->getOperand(1);
8258
8259   // Check if the two operands are from the same mul_lohi node.
8260   if (AddcOp0.getNode() == AddcOp1.getNode())
8261     return SDValue();
8262
8263   assert(AddcNode->getNumValues() == 2 &&
8264          AddcNode->getValueType(0) == MVT::i32 &&
8265          "Expect ADDC with two result values. First: i32");
8266
8267   // Check that we have a glued ADDC node.
8268   if (AddcNode->getValueType(1) != MVT::Glue)
8269     return SDValue();
8270
8271   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8272   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8273       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8274       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8275       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8276     return SDValue();
8277
8278   // Look for the glued ADDE.
8279   SDNode* AddeNode = AddcNode->getGluedUser();
8280   if (!AddeNode)
8281     return SDValue();
8282
8283   // Make sure it is really an ADDE.
8284   if (AddeNode->getOpcode() != ISD::ADDE)
8285     return SDValue();
8286
8287   assert(AddeNode->getNumOperands() == 3 &&
8288          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8289          "ADDE node has the wrong inputs");
8290
8291   // Check for the triangle shape.
8292   SDValue AddeOp0 = AddeNode->getOperand(0);
8293   SDValue AddeOp1 = AddeNode->getOperand(1);
8294
8295   // Make sure that the ADDE operands are not coming from the same node.
8296   if (AddeOp0.getNode() == AddeOp1.getNode())
8297     return SDValue();
8298
8299   // Find the MUL_LOHI node walking up ADDE's operands.
8300   bool IsLeftOperandMUL = false;
8301   SDValue MULOp = findMUL_LOHI(AddeOp0);
8302   if (MULOp == SDValue())
8303    MULOp = findMUL_LOHI(AddeOp1);
8304   else
8305     IsLeftOperandMUL = true;
8306   if (MULOp == SDValue())
8307     return SDValue();
8308
8309   // Figure out the right opcode.
8310   unsigned Opc = MULOp->getOpcode();
8311   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8312
8313   // Figure out the high and low input values to the MLAL node.
8314   SDValue* HiAdd = nullptr;
8315   SDValue* LoMul = nullptr;
8316   SDValue* LowAdd = nullptr;
8317
8318   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8319   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8320     return SDValue();
8321
8322   if (IsLeftOperandMUL)
8323     HiAdd = &AddeOp1;
8324   else
8325     HiAdd = &AddeOp0;
8326
8327
8328   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8329   // whose low result is fed to the ADDC we are checking.
8330
8331   if (AddcOp0 == MULOp.getValue(0)) {
8332     LoMul = &AddcOp0;
8333     LowAdd = &AddcOp1;
8334   }
8335   if (AddcOp1 == MULOp.getValue(0)) {
8336     LoMul = &AddcOp1;
8337     LowAdd = &AddcOp0;
8338   }
8339
8340   if (!LoMul)
8341     return SDValue();
8342
8343   // Create the merged node.
8344   SelectionDAG &DAG = DCI.DAG;
8345
8346   // Build operand list.
8347   SmallVector<SDValue, 8> Ops;
8348   Ops.push_back(LoMul->getOperand(0));
8349   Ops.push_back(LoMul->getOperand(1));
8350   Ops.push_back(*LowAdd);
8351   Ops.push_back(*HiAdd);
8352
8353   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8354                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8355
8356   // Replace the ADDs' nodes uses by the MLA node's values.
8357   SDValue HiMLALResult(MLALNode.getNode(), 1);
8358   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8359
8360   SDValue LoMLALResult(MLALNode.getNode(), 0);
8361   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8362
8363   // Return original node to notify the driver to stop replacing.
8364   SDValue resNode(AddcNode, 0);
8365   return resNode;
8366 }
8367
8368 /// PerformADDCCombine - Target-specific dag combine transform from
8369 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8370 static SDValue PerformADDCCombine(SDNode *N,
8371                                  TargetLowering::DAGCombinerInfo &DCI,
8372                                  const ARMSubtarget *Subtarget) {
8373
8374   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8375
8376 }
8377
8378 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8379 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8380 /// called with the default operands, and if that fails, with commuted
8381 /// operands.
8382 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8383                                           TargetLowering::DAGCombinerInfo &DCI,
8384                                           const ARMSubtarget *Subtarget){
8385
8386   // Attempt to create vpaddl for this add.
8387   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8388   if (Result.getNode())
8389     return Result;
8390
8391   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8392   if (N0.getNode()->hasOneUse()) {
8393     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8394     if (Result.getNode()) return Result;
8395   }
8396   return SDValue();
8397 }
8398
8399 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8400 ///
8401 static SDValue PerformADDCombine(SDNode *N,
8402                                  TargetLowering::DAGCombinerInfo &DCI,
8403                                  const ARMSubtarget *Subtarget) {
8404   SDValue N0 = N->getOperand(0);
8405   SDValue N1 = N->getOperand(1);
8406
8407   // First try with the default operand order.
8408   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8409   if (Result.getNode())
8410     return Result;
8411
8412   // If that didn't work, try again with the operands commuted.
8413   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8414 }
8415
8416 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8417 ///
8418 static SDValue PerformSUBCombine(SDNode *N,
8419                                  TargetLowering::DAGCombinerInfo &DCI) {
8420   SDValue N0 = N->getOperand(0);
8421   SDValue N1 = N->getOperand(1);
8422
8423   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8424   if (N1.getNode()->hasOneUse()) {
8425     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8426     if (Result.getNode()) return Result;
8427   }
8428
8429   return SDValue();
8430 }
8431
8432 /// PerformVMULCombine
8433 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8434 /// special multiplier accumulator forwarding.
8435 ///   vmul d3, d0, d2
8436 ///   vmla d3, d1, d2
8437 /// is faster than
8438 ///   vadd d3, d0, d1
8439 ///   vmul d3, d3, d2
8440 //  However, for (A + B) * (A + B),
8441 //    vadd d2, d0, d1
8442 //    vmul d3, d0, d2
8443 //    vmla d3, d1, d2
8444 //  is slower than
8445 //    vadd d2, d0, d1
8446 //    vmul d3, d2, d2
8447 static SDValue PerformVMULCombine(SDNode *N,
8448                                   TargetLowering::DAGCombinerInfo &DCI,
8449                                   const ARMSubtarget *Subtarget) {
8450   if (!Subtarget->hasVMLxForwarding())
8451     return SDValue();
8452
8453   SelectionDAG &DAG = DCI.DAG;
8454   SDValue N0 = N->getOperand(0);
8455   SDValue N1 = N->getOperand(1);
8456   unsigned Opcode = N0.getOpcode();
8457   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8458       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8459     Opcode = N1.getOpcode();
8460     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8461         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8462       return SDValue();
8463     std::swap(N0, N1);
8464   }
8465
8466   if (N0 == N1)
8467     return SDValue();
8468
8469   EVT VT = N->getValueType(0);
8470   SDLoc DL(N);
8471   SDValue N00 = N0->getOperand(0);
8472   SDValue N01 = N0->getOperand(1);
8473   return DAG.getNode(Opcode, DL, VT,
8474                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8475                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8476 }
8477
8478 static SDValue PerformMULCombine(SDNode *N,
8479                                  TargetLowering::DAGCombinerInfo &DCI,
8480                                  const ARMSubtarget *Subtarget) {
8481   SelectionDAG &DAG = DCI.DAG;
8482
8483   if (Subtarget->isThumb1Only())
8484     return SDValue();
8485
8486   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8487     return SDValue();
8488
8489   EVT VT = N->getValueType(0);
8490   if (VT.is64BitVector() || VT.is128BitVector())
8491     return PerformVMULCombine(N, DCI, Subtarget);
8492   if (VT != MVT::i32)
8493     return SDValue();
8494
8495   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8496   if (!C)
8497     return SDValue();
8498
8499   int64_t MulAmt = C->getSExtValue();
8500   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8501
8502   ShiftAmt = ShiftAmt & (32 - 1);
8503   SDValue V = N->getOperand(0);
8504   SDLoc DL(N);
8505
8506   SDValue Res;
8507   MulAmt >>= ShiftAmt;
8508
8509   if (MulAmt >= 0) {
8510     if (isPowerOf2_32(MulAmt - 1)) {
8511       // (mul x, 2^N + 1) => (add (shl x, N), x)
8512       Res = DAG.getNode(ISD::ADD, DL, VT,
8513                         V,
8514                         DAG.getNode(ISD::SHL, DL, VT,
8515                                     V,
8516                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8517                                                     MVT::i32)));
8518     } else if (isPowerOf2_32(MulAmt + 1)) {
8519       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8520       Res = DAG.getNode(ISD::SUB, DL, VT,
8521                         DAG.getNode(ISD::SHL, DL, VT,
8522                                     V,
8523                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8524                                                     MVT::i32)),
8525                         V);
8526     } else
8527       return SDValue();
8528   } else {
8529     uint64_t MulAmtAbs = -MulAmt;
8530     if (isPowerOf2_32(MulAmtAbs + 1)) {
8531       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8532       Res = DAG.getNode(ISD::SUB, DL, VT,
8533                         V,
8534                         DAG.getNode(ISD::SHL, DL, VT,
8535                                     V,
8536                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8537                                                     MVT::i32)));
8538     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8539       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8540       Res = DAG.getNode(ISD::ADD, DL, VT,
8541                         V,
8542                         DAG.getNode(ISD::SHL, DL, VT,
8543                                     V,
8544                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8545                                                     MVT::i32)));
8546       Res = DAG.getNode(ISD::SUB, DL, VT,
8547                         DAG.getConstant(0, DL, MVT::i32), Res);
8548
8549     } else
8550       return SDValue();
8551   }
8552
8553   if (ShiftAmt != 0)
8554     Res = DAG.getNode(ISD::SHL, DL, VT,
8555                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8556
8557   // Do not add new nodes to DAG combiner worklist.
8558   DCI.CombineTo(N, Res, false);
8559   return SDValue();
8560 }
8561
8562 static SDValue PerformANDCombine(SDNode *N,
8563                                  TargetLowering::DAGCombinerInfo &DCI,
8564                                  const ARMSubtarget *Subtarget) {
8565
8566   // Attempt to use immediate-form VBIC
8567   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8568   SDLoc dl(N);
8569   EVT VT = N->getValueType(0);
8570   SelectionDAG &DAG = DCI.DAG;
8571
8572   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8573     return SDValue();
8574
8575   APInt SplatBits, SplatUndef;
8576   unsigned SplatBitSize;
8577   bool HasAnyUndefs;
8578   if (BVN &&
8579       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8580     if (SplatBitSize <= 64) {
8581       EVT VbicVT;
8582       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8583                                       SplatUndef.getZExtValue(), SplatBitSize,
8584                                       DAG, dl, VbicVT, VT.is128BitVector(),
8585                                       OtherModImm);
8586       if (Val.getNode()) {
8587         SDValue Input =
8588           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8589         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8590         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8591       }
8592     }
8593   }
8594
8595   if (!Subtarget->isThumb1Only()) {
8596     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8597     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8598     if (Result.getNode())
8599       return Result;
8600   }
8601
8602   return SDValue();
8603 }
8604
8605 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8606 static SDValue PerformORCombine(SDNode *N,
8607                                 TargetLowering::DAGCombinerInfo &DCI,
8608                                 const ARMSubtarget *Subtarget) {
8609   // Attempt to use immediate-form VORR
8610   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8611   SDLoc dl(N);
8612   EVT VT = N->getValueType(0);
8613   SelectionDAG &DAG = DCI.DAG;
8614
8615   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8616     return SDValue();
8617
8618   APInt SplatBits, SplatUndef;
8619   unsigned SplatBitSize;
8620   bool HasAnyUndefs;
8621   if (BVN && Subtarget->hasNEON() &&
8622       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8623     if (SplatBitSize <= 64) {
8624       EVT VorrVT;
8625       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8626                                       SplatUndef.getZExtValue(), SplatBitSize,
8627                                       DAG, dl, VorrVT, VT.is128BitVector(),
8628                                       OtherModImm);
8629       if (Val.getNode()) {
8630         SDValue Input =
8631           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8632         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8633         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8634       }
8635     }
8636   }
8637
8638   if (!Subtarget->isThumb1Only()) {
8639     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8640     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8641     if (Result.getNode())
8642       return Result;
8643   }
8644
8645   // The code below optimizes (or (and X, Y), Z).
8646   // The AND operand needs to have a single user to make these optimizations
8647   // profitable.
8648   SDValue N0 = N->getOperand(0);
8649   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8650     return SDValue();
8651   SDValue N1 = N->getOperand(1);
8652
8653   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8654   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8655       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8656     APInt SplatUndef;
8657     unsigned SplatBitSize;
8658     bool HasAnyUndefs;
8659
8660     APInt SplatBits0, SplatBits1;
8661     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8662     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8663     // Ensure that the second operand of both ands are constants
8664     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8665                                       HasAnyUndefs) && !HasAnyUndefs) {
8666         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8667                                           HasAnyUndefs) && !HasAnyUndefs) {
8668             // Ensure that the bit width of the constants are the same and that
8669             // the splat arguments are logical inverses as per the pattern we
8670             // are trying to simplify.
8671             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8672                 SplatBits0 == ~SplatBits1) {
8673                 // Canonicalize the vector type to make instruction selection
8674                 // simpler.
8675                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8676                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8677                                              N0->getOperand(1),
8678                                              N0->getOperand(0),
8679                                              N1->getOperand(0));
8680                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8681             }
8682         }
8683     }
8684   }
8685
8686   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8687   // reasonable.
8688
8689   // BFI is only available on V6T2+
8690   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8691     return SDValue();
8692
8693   SDLoc DL(N);
8694   // 1) or (and A, mask), val => ARMbfi A, val, mask
8695   //      iff (val & mask) == val
8696   //
8697   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8698   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8699   //          && mask == ~mask2
8700   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8701   //          && ~mask == mask2
8702   //  (i.e., copy a bitfield value into another bitfield of the same width)
8703
8704   if (VT != MVT::i32)
8705     return SDValue();
8706
8707   SDValue N00 = N0.getOperand(0);
8708
8709   // The value and the mask need to be constants so we can verify this is
8710   // actually a bitfield set. If the mask is 0xffff, we can do better
8711   // via a movt instruction, so don't use BFI in that case.
8712   SDValue MaskOp = N0.getOperand(1);
8713   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8714   if (!MaskC)
8715     return SDValue();
8716   unsigned Mask = MaskC->getZExtValue();
8717   if (Mask == 0xffff)
8718     return SDValue();
8719   SDValue Res;
8720   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8721   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8722   if (N1C) {
8723     unsigned Val = N1C->getZExtValue();
8724     if ((Val & ~Mask) != Val)
8725       return SDValue();
8726
8727     if (ARM::isBitFieldInvertedMask(Mask)) {
8728       Val >>= countTrailingZeros(~Mask);
8729
8730       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8731                         DAG.getConstant(Val, DL, MVT::i32),
8732                         DAG.getConstant(Mask, DL, MVT::i32));
8733
8734       // Do not add new nodes to DAG combiner worklist.
8735       DCI.CombineTo(N, Res, false);
8736       return SDValue();
8737     }
8738   } else if (N1.getOpcode() == ISD::AND) {
8739     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8740     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8741     if (!N11C)
8742       return SDValue();
8743     unsigned Mask2 = N11C->getZExtValue();
8744
8745     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8746     // as is to match.
8747     if (ARM::isBitFieldInvertedMask(Mask) &&
8748         (Mask == ~Mask2)) {
8749       // The pack halfword instruction works better for masks that fit it,
8750       // so use that when it's available.
8751       if (Subtarget->hasT2ExtractPack() &&
8752           (Mask == 0xffff || Mask == 0xffff0000))
8753         return SDValue();
8754       // 2a
8755       unsigned amt = countTrailingZeros(Mask2);
8756       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8757                         DAG.getConstant(amt, DL, MVT::i32));
8758       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8759                         DAG.getConstant(Mask, DL, MVT::i32));
8760       // Do not add new nodes to DAG combiner worklist.
8761       DCI.CombineTo(N, Res, false);
8762       return SDValue();
8763     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8764                (~Mask == Mask2)) {
8765       // The pack halfword instruction works better for masks that fit it,
8766       // so use that when it's available.
8767       if (Subtarget->hasT2ExtractPack() &&
8768           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8769         return SDValue();
8770       // 2b
8771       unsigned lsb = countTrailingZeros(Mask);
8772       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8773                         DAG.getConstant(lsb, DL, MVT::i32));
8774       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8775                         DAG.getConstant(Mask2, DL, MVT::i32));
8776       // Do not add new nodes to DAG combiner worklist.
8777       DCI.CombineTo(N, Res, false);
8778       return SDValue();
8779     }
8780   }
8781
8782   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8783       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8784       ARM::isBitFieldInvertedMask(~Mask)) {
8785     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8786     // where lsb(mask) == #shamt and masked bits of B are known zero.
8787     SDValue ShAmt = N00.getOperand(1);
8788     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8789     unsigned LSB = countTrailingZeros(Mask);
8790     if (ShAmtC != LSB)
8791       return SDValue();
8792
8793     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8794                       DAG.getConstant(~Mask, DL, MVT::i32));
8795
8796     // Do not add new nodes to DAG combiner worklist.
8797     DCI.CombineTo(N, Res, false);
8798   }
8799
8800   return SDValue();
8801 }
8802
8803 static SDValue PerformXORCombine(SDNode *N,
8804                                  TargetLowering::DAGCombinerInfo &DCI,
8805                                  const ARMSubtarget *Subtarget) {
8806   EVT VT = N->getValueType(0);
8807   SelectionDAG &DAG = DCI.DAG;
8808
8809   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8810     return SDValue();
8811
8812   if (!Subtarget->isThumb1Only()) {
8813     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8814     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8815     if (Result.getNode())
8816       return Result;
8817   }
8818
8819   return SDValue();
8820 }
8821
8822 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8823 /// the bits being cleared by the AND are not demanded by the BFI.
8824 static SDValue PerformBFICombine(SDNode *N,
8825                                  TargetLowering::DAGCombinerInfo &DCI) {
8826   SDValue N1 = N->getOperand(1);
8827   if (N1.getOpcode() == ISD::AND) {
8828     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8829     if (!N11C)
8830       return SDValue();
8831     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8832     unsigned LSB = countTrailingZeros(~InvMask);
8833     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8834     assert(Width <
8835                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8836            "undefined behavior");
8837     unsigned Mask = (1u << Width) - 1;
8838     unsigned Mask2 = N11C->getZExtValue();
8839     if ((Mask & (~Mask2)) == 0)
8840       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8841                              N->getOperand(0), N1.getOperand(0),
8842                              N->getOperand(2));
8843   }
8844   return SDValue();
8845 }
8846
8847 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8848 /// ARMISD::VMOVRRD.
8849 static SDValue PerformVMOVRRDCombine(SDNode *N,
8850                                      TargetLowering::DAGCombinerInfo &DCI,
8851                                      const ARMSubtarget *Subtarget) {
8852   // vmovrrd(vmovdrr x, y) -> x,y
8853   SDValue InDouble = N->getOperand(0);
8854   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8855     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8856
8857   // vmovrrd(load f64) -> (load i32), (load i32)
8858   SDNode *InNode = InDouble.getNode();
8859   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8860       InNode->getValueType(0) == MVT::f64 &&
8861       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8862       !cast<LoadSDNode>(InNode)->isVolatile()) {
8863     // TODO: Should this be done for non-FrameIndex operands?
8864     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8865
8866     SelectionDAG &DAG = DCI.DAG;
8867     SDLoc DL(LD);
8868     SDValue BasePtr = LD->getBasePtr();
8869     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8870                                  LD->getPointerInfo(), LD->isVolatile(),
8871                                  LD->isNonTemporal(), LD->isInvariant(),
8872                                  LD->getAlignment());
8873
8874     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8875                                     DAG.getConstant(4, DL, MVT::i32));
8876     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8877                                  LD->getPointerInfo(), LD->isVolatile(),
8878                                  LD->isNonTemporal(), LD->isInvariant(),
8879                                  std::min(4U, LD->getAlignment() / 2));
8880
8881     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8882     if (DCI.DAG.getDataLayout().isBigEndian())
8883       std::swap (NewLD1, NewLD2);
8884     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8885     return Result;
8886   }
8887
8888   return SDValue();
8889 }
8890
8891 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8892 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8893 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8894   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8895   SDValue Op0 = N->getOperand(0);
8896   SDValue Op1 = N->getOperand(1);
8897   if (Op0.getOpcode() == ISD::BITCAST)
8898     Op0 = Op0.getOperand(0);
8899   if (Op1.getOpcode() == ISD::BITCAST)
8900     Op1 = Op1.getOperand(0);
8901   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8902       Op0.getNode() == Op1.getNode() &&
8903       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8904     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8905                        N->getValueType(0), Op0.getOperand(0));
8906   return SDValue();
8907 }
8908
8909 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8910 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8911 /// i64 vector to have f64 elements, since the value can then be loaded
8912 /// directly into a VFP register.
8913 static bool hasNormalLoadOperand(SDNode *N) {
8914   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8915   for (unsigned i = 0; i < NumElts; ++i) {
8916     SDNode *Elt = N->getOperand(i).getNode();
8917     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8918       return true;
8919   }
8920   return false;
8921 }
8922
8923 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8924 /// ISD::BUILD_VECTOR.
8925 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8926                                           TargetLowering::DAGCombinerInfo &DCI,
8927                                           const ARMSubtarget *Subtarget) {
8928   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8929   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8930   // into a pair of GPRs, which is fine when the value is used as a scalar,
8931   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8932   SelectionDAG &DAG = DCI.DAG;
8933   if (N->getNumOperands() == 2) {
8934     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8935     if (RV.getNode())
8936       return RV;
8937   }
8938
8939   // Load i64 elements as f64 values so that type legalization does not split
8940   // them up into i32 values.
8941   EVT VT = N->getValueType(0);
8942   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8943     return SDValue();
8944   SDLoc dl(N);
8945   SmallVector<SDValue, 8> Ops;
8946   unsigned NumElts = VT.getVectorNumElements();
8947   for (unsigned i = 0; i < NumElts; ++i) {
8948     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8949     Ops.push_back(V);
8950     // Make the DAGCombiner fold the bitcast.
8951     DCI.AddToWorklist(V.getNode());
8952   }
8953   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8954   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8955   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8956 }
8957
8958 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8959 static SDValue
8960 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8961   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8962   // At that time, we may have inserted bitcasts from integer to float.
8963   // If these bitcasts have survived DAGCombine, change the lowering of this
8964   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8965   // force to use floating point types.
8966
8967   // Make sure we can change the type of the vector.
8968   // This is possible iff:
8969   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8970   //    1.1. Vector is used only once.
8971   //    1.2. Use is a bit convert to an integer type.
8972   // 2. The size of its operands are 32-bits (64-bits are not legal).
8973   EVT VT = N->getValueType(0);
8974   EVT EltVT = VT.getVectorElementType();
8975
8976   // Check 1.1. and 2.
8977   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8978     return SDValue();
8979
8980   // By construction, the input type must be float.
8981   assert(EltVT == MVT::f32 && "Unexpected type!");
8982
8983   // Check 1.2.
8984   SDNode *Use = *N->use_begin();
8985   if (Use->getOpcode() != ISD::BITCAST ||
8986       Use->getValueType(0).isFloatingPoint())
8987     return SDValue();
8988
8989   // Check profitability.
8990   // Model is, if more than half of the relevant operands are bitcast from
8991   // i32, turn the build_vector into a sequence of insert_vector_elt.
8992   // Relevant operands are everything that is not statically
8993   // (i.e., at compile time) bitcasted.
8994   unsigned NumOfBitCastedElts = 0;
8995   unsigned NumElts = VT.getVectorNumElements();
8996   unsigned NumOfRelevantElts = NumElts;
8997   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8998     SDValue Elt = N->getOperand(Idx);
8999     if (Elt->getOpcode() == ISD::BITCAST) {
9000       // Assume only bit cast to i32 will go away.
9001       if (Elt->getOperand(0).getValueType() == MVT::i32)
9002         ++NumOfBitCastedElts;
9003     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9004       // Constants are statically casted, thus do not count them as
9005       // relevant operands.
9006       --NumOfRelevantElts;
9007   }
9008
9009   // Check if more than half of the elements require a non-free bitcast.
9010   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9011     return SDValue();
9012
9013   SelectionDAG &DAG = DCI.DAG;
9014   // Create the new vector type.
9015   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9016   // Check if the type is legal.
9017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9018   if (!TLI.isTypeLegal(VecVT))
9019     return SDValue();
9020
9021   // Combine:
9022   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9023   // => BITCAST INSERT_VECTOR_ELT
9024   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9025   //                      (BITCAST EN), N.
9026   SDValue Vec = DAG.getUNDEF(VecVT);
9027   SDLoc dl(N);
9028   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9029     SDValue V = N->getOperand(Idx);
9030     if (V.getOpcode() == ISD::UNDEF)
9031       continue;
9032     if (V.getOpcode() == ISD::BITCAST &&
9033         V->getOperand(0).getValueType() == MVT::i32)
9034       // Fold obvious case.
9035       V = V.getOperand(0);
9036     else {
9037       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9038       // Make the DAGCombiner fold the bitcasts.
9039       DCI.AddToWorklist(V.getNode());
9040     }
9041     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9042     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9043   }
9044   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9045   // Make the DAGCombiner fold the bitcasts.
9046   DCI.AddToWorklist(Vec.getNode());
9047   return Vec;
9048 }
9049
9050 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9051 /// ISD::INSERT_VECTOR_ELT.
9052 static SDValue PerformInsertEltCombine(SDNode *N,
9053                                        TargetLowering::DAGCombinerInfo &DCI) {
9054   // Bitcast an i64 load inserted into a vector to f64.
9055   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9056   EVT VT = N->getValueType(0);
9057   SDNode *Elt = N->getOperand(1).getNode();
9058   if (VT.getVectorElementType() != MVT::i64 ||
9059       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9060     return SDValue();
9061
9062   SelectionDAG &DAG = DCI.DAG;
9063   SDLoc dl(N);
9064   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9065                                  VT.getVectorNumElements());
9066   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9067   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9068   // Make the DAGCombiner fold the bitcasts.
9069   DCI.AddToWorklist(Vec.getNode());
9070   DCI.AddToWorklist(V.getNode());
9071   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9072                                Vec, V, N->getOperand(2));
9073   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9074 }
9075
9076 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9077 /// ISD::VECTOR_SHUFFLE.
9078 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9079   // The LLVM shufflevector instruction does not require the shuffle mask
9080   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9081   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9082   // operands do not match the mask length, they are extended by concatenating
9083   // them with undef vectors.  That is probably the right thing for other
9084   // targets, but for NEON it is better to concatenate two double-register
9085   // size vector operands into a single quad-register size vector.  Do that
9086   // transformation here:
9087   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9088   //   shuffle(concat(v1, v2), undef)
9089   SDValue Op0 = N->getOperand(0);
9090   SDValue Op1 = N->getOperand(1);
9091   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9092       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9093       Op0.getNumOperands() != 2 ||
9094       Op1.getNumOperands() != 2)
9095     return SDValue();
9096   SDValue Concat0Op1 = Op0.getOperand(1);
9097   SDValue Concat1Op1 = Op1.getOperand(1);
9098   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9099       Concat1Op1.getOpcode() != ISD::UNDEF)
9100     return SDValue();
9101   // Skip the transformation if any of the types are illegal.
9102   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9103   EVT VT = N->getValueType(0);
9104   if (!TLI.isTypeLegal(VT) ||
9105       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9106       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9107     return SDValue();
9108
9109   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9110                                   Op0.getOperand(0), Op1.getOperand(0));
9111   // Translate the shuffle mask.
9112   SmallVector<int, 16> NewMask;
9113   unsigned NumElts = VT.getVectorNumElements();
9114   unsigned HalfElts = NumElts/2;
9115   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9116   for (unsigned n = 0; n < NumElts; ++n) {
9117     int MaskElt = SVN->getMaskElt(n);
9118     int NewElt = -1;
9119     if (MaskElt < (int)HalfElts)
9120       NewElt = MaskElt;
9121     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9122       NewElt = HalfElts + MaskElt - NumElts;
9123     NewMask.push_back(NewElt);
9124   }
9125   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9126                               DAG.getUNDEF(VT), NewMask.data());
9127 }
9128
9129 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9130 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9131 /// base address updates.
9132 /// For generic load/stores, the memory type is assumed to be a vector.
9133 /// The caller is assumed to have checked legality.
9134 static SDValue CombineBaseUpdate(SDNode *N,
9135                                  TargetLowering::DAGCombinerInfo &DCI) {
9136   SelectionDAG &DAG = DCI.DAG;
9137   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9138                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9139   const bool isStore = N->getOpcode() == ISD::STORE;
9140   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9141   SDValue Addr = N->getOperand(AddrOpIdx);
9142   MemSDNode *MemN = cast<MemSDNode>(N);
9143   SDLoc dl(N);
9144
9145   // Search for a use of the address operand that is an increment.
9146   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9147          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9148     SDNode *User = *UI;
9149     if (User->getOpcode() != ISD::ADD ||
9150         UI.getUse().getResNo() != Addr.getResNo())
9151       continue;
9152
9153     // Check that the add is independent of the load/store.  Otherwise, folding
9154     // it would create a cycle.
9155     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9156       continue;
9157
9158     // Find the new opcode for the updating load/store.
9159     bool isLoadOp = true;
9160     bool isLaneOp = false;
9161     unsigned NewOpc = 0;
9162     unsigned NumVecs = 0;
9163     if (isIntrinsic) {
9164       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9165       switch (IntNo) {
9166       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9167       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9168         NumVecs = 1; break;
9169       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9170         NumVecs = 2; break;
9171       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9172         NumVecs = 3; break;
9173       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9174         NumVecs = 4; break;
9175       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9176         NumVecs = 2; isLaneOp = true; break;
9177       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9178         NumVecs = 3; isLaneOp = true; break;
9179       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9180         NumVecs = 4; isLaneOp = true; break;
9181       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9182         NumVecs = 1; isLoadOp = false; break;
9183       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9184         NumVecs = 2; isLoadOp = false; break;
9185       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9186         NumVecs = 3; isLoadOp = false; break;
9187       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9188         NumVecs = 4; isLoadOp = false; break;
9189       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9190         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9191       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9192         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9193       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9194         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9195       }
9196     } else {
9197       isLaneOp = true;
9198       switch (N->getOpcode()) {
9199       default: llvm_unreachable("unexpected opcode for Neon base update");
9200       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9201       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9202       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9203       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9204         NumVecs = 1; isLaneOp = false; break;
9205       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9206         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9207       }
9208     }
9209
9210     // Find the size of memory referenced by the load/store.
9211     EVT VecTy;
9212     if (isLoadOp) {
9213       VecTy = N->getValueType(0);
9214     } else if (isIntrinsic) {
9215       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9216     } else {
9217       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9218       VecTy = N->getOperand(1).getValueType();
9219     }
9220
9221     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9222     if (isLaneOp)
9223       NumBytes /= VecTy.getVectorNumElements();
9224
9225     // If the increment is a constant, it must match the memory ref size.
9226     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9227     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9228       uint64_t IncVal = CInc->getZExtValue();
9229       if (IncVal != NumBytes)
9230         continue;
9231     } else if (NumBytes >= 3 * 16) {
9232       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9233       // separate instructions that make it harder to use a non-constant update.
9234       continue;
9235     }
9236
9237     // OK, we found an ADD we can fold into the base update.
9238     // Now, create a _UPD node, taking care of not breaking alignment.
9239
9240     EVT AlignedVecTy = VecTy;
9241     unsigned Alignment = MemN->getAlignment();
9242
9243     // If this is a less-than-standard-aligned load/store, change the type to
9244     // match the standard alignment.
9245     // The alignment is overlooked when selecting _UPD variants; and it's
9246     // easier to introduce bitcasts here than fix that.
9247     // There are 3 ways to get to this base-update combine:
9248     // - intrinsics: they are assumed to be properly aligned (to the standard
9249     //   alignment of the memory type), so we don't need to do anything.
9250     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9251     //   intrinsics, so, likewise, there's nothing to do.
9252     // - generic load/store instructions: the alignment is specified as an
9253     //   explicit operand, rather than implicitly as the standard alignment
9254     //   of the memory type (like the intrisics).  We need to change the
9255     //   memory type to match the explicit alignment.  That way, we don't
9256     //   generate non-standard-aligned ARMISD::VLDx nodes.
9257     if (isa<LSBaseSDNode>(N)) {
9258       if (Alignment == 0)
9259         Alignment = 1;
9260       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9261         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9262         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9263         assert(!isLaneOp && "Unexpected generic load/store lane.");
9264         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9265         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9266       }
9267       // Don't set an explicit alignment on regular load/stores that we want
9268       // to transform to VLD/VST 1_UPD nodes.
9269       // This matches the behavior of regular load/stores, which only get an
9270       // explicit alignment if the MMO alignment is larger than the standard
9271       // alignment of the memory type.
9272       // Intrinsics, however, always get an explicit alignment, set to the
9273       // alignment of the MMO.
9274       Alignment = 1;
9275     }
9276
9277     // Create the new updating load/store node.
9278     // First, create an SDVTList for the new updating node's results.
9279     EVT Tys[6];
9280     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9281     unsigned n;
9282     for (n = 0; n < NumResultVecs; ++n)
9283       Tys[n] = AlignedVecTy;
9284     Tys[n++] = MVT::i32;
9285     Tys[n] = MVT::Other;
9286     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9287
9288     // Then, gather the new node's operands.
9289     SmallVector<SDValue, 8> Ops;
9290     Ops.push_back(N->getOperand(0)); // incoming chain
9291     Ops.push_back(N->getOperand(AddrOpIdx));
9292     Ops.push_back(Inc);
9293
9294     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9295       // Try to match the intrinsic's signature
9296       Ops.push_back(StN->getValue());
9297     } else {
9298       // Loads (and of course intrinsics) match the intrinsics' signature,
9299       // so just add all but the alignment operand.
9300       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9301         Ops.push_back(N->getOperand(i));
9302     }
9303
9304     // For all node types, the alignment operand is always the last one.
9305     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9306
9307     // If this is a non-standard-aligned STORE, the penultimate operand is the
9308     // stored value.  Bitcast it to the aligned type.
9309     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9310       SDValue &StVal = Ops[Ops.size()-2];
9311       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9312     }
9313
9314     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9315                                            Ops, AlignedVecTy,
9316                                            MemN->getMemOperand());
9317
9318     // Update the uses.
9319     SmallVector<SDValue, 5> NewResults;
9320     for (unsigned i = 0; i < NumResultVecs; ++i)
9321       NewResults.push_back(SDValue(UpdN.getNode(), i));
9322
9323     // If this is an non-standard-aligned LOAD, the first result is the loaded
9324     // value.  Bitcast it to the expected result type.
9325     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9326       SDValue &LdVal = NewResults[0];
9327       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9328     }
9329
9330     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9331     DCI.CombineTo(N, NewResults);
9332     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9333
9334     break;
9335   }
9336   return SDValue();
9337 }
9338
9339 static SDValue PerformVLDCombine(SDNode *N,
9340                                  TargetLowering::DAGCombinerInfo &DCI) {
9341   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9342     return SDValue();
9343
9344   return CombineBaseUpdate(N, DCI);
9345 }
9346
9347 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9348 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9349 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9350 /// return true.
9351 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9352   SelectionDAG &DAG = DCI.DAG;
9353   EVT VT = N->getValueType(0);
9354   // vldN-dup instructions only support 64-bit vectors for N > 1.
9355   if (!VT.is64BitVector())
9356     return false;
9357
9358   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9359   SDNode *VLD = N->getOperand(0).getNode();
9360   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9361     return false;
9362   unsigned NumVecs = 0;
9363   unsigned NewOpc = 0;
9364   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9365   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9366     NumVecs = 2;
9367     NewOpc = ARMISD::VLD2DUP;
9368   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9369     NumVecs = 3;
9370     NewOpc = ARMISD::VLD3DUP;
9371   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9372     NumVecs = 4;
9373     NewOpc = ARMISD::VLD4DUP;
9374   } else {
9375     return false;
9376   }
9377
9378   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9379   // numbers match the load.
9380   unsigned VLDLaneNo =
9381     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9382   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9383        UI != UE; ++UI) {
9384     // Ignore uses of the chain result.
9385     if (UI.getUse().getResNo() == NumVecs)
9386       continue;
9387     SDNode *User = *UI;
9388     if (User->getOpcode() != ARMISD::VDUPLANE ||
9389         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9390       return false;
9391   }
9392
9393   // Create the vldN-dup node.
9394   EVT Tys[5];
9395   unsigned n;
9396   for (n = 0; n < NumVecs; ++n)
9397     Tys[n] = VT;
9398   Tys[n] = MVT::Other;
9399   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9400   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9401   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9402   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9403                                            Ops, VLDMemInt->getMemoryVT(),
9404                                            VLDMemInt->getMemOperand());
9405
9406   // Update the uses.
9407   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9408        UI != UE; ++UI) {
9409     unsigned ResNo = UI.getUse().getResNo();
9410     // Ignore uses of the chain result.
9411     if (ResNo == NumVecs)
9412       continue;
9413     SDNode *User = *UI;
9414     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9415   }
9416
9417   // Now the vldN-lane intrinsic is dead except for its chain result.
9418   // Update uses of the chain.
9419   std::vector<SDValue> VLDDupResults;
9420   for (unsigned n = 0; n < NumVecs; ++n)
9421     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9422   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9423   DCI.CombineTo(VLD, VLDDupResults);
9424
9425   return true;
9426 }
9427
9428 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9429 /// ARMISD::VDUPLANE.
9430 static SDValue PerformVDUPLANECombine(SDNode *N,
9431                                       TargetLowering::DAGCombinerInfo &DCI) {
9432   SDValue Op = N->getOperand(0);
9433
9434   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9435   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9436   if (CombineVLDDUP(N, DCI))
9437     return SDValue(N, 0);
9438
9439   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9440   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9441   while (Op.getOpcode() == ISD::BITCAST)
9442     Op = Op.getOperand(0);
9443   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9444     return SDValue();
9445
9446   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9447   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9448   // The canonical VMOV for a zero vector uses a 32-bit element size.
9449   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9450   unsigned EltBits;
9451   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9452     EltSize = 8;
9453   EVT VT = N->getValueType(0);
9454   if (EltSize > VT.getVectorElementType().getSizeInBits())
9455     return SDValue();
9456
9457   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9458 }
9459
9460 static SDValue PerformLOADCombine(SDNode *N,
9461                                   TargetLowering::DAGCombinerInfo &DCI) {
9462   EVT VT = N->getValueType(0);
9463
9464   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9465   if (ISD::isNormalLoad(N) && VT.isVector() &&
9466       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9467     return CombineBaseUpdate(N, DCI);
9468
9469   return SDValue();
9470 }
9471
9472 /// PerformSTORECombine - Target-specific dag combine xforms for
9473 /// ISD::STORE.
9474 static SDValue PerformSTORECombine(SDNode *N,
9475                                    TargetLowering::DAGCombinerInfo &DCI) {
9476   StoreSDNode *St = cast<StoreSDNode>(N);
9477   if (St->isVolatile())
9478     return SDValue();
9479
9480   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9481   // pack all of the elements in one place.  Next, store to memory in fewer
9482   // chunks.
9483   SDValue StVal = St->getValue();
9484   EVT VT = StVal.getValueType();
9485   if (St->isTruncatingStore() && VT.isVector()) {
9486     SelectionDAG &DAG = DCI.DAG;
9487     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9488     EVT StVT = St->getMemoryVT();
9489     unsigned NumElems = VT.getVectorNumElements();
9490     assert(StVT != VT && "Cannot truncate to the same type");
9491     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9492     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9493
9494     // From, To sizes and ElemCount must be pow of two
9495     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9496
9497     // We are going to use the original vector elt for storing.
9498     // Accumulated smaller vector elements must be a multiple of the store size.
9499     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9500
9501     unsigned SizeRatio  = FromEltSz / ToEltSz;
9502     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9503
9504     // Create a type on which we perform the shuffle.
9505     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9506                                      NumElems*SizeRatio);
9507     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9508
9509     SDLoc DL(St);
9510     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9511     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9512     for (unsigned i = 0; i < NumElems; ++i)
9513       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9514                           ? (i + 1) * SizeRatio - 1
9515                           : i * SizeRatio;
9516
9517     // Can't shuffle using an illegal type.
9518     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9519
9520     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9521                                 DAG.getUNDEF(WideVec.getValueType()),
9522                                 ShuffleVec.data());
9523     // At this point all of the data is stored at the bottom of the
9524     // register. We now need to save it to mem.
9525
9526     // Find the largest store unit
9527     MVT StoreType = MVT::i8;
9528     for (MVT Tp : MVT::integer_valuetypes()) {
9529       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9530         StoreType = Tp;
9531     }
9532     // Didn't find a legal store type.
9533     if (!TLI.isTypeLegal(StoreType))
9534       return SDValue();
9535
9536     // Bitcast the original vector into a vector of store-size units
9537     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9538             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9539     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9540     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9541     SmallVector<SDValue, 8> Chains;
9542     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9543                                         TLI.getPointerTy(DAG.getDataLayout()));
9544     SDValue BasePtr = St->getBasePtr();
9545
9546     // Perform one or more big stores into memory.
9547     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9548     for (unsigned I = 0; I < E; I++) {
9549       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9550                                    StoreType, ShuffWide,
9551                                    DAG.getIntPtrConstant(I, DL));
9552       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9553                                 St->getPointerInfo(), St->isVolatile(),
9554                                 St->isNonTemporal(), St->getAlignment());
9555       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9556                             Increment);
9557       Chains.push_back(Ch);
9558     }
9559     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9560   }
9561
9562   if (!ISD::isNormalStore(St))
9563     return SDValue();
9564
9565   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9566   // ARM stores of arguments in the same cache line.
9567   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9568       StVal.getNode()->hasOneUse()) {
9569     SelectionDAG  &DAG = DCI.DAG;
9570     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9571     SDLoc DL(St);
9572     SDValue BasePtr = St->getBasePtr();
9573     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9574                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9575                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9576                                   St->isNonTemporal(), St->getAlignment());
9577
9578     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9579                                     DAG.getConstant(4, DL, MVT::i32));
9580     return DAG.getStore(NewST1.getValue(0), DL,
9581                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9582                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9583                         St->isNonTemporal(),
9584                         std::min(4U, St->getAlignment() / 2));
9585   }
9586
9587   if (StVal.getValueType() == MVT::i64 &&
9588       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9589
9590     // Bitcast an i64 store extracted from a vector to f64.
9591     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9592     SelectionDAG &DAG = DCI.DAG;
9593     SDLoc dl(StVal);
9594     SDValue IntVec = StVal.getOperand(0);
9595     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9596                                    IntVec.getValueType().getVectorNumElements());
9597     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9598     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9599                                  Vec, StVal.getOperand(1));
9600     dl = SDLoc(N);
9601     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9602     // Make the DAGCombiner fold the bitcasts.
9603     DCI.AddToWorklist(Vec.getNode());
9604     DCI.AddToWorklist(ExtElt.getNode());
9605     DCI.AddToWorklist(V.getNode());
9606     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9607                         St->getPointerInfo(), St->isVolatile(),
9608                         St->isNonTemporal(), St->getAlignment(),
9609                         St->getAAInfo());
9610   }
9611
9612   // If this is a legal vector store, try to combine it into a VST1_UPD.
9613   if (ISD::isNormalStore(N) && VT.isVector() &&
9614       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9615     return CombineBaseUpdate(N, DCI);
9616
9617   return SDValue();
9618 }
9619
9620 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9621 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9622 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9623 {
9624   integerPart cN;
9625   integerPart c0 = 0;
9626   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9627        I != E; I++) {
9628     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9629     if (!C)
9630       return false;
9631
9632     bool isExact;
9633     APFloat APF = C->getValueAPF();
9634     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9635         != APFloat::opOK || !isExact)
9636       return false;
9637
9638     c0 = (I == 0) ? cN : c0;
9639     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9640       return false;
9641   }
9642   C = c0;
9643   return true;
9644 }
9645
9646 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9647 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9648 /// when the VMUL has a constant operand that is a power of 2.
9649 ///
9650 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9651 ///  vmul.f32        d16, d17, d16
9652 ///  vcvt.s32.f32    d16, d16
9653 /// becomes:
9654 ///  vcvt.s32.f32    d16, d16, #3
9655 static SDValue PerformVCVTCombine(SDNode *N,
9656                                   TargetLowering::DAGCombinerInfo &DCI,
9657                                   const ARMSubtarget *Subtarget) {
9658   SelectionDAG &DAG = DCI.DAG;
9659   SDValue Op = N->getOperand(0);
9660
9661   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9662       Op.getOpcode() != ISD::FMUL)
9663     return SDValue();
9664
9665   uint64_t C;
9666   SDValue N0 = Op->getOperand(0);
9667   SDValue ConstVec = Op->getOperand(1);
9668   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9669
9670   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9671       !isConstVecPow2(ConstVec, isSigned, C))
9672     return SDValue();
9673
9674   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9675   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9676   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9677   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9678       NumLanes > 4) {
9679     // These instructions only exist converting from f32 to i32. We can handle
9680     // smaller integers by generating an extra truncate, but larger ones would
9681     // be lossy. We also can't handle more then 4 lanes, since these intructions
9682     // only support v2i32/v4i32 types.
9683     return SDValue();
9684   }
9685
9686   SDLoc dl(N);
9687   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9688     Intrinsic::arm_neon_vcvtfp2fxu;
9689   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9690                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9691                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9692                                  N0,
9693                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9694
9695   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9696     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9697
9698   return FixConv;
9699 }
9700
9701 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9702 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9703 /// when the VDIV has a constant operand that is a power of 2.
9704 ///
9705 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9706 ///  vcvt.f32.s32    d16, d16
9707 ///  vdiv.f32        d16, d17, d16
9708 /// becomes:
9709 ///  vcvt.f32.s32    d16, d16, #3
9710 static SDValue PerformVDIVCombine(SDNode *N,
9711                                   TargetLowering::DAGCombinerInfo &DCI,
9712                                   const ARMSubtarget *Subtarget) {
9713   SelectionDAG &DAG = DCI.DAG;
9714   SDValue Op = N->getOperand(0);
9715   unsigned OpOpcode = Op.getNode()->getOpcode();
9716
9717   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9718       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9719     return SDValue();
9720
9721   uint64_t C;
9722   SDValue ConstVec = N->getOperand(1);
9723   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9724
9725   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9726       !isConstVecPow2(ConstVec, isSigned, C))
9727     return SDValue();
9728
9729   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9730   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9731   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9732     // These instructions only exist converting from i32 to f32. We can handle
9733     // smaller integers by generating an extra extend, but larger ones would
9734     // be lossy.
9735     return SDValue();
9736   }
9737
9738   SDLoc dl(N);
9739   SDValue ConvInput = Op.getOperand(0);
9740   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9741   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9742     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9743                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9744                             ConvInput);
9745
9746   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9747     Intrinsic::arm_neon_vcvtfxu2fp;
9748   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9749                      Op.getValueType(),
9750                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9751                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9752 }
9753
9754 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9755 /// operand of a vector shift operation, where all the elements of the
9756 /// build_vector must have the same constant integer value.
9757 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9758   // Ignore bit_converts.
9759   while (Op.getOpcode() == ISD::BITCAST)
9760     Op = Op.getOperand(0);
9761   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9762   APInt SplatBits, SplatUndef;
9763   unsigned SplatBitSize;
9764   bool HasAnyUndefs;
9765   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9766                                       HasAnyUndefs, ElementBits) ||
9767       SplatBitSize > ElementBits)
9768     return false;
9769   Cnt = SplatBits.getSExtValue();
9770   return true;
9771 }
9772
9773 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9774 /// operand of a vector shift left operation.  That value must be in the range:
9775 ///   0 <= Value < ElementBits for a left shift; or
9776 ///   0 <= Value <= ElementBits for a long left shift.
9777 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9778   assert(VT.isVector() && "vector shift count is not a vector type");
9779   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9780   if (! getVShiftImm(Op, ElementBits, Cnt))
9781     return false;
9782   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9783 }
9784
9785 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9786 /// operand of a vector shift right operation.  For a shift opcode, the value
9787 /// is positive, but for an intrinsic the value count must be negative. The
9788 /// absolute value must be in the range:
9789 ///   1 <= |Value| <= ElementBits for a right shift; or
9790 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9791 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9792                          int64_t &Cnt) {
9793   assert(VT.isVector() && "vector shift count is not a vector type");
9794   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9795   if (! getVShiftImm(Op, ElementBits, Cnt))
9796     return false;
9797   if (!isIntrinsic)
9798     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9799   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9800     Cnt = -Cnt;
9801     return true;
9802   }
9803   return false;
9804 }
9805
9806 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9807 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9808   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9809   switch (IntNo) {
9810   default:
9811     // Don't do anything for most intrinsics.
9812     break;
9813
9814   case Intrinsic::arm_neon_vabds:
9815     if (!N->getValueType(0).isInteger())
9816       return SDValue();
9817     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9818                        N->getOperand(1), N->getOperand(2));
9819   case Intrinsic::arm_neon_vabdu:
9820     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9821                        N->getOperand(1), N->getOperand(2));
9822
9823   // Vector shifts: check for immediate versions and lower them.
9824   // Note: This is done during DAG combining instead of DAG legalizing because
9825   // the build_vectors for 64-bit vector element shift counts are generally
9826   // not legal, and it is hard to see their values after they get legalized to
9827   // loads from a constant pool.
9828   case Intrinsic::arm_neon_vshifts:
9829   case Intrinsic::arm_neon_vshiftu:
9830   case Intrinsic::arm_neon_vrshifts:
9831   case Intrinsic::arm_neon_vrshiftu:
9832   case Intrinsic::arm_neon_vrshiftn:
9833   case Intrinsic::arm_neon_vqshifts:
9834   case Intrinsic::arm_neon_vqshiftu:
9835   case Intrinsic::arm_neon_vqshiftsu:
9836   case Intrinsic::arm_neon_vqshiftns:
9837   case Intrinsic::arm_neon_vqshiftnu:
9838   case Intrinsic::arm_neon_vqshiftnsu:
9839   case Intrinsic::arm_neon_vqrshiftns:
9840   case Intrinsic::arm_neon_vqrshiftnu:
9841   case Intrinsic::arm_neon_vqrshiftnsu: {
9842     EVT VT = N->getOperand(1).getValueType();
9843     int64_t Cnt;
9844     unsigned VShiftOpc = 0;
9845
9846     switch (IntNo) {
9847     case Intrinsic::arm_neon_vshifts:
9848     case Intrinsic::arm_neon_vshiftu:
9849       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9850         VShiftOpc = ARMISD::VSHL;
9851         break;
9852       }
9853       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9854         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9855                      ARMISD::VSHRs : ARMISD::VSHRu);
9856         break;
9857       }
9858       return SDValue();
9859
9860     case Intrinsic::arm_neon_vrshifts:
9861     case Intrinsic::arm_neon_vrshiftu:
9862       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9863         break;
9864       return SDValue();
9865
9866     case Intrinsic::arm_neon_vqshifts:
9867     case Intrinsic::arm_neon_vqshiftu:
9868       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9869         break;
9870       return SDValue();
9871
9872     case Intrinsic::arm_neon_vqshiftsu:
9873       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9874         break;
9875       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9876
9877     case Intrinsic::arm_neon_vrshiftn:
9878     case Intrinsic::arm_neon_vqshiftns:
9879     case Intrinsic::arm_neon_vqshiftnu:
9880     case Intrinsic::arm_neon_vqshiftnsu:
9881     case Intrinsic::arm_neon_vqrshiftns:
9882     case Intrinsic::arm_neon_vqrshiftnu:
9883     case Intrinsic::arm_neon_vqrshiftnsu:
9884       // Narrowing shifts require an immediate right shift.
9885       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9886         break;
9887       llvm_unreachable("invalid shift count for narrowing vector shift "
9888                        "intrinsic");
9889
9890     default:
9891       llvm_unreachable("unhandled vector shift");
9892     }
9893
9894     switch (IntNo) {
9895     case Intrinsic::arm_neon_vshifts:
9896     case Intrinsic::arm_neon_vshiftu:
9897       // Opcode already set above.
9898       break;
9899     case Intrinsic::arm_neon_vrshifts:
9900       VShiftOpc = ARMISD::VRSHRs; break;
9901     case Intrinsic::arm_neon_vrshiftu:
9902       VShiftOpc = ARMISD::VRSHRu; break;
9903     case Intrinsic::arm_neon_vrshiftn:
9904       VShiftOpc = ARMISD::VRSHRN; break;
9905     case Intrinsic::arm_neon_vqshifts:
9906       VShiftOpc = ARMISD::VQSHLs; break;
9907     case Intrinsic::arm_neon_vqshiftu:
9908       VShiftOpc = ARMISD::VQSHLu; break;
9909     case Intrinsic::arm_neon_vqshiftsu:
9910       VShiftOpc = ARMISD::VQSHLsu; break;
9911     case Intrinsic::arm_neon_vqshiftns:
9912       VShiftOpc = ARMISD::VQSHRNs; break;
9913     case Intrinsic::arm_neon_vqshiftnu:
9914       VShiftOpc = ARMISD::VQSHRNu; break;
9915     case Intrinsic::arm_neon_vqshiftnsu:
9916       VShiftOpc = ARMISD::VQSHRNsu; break;
9917     case Intrinsic::arm_neon_vqrshiftns:
9918       VShiftOpc = ARMISD::VQRSHRNs; break;
9919     case Intrinsic::arm_neon_vqrshiftnu:
9920       VShiftOpc = ARMISD::VQRSHRNu; break;
9921     case Intrinsic::arm_neon_vqrshiftnsu:
9922       VShiftOpc = ARMISD::VQRSHRNsu; break;
9923     }
9924
9925     SDLoc dl(N);
9926     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9927                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9928   }
9929
9930   case Intrinsic::arm_neon_vshiftins: {
9931     EVT VT = N->getOperand(1).getValueType();
9932     int64_t Cnt;
9933     unsigned VShiftOpc = 0;
9934
9935     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9936       VShiftOpc = ARMISD::VSLI;
9937     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9938       VShiftOpc = ARMISD::VSRI;
9939     else {
9940       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9941     }
9942
9943     SDLoc dl(N);
9944     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9945                        N->getOperand(1), N->getOperand(2),
9946                        DAG.getConstant(Cnt, dl, MVT::i32));
9947   }
9948
9949   case Intrinsic::arm_neon_vqrshifts:
9950   case Intrinsic::arm_neon_vqrshiftu:
9951     // No immediate versions of these to check for.
9952     break;
9953   }
9954
9955   return SDValue();
9956 }
9957
9958 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9959 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9960 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9961 /// vector element shift counts are generally not legal, and it is hard to see
9962 /// their values after they get legalized to loads from a constant pool.
9963 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9964                                    const ARMSubtarget *ST) {
9965   EVT VT = N->getValueType(0);
9966   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9967     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9968     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9969     SDValue N1 = N->getOperand(1);
9970     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9971       SDValue N0 = N->getOperand(0);
9972       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9973           DAG.MaskedValueIsZero(N0.getOperand(0),
9974                                 APInt::getHighBitsSet(32, 16)))
9975         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9976     }
9977   }
9978
9979   // Nothing to be done for scalar shifts.
9980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9981   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9982     return SDValue();
9983
9984   assert(ST->hasNEON() && "unexpected vector shift");
9985   int64_t Cnt;
9986
9987   switch (N->getOpcode()) {
9988   default: llvm_unreachable("unexpected shift opcode");
9989
9990   case ISD::SHL:
9991     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9992       SDLoc dl(N);
9993       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9994                          DAG.getConstant(Cnt, dl, MVT::i32));
9995     }
9996     break;
9997
9998   case ISD::SRA:
9999   case ISD::SRL:
10000     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10001       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10002                             ARMISD::VSHRs : ARMISD::VSHRu);
10003       SDLoc dl(N);
10004       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10005                          DAG.getConstant(Cnt, dl, MVT::i32));
10006     }
10007   }
10008   return SDValue();
10009 }
10010
10011 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10012 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10013 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10014                                     const ARMSubtarget *ST) {
10015   SDValue N0 = N->getOperand(0);
10016
10017   // Check for sign- and zero-extensions of vector extract operations of 8-
10018   // and 16-bit vector elements.  NEON supports these directly.  They are
10019   // handled during DAG combining because type legalization will promote them
10020   // to 32-bit types and it is messy to recognize the operations after that.
10021   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10022     SDValue Vec = N0.getOperand(0);
10023     SDValue Lane = N0.getOperand(1);
10024     EVT VT = N->getValueType(0);
10025     EVT EltVT = N0.getValueType();
10026     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10027
10028     if (VT == MVT::i32 &&
10029         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10030         TLI.isTypeLegal(Vec.getValueType()) &&
10031         isa<ConstantSDNode>(Lane)) {
10032
10033       unsigned Opc = 0;
10034       switch (N->getOpcode()) {
10035       default: llvm_unreachable("unexpected opcode");
10036       case ISD::SIGN_EXTEND:
10037         Opc = ARMISD::VGETLANEs;
10038         break;
10039       case ISD::ZERO_EXTEND:
10040       case ISD::ANY_EXTEND:
10041         Opc = ARMISD::VGETLANEu;
10042         break;
10043       }
10044       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10045     }
10046   }
10047
10048   return SDValue();
10049 }
10050
10051 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10052 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10053 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10054                                        const ARMSubtarget *ST) {
10055   // If the target supports NEON, try to use vmax/vmin instructions for f32
10056   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10057   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10058   // a NaN; only do the transformation when it matches that behavior.
10059
10060   // For now only do this when using NEON for FP operations; if using VFP, it
10061   // is not obvious that the benefit outweighs the cost of switching to the
10062   // NEON pipeline.
10063   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10064       N->getValueType(0) != MVT::f32)
10065     return SDValue();
10066
10067   SDValue CondLHS = N->getOperand(0);
10068   SDValue CondRHS = N->getOperand(1);
10069   SDValue LHS = N->getOperand(2);
10070   SDValue RHS = N->getOperand(3);
10071   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10072
10073   unsigned Opcode = 0;
10074   bool IsReversed;
10075   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10076     IsReversed = false; // x CC y ? x : y
10077   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10078     IsReversed = true ; // x CC y ? y : x
10079   } else {
10080     return SDValue();
10081   }
10082
10083   bool IsUnordered;
10084   switch (CC) {
10085   default: break;
10086   case ISD::SETOLT:
10087   case ISD::SETOLE:
10088   case ISD::SETLT:
10089   case ISD::SETLE:
10090   case ISD::SETULT:
10091   case ISD::SETULE:
10092     // If LHS is NaN, an ordered comparison will be false and the result will
10093     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10094     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10095     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10096     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10097       break;
10098     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10099     // will return -0, so vmin can only be used for unsafe math or if one of
10100     // the operands is known to be nonzero.
10101     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10102         !DAG.getTarget().Options.UnsafeFPMath &&
10103         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10104       break;
10105     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10106     break;
10107
10108   case ISD::SETOGT:
10109   case ISD::SETOGE:
10110   case ISD::SETGT:
10111   case ISD::SETGE:
10112   case ISD::SETUGT:
10113   case ISD::SETUGE:
10114     // If LHS is NaN, an ordered comparison will be false and the result will
10115     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10116     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10117     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10118     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10119       break;
10120     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10121     // will return +0, so vmax can only be used for unsafe math or if one of
10122     // the operands is known to be nonzero.
10123     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10124         !DAG.getTarget().Options.UnsafeFPMath &&
10125         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10126       break;
10127     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10128     break;
10129   }
10130
10131   if (!Opcode)
10132     return SDValue();
10133   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10134 }
10135
10136 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10137 SDValue
10138 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10139   SDValue Cmp = N->getOperand(4);
10140   if (Cmp.getOpcode() != ARMISD::CMPZ)
10141     // Only looking at EQ and NE cases.
10142     return SDValue();
10143
10144   EVT VT = N->getValueType(0);
10145   SDLoc dl(N);
10146   SDValue LHS = Cmp.getOperand(0);
10147   SDValue RHS = Cmp.getOperand(1);
10148   SDValue FalseVal = N->getOperand(0);
10149   SDValue TrueVal = N->getOperand(1);
10150   SDValue ARMcc = N->getOperand(2);
10151   ARMCC::CondCodes CC =
10152     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10153
10154   // Simplify
10155   //   mov     r1, r0
10156   //   cmp     r1, x
10157   //   mov     r0, y
10158   //   moveq   r0, x
10159   // to
10160   //   cmp     r0, x
10161   //   movne   r0, y
10162   //
10163   //   mov     r1, r0
10164   //   cmp     r1, x
10165   //   mov     r0, x
10166   //   movne   r0, y
10167   // to
10168   //   cmp     r0, x
10169   //   movne   r0, y
10170   /// FIXME: Turn this into a target neutral optimization?
10171   SDValue Res;
10172   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10173     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10174                       N->getOperand(3), Cmp);
10175   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10176     SDValue ARMcc;
10177     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10178     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10179                       N->getOperand(3), NewCmp);
10180   }
10181
10182   if (Res.getNode()) {
10183     APInt KnownZero, KnownOne;
10184     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10185     // Capture demanded bits information that would be otherwise lost.
10186     if (KnownZero == 0xfffffffe)
10187       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10188                         DAG.getValueType(MVT::i1));
10189     else if (KnownZero == 0xffffff00)
10190       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10191                         DAG.getValueType(MVT::i8));
10192     else if (KnownZero == 0xffff0000)
10193       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10194                         DAG.getValueType(MVT::i16));
10195   }
10196
10197   return Res;
10198 }
10199
10200 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10201                                              DAGCombinerInfo &DCI) const {
10202   switch (N->getOpcode()) {
10203   default: break;
10204   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10205   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10206   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10207   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10208   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10209   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10210   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10211   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10212   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10213   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10214   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10215   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10216   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10217   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10218   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10219   case ISD::FP_TO_SINT:
10220   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10221   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10222   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10223   case ISD::SHL:
10224   case ISD::SRA:
10225   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10226   case ISD::SIGN_EXTEND:
10227   case ISD::ZERO_EXTEND:
10228   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10229   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10230   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10231   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10232   case ARMISD::VLD2DUP:
10233   case ARMISD::VLD3DUP:
10234   case ARMISD::VLD4DUP:
10235     return PerformVLDCombine(N, DCI);
10236   case ARMISD::BUILD_VECTOR:
10237     return PerformARMBUILD_VECTORCombine(N, DCI);
10238   case ISD::INTRINSIC_VOID:
10239   case ISD::INTRINSIC_W_CHAIN:
10240     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10241     case Intrinsic::arm_neon_vld1:
10242     case Intrinsic::arm_neon_vld2:
10243     case Intrinsic::arm_neon_vld3:
10244     case Intrinsic::arm_neon_vld4:
10245     case Intrinsic::arm_neon_vld2lane:
10246     case Intrinsic::arm_neon_vld3lane:
10247     case Intrinsic::arm_neon_vld4lane:
10248     case Intrinsic::arm_neon_vst1:
10249     case Intrinsic::arm_neon_vst2:
10250     case Intrinsic::arm_neon_vst3:
10251     case Intrinsic::arm_neon_vst4:
10252     case Intrinsic::arm_neon_vst2lane:
10253     case Intrinsic::arm_neon_vst3lane:
10254     case Intrinsic::arm_neon_vst4lane:
10255       return PerformVLDCombine(N, DCI);
10256     default: break;
10257     }
10258     break;
10259   }
10260   return SDValue();
10261 }
10262
10263 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10264                                                           EVT VT) const {
10265   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10266 }
10267
10268 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10269                                                        unsigned,
10270                                                        unsigned,
10271                                                        bool *Fast) const {
10272   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10273   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10274
10275   switch (VT.getSimpleVT().SimpleTy) {
10276   default:
10277     return false;
10278   case MVT::i8:
10279   case MVT::i16:
10280   case MVT::i32: {
10281     // Unaligned access can use (for example) LRDB, LRDH, LDR
10282     if (AllowsUnaligned) {
10283       if (Fast)
10284         *Fast = Subtarget->hasV7Ops();
10285       return true;
10286     }
10287     return false;
10288   }
10289   case MVT::f64:
10290   case MVT::v2f64: {
10291     // For any little-endian targets with neon, we can support unaligned ld/st
10292     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10293     // A big-endian target may also explicitly support unaligned accesses
10294     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10295       if (Fast)
10296         *Fast = true;
10297       return true;
10298     }
10299     return false;
10300   }
10301   }
10302 }
10303
10304 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10305                        unsigned AlignCheck) {
10306   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10307           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10308 }
10309
10310 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10311                                            unsigned DstAlign, unsigned SrcAlign,
10312                                            bool IsMemset, bool ZeroMemset,
10313                                            bool MemcpyStrSrc,
10314                                            MachineFunction &MF) const {
10315   const Function *F = MF.getFunction();
10316
10317   // See if we can use NEON instructions for this...
10318   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10319       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10320     bool Fast;
10321     if (Size >= 16 &&
10322         (memOpAlign(SrcAlign, DstAlign, 16) ||
10323          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10324       return MVT::v2f64;
10325     } else if (Size >= 8 &&
10326                (memOpAlign(SrcAlign, DstAlign, 8) ||
10327                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10328                  Fast))) {
10329       return MVT::f64;
10330     }
10331   }
10332
10333   // Lowering to i32/i16 if the size permits.
10334   if (Size >= 4)
10335     return MVT::i32;
10336   else if (Size >= 2)
10337     return MVT::i16;
10338
10339   // Let the target-independent logic figure it out.
10340   return MVT::Other;
10341 }
10342
10343 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10344   if (Val.getOpcode() != ISD::LOAD)
10345     return false;
10346
10347   EVT VT1 = Val.getValueType();
10348   if (!VT1.isSimple() || !VT1.isInteger() ||
10349       !VT2.isSimple() || !VT2.isInteger())
10350     return false;
10351
10352   switch (VT1.getSimpleVT().SimpleTy) {
10353   default: break;
10354   case MVT::i1:
10355   case MVT::i8:
10356   case MVT::i16:
10357     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10358     return true;
10359   }
10360
10361   return false;
10362 }
10363
10364 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10365   EVT VT = ExtVal.getValueType();
10366
10367   if (!isTypeLegal(VT))
10368     return false;
10369
10370   // Don't create a loadext if we can fold the extension into a wide/long
10371   // instruction.
10372   // If there's more than one user instruction, the loadext is desirable no
10373   // matter what.  There can be two uses by the same instruction.
10374   if (ExtVal->use_empty() ||
10375       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10376     return true;
10377
10378   SDNode *U = *ExtVal->use_begin();
10379   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10380        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10381     return false;
10382
10383   return true;
10384 }
10385
10386 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10387   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10388     return false;
10389
10390   if (!isTypeLegal(EVT::getEVT(Ty1)))
10391     return false;
10392
10393   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10394
10395   // Assuming the caller doesn't have a zeroext or signext return parameter,
10396   // truncation all the way down to i1 is valid.
10397   return true;
10398 }
10399
10400
10401 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10402   if (V < 0)
10403     return false;
10404
10405   unsigned Scale = 1;
10406   switch (VT.getSimpleVT().SimpleTy) {
10407   default: return false;
10408   case MVT::i1:
10409   case MVT::i8:
10410     // Scale == 1;
10411     break;
10412   case MVT::i16:
10413     // Scale == 2;
10414     Scale = 2;
10415     break;
10416   case MVT::i32:
10417     // Scale == 4;
10418     Scale = 4;
10419     break;
10420   }
10421
10422   if ((V & (Scale - 1)) != 0)
10423     return false;
10424   V /= Scale;
10425   return V == (V & ((1LL << 5) - 1));
10426 }
10427
10428 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10429                                       const ARMSubtarget *Subtarget) {
10430   bool isNeg = false;
10431   if (V < 0) {
10432     isNeg = true;
10433     V = - V;
10434   }
10435
10436   switch (VT.getSimpleVT().SimpleTy) {
10437   default: return false;
10438   case MVT::i1:
10439   case MVT::i8:
10440   case MVT::i16:
10441   case MVT::i32:
10442     // + imm12 or - imm8
10443     if (isNeg)
10444       return V == (V & ((1LL << 8) - 1));
10445     return V == (V & ((1LL << 12) - 1));
10446   case MVT::f32:
10447   case MVT::f64:
10448     // Same as ARM mode. FIXME: NEON?
10449     if (!Subtarget->hasVFP2())
10450       return false;
10451     if ((V & 3) != 0)
10452       return false;
10453     V >>= 2;
10454     return V == (V & ((1LL << 8) - 1));
10455   }
10456 }
10457
10458 /// isLegalAddressImmediate - Return true if the integer value can be used
10459 /// as the offset of the target addressing mode for load / store of the
10460 /// given type.
10461 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10462                                     const ARMSubtarget *Subtarget) {
10463   if (V == 0)
10464     return true;
10465
10466   if (!VT.isSimple())
10467     return false;
10468
10469   if (Subtarget->isThumb1Only())
10470     return isLegalT1AddressImmediate(V, VT);
10471   else if (Subtarget->isThumb2())
10472     return isLegalT2AddressImmediate(V, VT, Subtarget);
10473
10474   // ARM mode.
10475   if (V < 0)
10476     V = - V;
10477   switch (VT.getSimpleVT().SimpleTy) {
10478   default: return false;
10479   case MVT::i1:
10480   case MVT::i8:
10481   case MVT::i32:
10482     // +- imm12
10483     return V == (V & ((1LL << 12) - 1));
10484   case MVT::i16:
10485     // +- imm8
10486     return V == (V & ((1LL << 8) - 1));
10487   case MVT::f32:
10488   case MVT::f64:
10489     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10490       return false;
10491     if ((V & 3) != 0)
10492       return false;
10493     V >>= 2;
10494     return V == (V & ((1LL << 8) - 1));
10495   }
10496 }
10497
10498 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10499                                                       EVT VT) const {
10500   int Scale = AM.Scale;
10501   if (Scale < 0)
10502     return false;
10503
10504   switch (VT.getSimpleVT().SimpleTy) {
10505   default: return false;
10506   case MVT::i1:
10507   case MVT::i8:
10508   case MVT::i16:
10509   case MVT::i32:
10510     if (Scale == 1)
10511       return true;
10512     // r + r << imm
10513     Scale = Scale & ~1;
10514     return Scale == 2 || Scale == 4 || Scale == 8;
10515   case MVT::i64:
10516     // r + r
10517     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10518       return true;
10519     return false;
10520   case MVT::isVoid:
10521     // Note, we allow "void" uses (basically, uses that aren't loads or
10522     // stores), because arm allows folding a scale into many arithmetic
10523     // operations.  This should be made more precise and revisited later.
10524
10525     // Allow r << imm, but the imm has to be a multiple of two.
10526     if (Scale & 1) return false;
10527     return isPowerOf2_32(Scale);
10528   }
10529 }
10530
10531 /// isLegalAddressingMode - Return true if the addressing mode represented
10532 /// by AM is legal for this target, for a load/store of the specified type.
10533 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10534                                               const AddrMode &AM, Type *Ty,
10535                                               unsigned AS) const {
10536   EVT VT = getValueType(DL, Ty, true);
10537   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10538     return false;
10539
10540   // Can never fold addr of global into load/store.
10541   if (AM.BaseGV)
10542     return false;
10543
10544   switch (AM.Scale) {
10545   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10546     break;
10547   case 1:
10548     if (Subtarget->isThumb1Only())
10549       return false;
10550     // FALL THROUGH.
10551   default:
10552     // ARM doesn't support any R+R*scale+imm addr modes.
10553     if (AM.BaseOffs)
10554       return false;
10555
10556     if (!VT.isSimple())
10557       return false;
10558
10559     if (Subtarget->isThumb2())
10560       return isLegalT2ScaledAddressingMode(AM, VT);
10561
10562     int Scale = AM.Scale;
10563     switch (VT.getSimpleVT().SimpleTy) {
10564     default: return false;
10565     case MVT::i1:
10566     case MVT::i8:
10567     case MVT::i32:
10568       if (Scale < 0) Scale = -Scale;
10569       if (Scale == 1)
10570         return true;
10571       // r + r << imm
10572       return isPowerOf2_32(Scale & ~1);
10573     case MVT::i16:
10574     case MVT::i64:
10575       // r + r
10576       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10577         return true;
10578       return false;
10579
10580     case MVT::isVoid:
10581       // Note, we allow "void" uses (basically, uses that aren't loads or
10582       // stores), because arm allows folding a scale into many arithmetic
10583       // operations.  This should be made more precise and revisited later.
10584
10585       // Allow r << imm, but the imm has to be a multiple of two.
10586       if (Scale & 1) return false;
10587       return isPowerOf2_32(Scale);
10588     }
10589   }
10590   return true;
10591 }
10592
10593 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10594 /// icmp immediate, that is the target has icmp instructions which can compare
10595 /// a register against the immediate without having to materialize the
10596 /// immediate into a register.
10597 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10598   // Thumb2 and ARM modes can use cmn for negative immediates.
10599   if (!Subtarget->isThumb())
10600     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10601   if (Subtarget->isThumb2())
10602     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10603   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10604   return Imm >= 0 && Imm <= 255;
10605 }
10606
10607 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10608 /// *or sub* immediate, that is the target has add or sub instructions which can
10609 /// add a register with the immediate without having to materialize the
10610 /// immediate into a register.
10611 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10612   // Same encoding for add/sub, just flip the sign.
10613   int64_t AbsImm = std::abs(Imm);
10614   if (!Subtarget->isThumb())
10615     return ARM_AM::getSOImmVal(AbsImm) != -1;
10616   if (Subtarget->isThumb2())
10617     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10618   // Thumb1 only has 8-bit unsigned immediate.
10619   return AbsImm >= 0 && AbsImm <= 255;
10620 }
10621
10622 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10623                                       bool isSEXTLoad, SDValue &Base,
10624                                       SDValue &Offset, bool &isInc,
10625                                       SelectionDAG &DAG) {
10626   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10627     return false;
10628
10629   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10630     // AddressingMode 3
10631     Base = Ptr->getOperand(0);
10632     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10633       int RHSC = (int)RHS->getZExtValue();
10634       if (RHSC < 0 && RHSC > -256) {
10635         assert(Ptr->getOpcode() == ISD::ADD);
10636         isInc = false;
10637         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10638         return true;
10639       }
10640     }
10641     isInc = (Ptr->getOpcode() == ISD::ADD);
10642     Offset = Ptr->getOperand(1);
10643     return true;
10644   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10645     // AddressingMode 2
10646     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10647       int RHSC = (int)RHS->getZExtValue();
10648       if (RHSC < 0 && RHSC > -0x1000) {
10649         assert(Ptr->getOpcode() == ISD::ADD);
10650         isInc = false;
10651         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10652         Base = Ptr->getOperand(0);
10653         return true;
10654       }
10655     }
10656
10657     if (Ptr->getOpcode() == ISD::ADD) {
10658       isInc = true;
10659       ARM_AM::ShiftOpc ShOpcVal=
10660         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10661       if (ShOpcVal != ARM_AM::no_shift) {
10662         Base = Ptr->getOperand(1);
10663         Offset = Ptr->getOperand(0);
10664       } else {
10665         Base = Ptr->getOperand(0);
10666         Offset = Ptr->getOperand(1);
10667       }
10668       return true;
10669     }
10670
10671     isInc = (Ptr->getOpcode() == ISD::ADD);
10672     Base = Ptr->getOperand(0);
10673     Offset = Ptr->getOperand(1);
10674     return true;
10675   }
10676
10677   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10678   return false;
10679 }
10680
10681 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10682                                      bool isSEXTLoad, SDValue &Base,
10683                                      SDValue &Offset, bool &isInc,
10684                                      SelectionDAG &DAG) {
10685   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10686     return false;
10687
10688   Base = Ptr->getOperand(0);
10689   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10690     int RHSC = (int)RHS->getZExtValue();
10691     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10692       assert(Ptr->getOpcode() == ISD::ADD);
10693       isInc = false;
10694       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10695       return true;
10696     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10697       isInc = Ptr->getOpcode() == ISD::ADD;
10698       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10699       return true;
10700     }
10701   }
10702
10703   return false;
10704 }
10705
10706 /// getPreIndexedAddressParts - returns true by value, base pointer and
10707 /// offset pointer and addressing mode by reference if the node's address
10708 /// can be legally represented as pre-indexed load / store address.
10709 bool
10710 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10711                                              SDValue &Offset,
10712                                              ISD::MemIndexedMode &AM,
10713                                              SelectionDAG &DAG) const {
10714   if (Subtarget->isThumb1Only())
10715     return false;
10716
10717   EVT VT;
10718   SDValue Ptr;
10719   bool isSEXTLoad = false;
10720   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10721     Ptr = LD->getBasePtr();
10722     VT  = LD->getMemoryVT();
10723     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10724   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10725     Ptr = ST->getBasePtr();
10726     VT  = ST->getMemoryVT();
10727   } else
10728     return false;
10729
10730   bool isInc;
10731   bool isLegal = false;
10732   if (Subtarget->isThumb2())
10733     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10734                                        Offset, isInc, DAG);
10735   else
10736     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10737                                         Offset, isInc, DAG);
10738   if (!isLegal)
10739     return false;
10740
10741   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10742   return true;
10743 }
10744
10745 /// getPostIndexedAddressParts - returns true by value, base pointer and
10746 /// offset pointer and addressing mode by reference if this node can be
10747 /// combined with a load / store to form a post-indexed load / store.
10748 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10749                                                    SDValue &Base,
10750                                                    SDValue &Offset,
10751                                                    ISD::MemIndexedMode &AM,
10752                                                    SelectionDAG &DAG) const {
10753   if (Subtarget->isThumb1Only())
10754     return false;
10755
10756   EVT VT;
10757   SDValue Ptr;
10758   bool isSEXTLoad = false;
10759   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10760     VT  = LD->getMemoryVT();
10761     Ptr = LD->getBasePtr();
10762     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10763   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10764     VT  = ST->getMemoryVT();
10765     Ptr = ST->getBasePtr();
10766   } else
10767     return false;
10768
10769   bool isInc;
10770   bool isLegal = false;
10771   if (Subtarget->isThumb2())
10772     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10773                                        isInc, DAG);
10774   else
10775     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10776                                         isInc, DAG);
10777   if (!isLegal)
10778     return false;
10779
10780   if (Ptr != Base) {
10781     // Swap base ptr and offset to catch more post-index load / store when
10782     // it's legal. In Thumb2 mode, offset must be an immediate.
10783     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10784         !Subtarget->isThumb2())
10785       std::swap(Base, Offset);
10786
10787     // Post-indexed load / store update the base pointer.
10788     if (Ptr != Base)
10789       return false;
10790   }
10791
10792   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10793   return true;
10794 }
10795
10796 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10797                                                       APInt &KnownZero,
10798                                                       APInt &KnownOne,
10799                                                       const SelectionDAG &DAG,
10800                                                       unsigned Depth) const {
10801   unsigned BitWidth = KnownOne.getBitWidth();
10802   KnownZero = KnownOne = APInt(BitWidth, 0);
10803   switch (Op.getOpcode()) {
10804   default: break;
10805   case ARMISD::ADDC:
10806   case ARMISD::ADDE:
10807   case ARMISD::SUBC:
10808   case ARMISD::SUBE:
10809     // These nodes' second result is a boolean
10810     if (Op.getResNo() == 0)
10811       break;
10812     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10813     break;
10814   case ARMISD::CMOV: {
10815     // Bits are known zero/one if known on the LHS and RHS.
10816     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10817     if (KnownZero == 0 && KnownOne == 0) return;
10818
10819     APInt KnownZeroRHS, KnownOneRHS;
10820     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10821     KnownZero &= KnownZeroRHS;
10822     KnownOne  &= KnownOneRHS;
10823     return;
10824   }
10825   case ISD::INTRINSIC_W_CHAIN: {
10826     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10827     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10828     switch (IntID) {
10829     default: return;
10830     case Intrinsic::arm_ldaex:
10831     case Intrinsic::arm_ldrex: {
10832       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10833       unsigned MemBits = VT.getScalarType().getSizeInBits();
10834       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10835       return;
10836     }
10837     }
10838   }
10839   }
10840 }
10841
10842 //===----------------------------------------------------------------------===//
10843 //                           ARM Inline Assembly Support
10844 //===----------------------------------------------------------------------===//
10845
10846 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10847   // Looking for "rev" which is V6+.
10848   if (!Subtarget->hasV6Ops())
10849     return false;
10850
10851   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10852   std::string AsmStr = IA->getAsmString();
10853   SmallVector<StringRef, 4> AsmPieces;
10854   SplitString(AsmStr, AsmPieces, ";\n");
10855
10856   switch (AsmPieces.size()) {
10857   default: return false;
10858   case 1:
10859     AsmStr = AsmPieces[0];
10860     AsmPieces.clear();
10861     SplitString(AsmStr, AsmPieces, " \t,");
10862
10863     // rev $0, $1
10864     if (AsmPieces.size() == 3 &&
10865         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10866         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10867       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10868       if (Ty && Ty->getBitWidth() == 32)
10869         return IntrinsicLowering::LowerToByteSwap(CI);
10870     }
10871     break;
10872   }
10873
10874   return false;
10875 }
10876
10877 /// getConstraintType - Given a constraint letter, return the type of
10878 /// constraint it is for this target.
10879 ARMTargetLowering::ConstraintType
10880 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10881   if (Constraint.size() == 1) {
10882     switch (Constraint[0]) {
10883     default:  break;
10884     case 'l': return C_RegisterClass;
10885     case 'w': return C_RegisterClass;
10886     case 'h': return C_RegisterClass;
10887     case 'x': return C_RegisterClass;
10888     case 't': return C_RegisterClass;
10889     case 'j': return C_Other; // Constant for movw.
10890       // An address with a single base register. Due to the way we
10891       // currently handle addresses it is the same as an 'r' memory constraint.
10892     case 'Q': return C_Memory;
10893     }
10894   } else if (Constraint.size() == 2) {
10895     switch (Constraint[0]) {
10896     default: break;
10897     // All 'U+' constraints are addresses.
10898     case 'U': return C_Memory;
10899     }
10900   }
10901   return TargetLowering::getConstraintType(Constraint);
10902 }
10903
10904 /// Examine constraint type and operand type and determine a weight value.
10905 /// This object must already have been set up with the operand type
10906 /// and the current alternative constraint selected.
10907 TargetLowering::ConstraintWeight
10908 ARMTargetLowering::getSingleConstraintMatchWeight(
10909     AsmOperandInfo &info, const char *constraint) const {
10910   ConstraintWeight weight = CW_Invalid;
10911   Value *CallOperandVal = info.CallOperandVal;
10912     // If we don't have a value, we can't do a match,
10913     // but allow it at the lowest weight.
10914   if (!CallOperandVal)
10915     return CW_Default;
10916   Type *type = CallOperandVal->getType();
10917   // Look at the constraint type.
10918   switch (*constraint) {
10919   default:
10920     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10921     break;
10922   case 'l':
10923     if (type->isIntegerTy()) {
10924       if (Subtarget->isThumb())
10925         weight = CW_SpecificReg;
10926       else
10927         weight = CW_Register;
10928     }
10929     break;
10930   case 'w':
10931     if (type->isFloatingPointTy())
10932       weight = CW_Register;
10933     break;
10934   }
10935   return weight;
10936 }
10937
10938 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10939 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10940     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10941   if (Constraint.size() == 1) {
10942     // GCC ARM Constraint Letters
10943     switch (Constraint[0]) {
10944     case 'l': // Low regs or general regs.
10945       if (Subtarget->isThumb())
10946         return RCPair(0U, &ARM::tGPRRegClass);
10947       return RCPair(0U, &ARM::GPRRegClass);
10948     case 'h': // High regs or no regs.
10949       if (Subtarget->isThumb())
10950         return RCPair(0U, &ARM::hGPRRegClass);
10951       break;
10952     case 'r':
10953       if (Subtarget->isThumb1Only())
10954         return RCPair(0U, &ARM::tGPRRegClass);
10955       return RCPair(0U, &ARM::GPRRegClass);
10956     case 'w':
10957       if (VT == MVT::Other)
10958         break;
10959       if (VT == MVT::f32)
10960         return RCPair(0U, &ARM::SPRRegClass);
10961       if (VT.getSizeInBits() == 64)
10962         return RCPair(0U, &ARM::DPRRegClass);
10963       if (VT.getSizeInBits() == 128)
10964         return RCPair(0U, &ARM::QPRRegClass);
10965       break;
10966     case 'x':
10967       if (VT == MVT::Other)
10968         break;
10969       if (VT == MVT::f32)
10970         return RCPair(0U, &ARM::SPR_8RegClass);
10971       if (VT.getSizeInBits() == 64)
10972         return RCPair(0U, &ARM::DPR_8RegClass);
10973       if (VT.getSizeInBits() == 128)
10974         return RCPair(0U, &ARM::QPR_8RegClass);
10975       break;
10976     case 't':
10977       if (VT == MVT::f32)
10978         return RCPair(0U, &ARM::SPRRegClass);
10979       break;
10980     }
10981   }
10982   if (StringRef("{cc}").equals_lower(Constraint))
10983     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10984
10985   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10986 }
10987
10988 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10989 /// vector.  If it is invalid, don't add anything to Ops.
10990 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10991                                                      std::string &Constraint,
10992                                                      std::vector<SDValue>&Ops,
10993                                                      SelectionDAG &DAG) const {
10994   SDValue Result;
10995
10996   // Currently only support length 1 constraints.
10997   if (Constraint.length() != 1) return;
10998
10999   char ConstraintLetter = Constraint[0];
11000   switch (ConstraintLetter) {
11001   default: break;
11002   case 'j':
11003   case 'I': case 'J': case 'K': case 'L':
11004   case 'M': case 'N': case 'O':
11005     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11006     if (!C)
11007       return;
11008
11009     int64_t CVal64 = C->getSExtValue();
11010     int CVal = (int) CVal64;
11011     // None of these constraints allow values larger than 32 bits.  Check
11012     // that the value fits in an int.
11013     if (CVal != CVal64)
11014       return;
11015
11016     switch (ConstraintLetter) {
11017       case 'j':
11018         // Constant suitable for movw, must be between 0 and
11019         // 65535.
11020         if (Subtarget->hasV6T2Ops())
11021           if (CVal >= 0 && CVal <= 65535)
11022             break;
11023         return;
11024       case 'I':
11025         if (Subtarget->isThumb1Only()) {
11026           // This must be a constant between 0 and 255, for ADD
11027           // immediates.
11028           if (CVal >= 0 && CVal <= 255)
11029             break;
11030         } else if (Subtarget->isThumb2()) {
11031           // A constant that can be used as an immediate value in a
11032           // data-processing instruction.
11033           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11034             break;
11035         } else {
11036           // A constant that can be used as an immediate value in a
11037           // data-processing instruction.
11038           if (ARM_AM::getSOImmVal(CVal) != -1)
11039             break;
11040         }
11041         return;
11042
11043       case 'J':
11044         if (Subtarget->isThumb()) {  // FIXME thumb2
11045           // This must be a constant between -255 and -1, for negated ADD
11046           // immediates. This can be used in GCC with an "n" modifier that
11047           // prints the negated value, for use with SUB instructions. It is
11048           // not useful otherwise but is implemented for compatibility.
11049           if (CVal >= -255 && CVal <= -1)
11050             break;
11051         } else {
11052           // This must be a constant between -4095 and 4095. It is not clear
11053           // what this constraint is intended for. Implemented for
11054           // compatibility with GCC.
11055           if (CVal >= -4095 && CVal <= 4095)
11056             break;
11057         }
11058         return;
11059
11060       case 'K':
11061         if (Subtarget->isThumb1Only()) {
11062           // A 32-bit value where only one byte has a nonzero value. Exclude
11063           // zero to match GCC. This constraint is used by GCC internally for
11064           // constants that can be loaded with a move/shift combination.
11065           // It is not useful otherwise but is implemented for compatibility.
11066           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11067             break;
11068         } else if (Subtarget->isThumb2()) {
11069           // A constant whose bitwise inverse can be used as an immediate
11070           // value in a data-processing instruction. This can be used in GCC
11071           // with a "B" modifier that prints the inverted value, for use with
11072           // BIC and MVN instructions. It is not useful otherwise but is
11073           // implemented for compatibility.
11074           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11075             break;
11076         } else {
11077           // A constant whose bitwise inverse can be used as an immediate
11078           // value in a data-processing instruction. This can be used in GCC
11079           // with a "B" modifier that prints the inverted value, for use with
11080           // BIC and MVN instructions. It is not useful otherwise but is
11081           // implemented for compatibility.
11082           if (ARM_AM::getSOImmVal(~CVal) != -1)
11083             break;
11084         }
11085         return;
11086
11087       case 'L':
11088         if (Subtarget->isThumb1Only()) {
11089           // This must be a constant between -7 and 7,
11090           // for 3-operand ADD/SUB immediate instructions.
11091           if (CVal >= -7 && CVal < 7)
11092             break;
11093         } else if (Subtarget->isThumb2()) {
11094           // A constant whose negation can be used as an immediate value in a
11095           // data-processing instruction. This can be used in GCC with an "n"
11096           // modifier that prints the negated value, for use with SUB
11097           // instructions. It is not useful otherwise but is implemented for
11098           // compatibility.
11099           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11100             break;
11101         } else {
11102           // A constant whose negation can be used as an immediate value in a
11103           // data-processing instruction. This can be used in GCC with an "n"
11104           // modifier that prints the negated value, for use with SUB
11105           // instructions. It is not useful otherwise but is implemented for
11106           // compatibility.
11107           if (ARM_AM::getSOImmVal(-CVal) != -1)
11108             break;
11109         }
11110         return;
11111
11112       case 'M':
11113         if (Subtarget->isThumb()) { // FIXME thumb2
11114           // This must be a multiple of 4 between 0 and 1020, for
11115           // ADD sp + immediate.
11116           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11117             break;
11118         } else {
11119           // A power of two or a constant between 0 and 32.  This is used in
11120           // GCC for the shift amount on shifted register operands, but it is
11121           // useful in general for any shift amounts.
11122           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11123             break;
11124         }
11125         return;
11126
11127       case 'N':
11128         if (Subtarget->isThumb()) {  // FIXME thumb2
11129           // This must be a constant between 0 and 31, for shift amounts.
11130           if (CVal >= 0 && CVal <= 31)
11131             break;
11132         }
11133         return;
11134
11135       case 'O':
11136         if (Subtarget->isThumb()) {  // FIXME thumb2
11137           // This must be a multiple of 4 between -508 and 508, for
11138           // ADD/SUB sp = sp + immediate.
11139           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11140             break;
11141         }
11142         return;
11143     }
11144     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11145     break;
11146   }
11147
11148   if (Result.getNode()) {
11149     Ops.push_back(Result);
11150     return;
11151   }
11152   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11153 }
11154
11155 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11156   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11157          "Register-based DivRem lowering only");
11158   unsigned Opcode = Op->getOpcode();
11159   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11160          "Invalid opcode for Div/Rem lowering");
11161   bool isSigned = (Opcode == ISD::SDIVREM);
11162   EVT VT = Op->getValueType(0);
11163   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11164
11165   RTLIB::Libcall LC;
11166   switch (VT.getSimpleVT().SimpleTy) {
11167   default: llvm_unreachable("Unexpected request for libcall!");
11168   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11169   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11170   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11171   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11172   }
11173
11174   SDValue InChain = DAG.getEntryNode();
11175
11176   TargetLowering::ArgListTy Args;
11177   TargetLowering::ArgListEntry Entry;
11178   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11179     EVT ArgVT = Op->getOperand(i).getValueType();
11180     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11181     Entry.Node = Op->getOperand(i);
11182     Entry.Ty = ArgTy;
11183     Entry.isSExt = isSigned;
11184     Entry.isZExt = !isSigned;
11185     Args.push_back(Entry);
11186   }
11187
11188   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11189                                          getPointerTy(DAG.getDataLayout()));
11190
11191   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11192
11193   SDLoc dl(Op);
11194   TargetLowering::CallLoweringInfo CLI(DAG);
11195   CLI.setDebugLoc(dl).setChain(InChain)
11196     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11197     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11198
11199   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11200   return CallInfo.first;
11201 }
11202
11203 SDValue
11204 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11205   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11206   SDLoc DL(Op);
11207
11208   // Get the inputs.
11209   SDValue Chain = Op.getOperand(0);
11210   SDValue Size  = Op.getOperand(1);
11211
11212   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11213                               DAG.getConstant(2, DL, MVT::i32));
11214
11215   SDValue Flag;
11216   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11217   Flag = Chain.getValue(1);
11218
11219   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11220   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11221
11222   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11223   Chain = NewSP.getValue(1);
11224
11225   SDValue Ops[2] = { NewSP, Chain };
11226   return DAG.getMergeValues(Ops, DL);
11227 }
11228
11229 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11230   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11231          "Unexpected type for custom-lowering FP_EXTEND");
11232
11233   RTLIB::Libcall LC;
11234   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11235
11236   SDValue SrcVal = Op.getOperand(0);
11237   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11238                      /*isSigned*/ false, SDLoc(Op)).first;
11239 }
11240
11241 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11242   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11243          Subtarget->isFPOnlySP() &&
11244          "Unexpected type for custom-lowering FP_ROUND");
11245
11246   RTLIB::Libcall LC;
11247   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11248
11249   SDValue SrcVal = Op.getOperand(0);
11250   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11251                      /*isSigned*/ false, SDLoc(Op)).first;
11252 }
11253
11254 bool
11255 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11256   // The ARM target isn't yet aware of offsets.
11257   return false;
11258 }
11259
11260 bool ARM::isBitFieldInvertedMask(unsigned v) {
11261   if (v == 0xffffffff)
11262     return false;
11263
11264   // there can be 1's on either or both "outsides", all the "inside"
11265   // bits must be 0's
11266   return isShiftedMask_32(~v);
11267 }
11268
11269 /// isFPImmLegal - Returns true if the target can instruction select the
11270 /// specified FP immediate natively. If false, the legalizer will
11271 /// materialize the FP immediate as a load from a constant pool.
11272 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11273   if (!Subtarget->hasVFP3())
11274     return false;
11275   if (VT == MVT::f32)
11276     return ARM_AM::getFP32Imm(Imm) != -1;
11277   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11278     return ARM_AM::getFP64Imm(Imm) != -1;
11279   return false;
11280 }
11281
11282 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11283 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11284 /// specified in the intrinsic calls.
11285 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11286                                            const CallInst &I,
11287                                            unsigned Intrinsic) const {
11288   switch (Intrinsic) {
11289   case Intrinsic::arm_neon_vld1:
11290   case Intrinsic::arm_neon_vld2:
11291   case Intrinsic::arm_neon_vld3:
11292   case Intrinsic::arm_neon_vld4:
11293   case Intrinsic::arm_neon_vld2lane:
11294   case Intrinsic::arm_neon_vld3lane:
11295   case Intrinsic::arm_neon_vld4lane: {
11296     Info.opc = ISD::INTRINSIC_W_CHAIN;
11297     // Conservatively set memVT to the entire set of vectors loaded.
11298     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11299     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11300     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11301     Info.ptrVal = I.getArgOperand(0);
11302     Info.offset = 0;
11303     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11304     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11305     Info.vol = false; // volatile loads with NEON intrinsics not supported
11306     Info.readMem = true;
11307     Info.writeMem = false;
11308     return true;
11309   }
11310   case Intrinsic::arm_neon_vst1:
11311   case Intrinsic::arm_neon_vst2:
11312   case Intrinsic::arm_neon_vst3:
11313   case Intrinsic::arm_neon_vst4:
11314   case Intrinsic::arm_neon_vst2lane:
11315   case Intrinsic::arm_neon_vst3lane:
11316   case Intrinsic::arm_neon_vst4lane: {
11317     Info.opc = ISD::INTRINSIC_VOID;
11318     // Conservatively set memVT to the entire set of vectors stored.
11319     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11320     unsigned NumElts = 0;
11321     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11322       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11323       if (!ArgTy->isVectorTy())
11324         break;
11325       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11326     }
11327     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11328     Info.ptrVal = I.getArgOperand(0);
11329     Info.offset = 0;
11330     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11331     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11332     Info.vol = false; // volatile stores with NEON intrinsics not supported
11333     Info.readMem = false;
11334     Info.writeMem = true;
11335     return true;
11336   }
11337   case Intrinsic::arm_ldaex:
11338   case Intrinsic::arm_ldrex: {
11339     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11340     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11341     Info.opc = ISD::INTRINSIC_W_CHAIN;
11342     Info.memVT = MVT::getVT(PtrTy->getElementType());
11343     Info.ptrVal = I.getArgOperand(0);
11344     Info.offset = 0;
11345     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11346     Info.vol = true;
11347     Info.readMem = true;
11348     Info.writeMem = false;
11349     return true;
11350   }
11351   case Intrinsic::arm_stlex:
11352   case Intrinsic::arm_strex: {
11353     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11354     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11355     Info.opc = ISD::INTRINSIC_W_CHAIN;
11356     Info.memVT = MVT::getVT(PtrTy->getElementType());
11357     Info.ptrVal = I.getArgOperand(1);
11358     Info.offset = 0;
11359     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11360     Info.vol = true;
11361     Info.readMem = false;
11362     Info.writeMem = true;
11363     return true;
11364   }
11365   case Intrinsic::arm_stlexd:
11366   case Intrinsic::arm_strexd: {
11367     Info.opc = ISD::INTRINSIC_W_CHAIN;
11368     Info.memVT = MVT::i64;
11369     Info.ptrVal = I.getArgOperand(2);
11370     Info.offset = 0;
11371     Info.align = 8;
11372     Info.vol = true;
11373     Info.readMem = false;
11374     Info.writeMem = true;
11375     return true;
11376   }
11377   case Intrinsic::arm_ldaexd:
11378   case Intrinsic::arm_ldrexd: {
11379     Info.opc = ISD::INTRINSIC_W_CHAIN;
11380     Info.memVT = MVT::i64;
11381     Info.ptrVal = I.getArgOperand(0);
11382     Info.offset = 0;
11383     Info.align = 8;
11384     Info.vol = true;
11385     Info.readMem = true;
11386     Info.writeMem = false;
11387     return true;
11388   }
11389   default:
11390     break;
11391   }
11392
11393   return false;
11394 }
11395
11396 /// \brief Returns true if it is beneficial to convert a load of a constant
11397 /// to just the constant itself.
11398 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11399                                                           Type *Ty) const {
11400   assert(Ty->isIntegerTy());
11401
11402   unsigned Bits = Ty->getPrimitiveSizeInBits();
11403   if (Bits == 0 || Bits > 32)
11404     return false;
11405   return true;
11406 }
11407
11408 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11409
11410 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11411                                         ARM_MB::MemBOpt Domain) const {
11412   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11413
11414   // First, if the target has no DMB, see what fallback we can use.
11415   if (!Subtarget->hasDataBarrier()) {
11416     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11417     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11418     // here.
11419     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11420       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11421       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11422                         Builder.getInt32(0), Builder.getInt32(7),
11423                         Builder.getInt32(10), Builder.getInt32(5)};
11424       return Builder.CreateCall(MCR, args);
11425     } else {
11426       // Instead of using barriers, atomic accesses on these subtargets use
11427       // libcalls.
11428       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11429     }
11430   } else {
11431     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11432     // Only a full system barrier exists in the M-class architectures.
11433     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11434     Constant *CDomain = Builder.getInt32(Domain);
11435     return Builder.CreateCall(DMB, CDomain);
11436   }
11437 }
11438
11439 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11440 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11441                                          AtomicOrdering Ord, bool IsStore,
11442                                          bool IsLoad) const {
11443   if (!getInsertFencesForAtomic())
11444     return nullptr;
11445
11446   switch (Ord) {
11447   case NotAtomic:
11448   case Unordered:
11449     llvm_unreachable("Invalid fence: unordered/non-atomic");
11450   case Monotonic:
11451   case Acquire:
11452     return nullptr; // Nothing to do
11453   case SequentiallyConsistent:
11454     if (!IsStore)
11455       return nullptr; // Nothing to do
11456     /*FALLTHROUGH*/
11457   case Release:
11458   case AcquireRelease:
11459     if (Subtarget->isSwift())
11460       return makeDMB(Builder, ARM_MB::ISHST);
11461     // FIXME: add a comment with a link to documentation justifying this.
11462     else
11463       return makeDMB(Builder, ARM_MB::ISH);
11464   }
11465   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11466 }
11467
11468 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11469                                           AtomicOrdering Ord, bool IsStore,
11470                                           bool IsLoad) const {
11471   if (!getInsertFencesForAtomic())
11472     return nullptr;
11473
11474   switch (Ord) {
11475   case NotAtomic:
11476   case Unordered:
11477     llvm_unreachable("Invalid fence: unordered/not-atomic");
11478   case Monotonic:
11479   case Release:
11480     return nullptr; // Nothing to do
11481   case Acquire:
11482   case AcquireRelease:
11483   case SequentiallyConsistent:
11484     return makeDMB(Builder, ARM_MB::ISH);
11485   }
11486   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11487 }
11488
11489 // Loads and stores less than 64-bits are already atomic; ones above that
11490 // are doomed anyway, so defer to the default libcall and blame the OS when
11491 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11492 // anything for those.
11493 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11494   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11495   return (Size == 64) && !Subtarget->isMClass();
11496 }
11497
11498 // Loads and stores less than 64-bits are already atomic; ones above that
11499 // are doomed anyway, so defer to the default libcall and blame the OS when
11500 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11501 // anything for those.
11502 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11503 // guarantee, see DDI0406C ARM architecture reference manual,
11504 // sections A8.8.72-74 LDRD)
11505 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11506   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11507   return (Size == 64) && !Subtarget->isMClass();
11508 }
11509
11510 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11511 // and up to 64 bits on the non-M profiles
11512 TargetLoweringBase::AtomicRMWExpansionKind
11513 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11514   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11515   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11516              ? AtomicRMWExpansionKind::LLSC
11517              : AtomicRMWExpansionKind::None;
11518 }
11519
11520 // This has so far only been implemented for MachO.
11521 bool ARMTargetLowering::useLoadStackGuardNode() const {
11522   return Subtarget->isTargetMachO();
11523 }
11524
11525 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11526                                                   unsigned &Cost) const {
11527   // If we do not have NEON, vector types are not natively supported.
11528   if (!Subtarget->hasNEON())
11529     return false;
11530
11531   // Floating point values and vector values map to the same register file.
11532   // Therefore, althought we could do a store extract of a vector type, this is
11533   // better to leave at float as we have more freedom in the addressing mode for
11534   // those.
11535   if (VectorTy->isFPOrFPVectorTy())
11536     return false;
11537
11538   // If the index is unknown at compile time, this is very expensive to lower
11539   // and it is not possible to combine the store with the extract.
11540   if (!isa<ConstantInt>(Idx))
11541     return false;
11542
11543   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11544   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11545   // We can do a store + vector extract on any vector that fits perfectly in a D
11546   // or Q register.
11547   if (BitWidth == 64 || BitWidth == 128) {
11548     Cost = 0;
11549     return true;
11550   }
11551   return false;
11552 }
11553
11554 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11555                                          AtomicOrdering Ord) const {
11556   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11557   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11558   bool IsAcquire = isAtLeastAcquire(Ord);
11559
11560   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11561   // intrinsic must return {i32, i32} and we have to recombine them into a
11562   // single i64 here.
11563   if (ValTy->getPrimitiveSizeInBits() == 64) {
11564     Intrinsic::ID Int =
11565         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11566     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11567
11568     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11569     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11570
11571     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11572     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11573     if (!Subtarget->isLittle())
11574       std::swap (Lo, Hi);
11575     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11576     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11577     return Builder.CreateOr(
11578         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11579   }
11580
11581   Type *Tys[] = { Addr->getType() };
11582   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11583   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11584
11585   return Builder.CreateTruncOrBitCast(
11586       Builder.CreateCall(Ldrex, Addr),
11587       cast<PointerType>(Addr->getType())->getElementType());
11588 }
11589
11590 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11591                                                Value *Addr,
11592                                                AtomicOrdering Ord) const {
11593   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11594   bool IsRelease = isAtLeastRelease(Ord);
11595
11596   // Since the intrinsics must have legal type, the i64 intrinsics take two
11597   // parameters: "i32, i32". We must marshal Val into the appropriate form
11598   // before the call.
11599   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11600     Intrinsic::ID Int =
11601         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11602     Function *Strex = Intrinsic::getDeclaration(M, Int);
11603     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11604
11605     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11606     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11607     if (!Subtarget->isLittle())
11608       std::swap (Lo, Hi);
11609     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11610     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11611   }
11612
11613   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11614   Type *Tys[] = { Addr->getType() };
11615   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11616
11617   return Builder.CreateCall(
11618       Strex, {Builder.CreateZExtOrBitCast(
11619                   Val, Strex->getFunctionType()->getParamType(0)),
11620               Addr});
11621 }
11622
11623 /// \brief Lower an interleaved load into a vldN intrinsic.
11624 ///
11625 /// E.g. Lower an interleaved load (Factor = 2):
11626 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11627 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11628 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11629 ///
11630 ///      Into:
11631 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11632 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11633 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11634 bool ARMTargetLowering::lowerInterleavedLoad(
11635     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11636     ArrayRef<unsigned> Indices, unsigned Factor) const {
11637   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11638          "Invalid interleave factor");
11639   assert(!Shuffles.empty() && "Empty shufflevector input");
11640   assert(Shuffles.size() == Indices.size() &&
11641          "Unmatched number of shufflevectors and indices");
11642
11643   VectorType *VecTy = Shuffles[0]->getType();
11644   Type *EltTy = VecTy->getVectorElementType();
11645
11646   const DataLayout &DL = LI->getModule()->getDataLayout();
11647   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11648   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11649
11650   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11651   // support i64/f64 element).
11652   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11653     return false;
11654
11655   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11656   // load integer vectors first and then convert to pointer vectors.
11657   if (EltTy->isPointerTy())
11658     VecTy =
11659         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11660
11661   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11662                                             Intrinsic::arm_neon_vld3,
11663                                             Intrinsic::arm_neon_vld4};
11664
11665   Function *VldnFunc =
11666       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11667
11668   IRBuilder<> Builder(LI);
11669   SmallVector<Value *, 2> Ops;
11670
11671   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11672   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11673   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11674
11675   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11676
11677   // Replace uses of each shufflevector with the corresponding vector loaded
11678   // by ldN.
11679   for (unsigned i = 0; i < Shuffles.size(); i++) {
11680     ShuffleVectorInst *SV = Shuffles[i];
11681     unsigned Index = Indices[i];
11682
11683     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11684
11685     // Convert the integer vector to pointer vector if the element is pointer.
11686     if (EltTy->isPointerTy())
11687       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11688
11689     SV->replaceAllUsesWith(SubVec);
11690   }
11691
11692   return true;
11693 }
11694
11695 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11696 ///
11697 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11698 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11699                                    unsigned NumElts) {
11700   SmallVector<Constant *, 16> Mask;
11701   for (unsigned i = 0; i < NumElts; i++)
11702     Mask.push_back(Builder.getInt32(Start + i));
11703
11704   return ConstantVector::get(Mask);
11705 }
11706
11707 /// \brief Lower an interleaved store into a vstN intrinsic.
11708 ///
11709 /// E.g. Lower an interleaved store (Factor = 3):
11710 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11711 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11712 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11713 ///
11714 ///      Into:
11715 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11716 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11717 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11718 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11719 ///
11720 /// Note that the new shufflevectors will be removed and we'll only generate one
11721 /// vst3 instruction in CodeGen.
11722 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11723                                               ShuffleVectorInst *SVI,
11724                                               unsigned Factor) const {
11725   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11726          "Invalid interleave factor");
11727
11728   VectorType *VecTy = SVI->getType();
11729   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11730          "Invalid interleaved store");
11731
11732   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11733   Type *EltTy = VecTy->getVectorElementType();
11734   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11735
11736   const DataLayout &DL = SI->getModule()->getDataLayout();
11737   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11738   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11739
11740   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11741   // doesn't support i64/f64 element).
11742   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11743     return false;
11744
11745   Value *Op0 = SVI->getOperand(0);
11746   Value *Op1 = SVI->getOperand(1);
11747   IRBuilder<> Builder(SI);
11748
11749   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11750   // vectors to integer vectors.
11751   if (EltTy->isPointerTy()) {
11752     Type *IntTy = DL.getIntPtrType(EltTy);
11753
11754     // Convert to the corresponding integer vector.
11755     Type *IntVecTy =
11756         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11757     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11758     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11759
11760     SubVecTy = VectorType::get(IntTy, NumSubElts);
11761   }
11762
11763   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11764                                        Intrinsic::arm_neon_vst3,
11765                                        Intrinsic::arm_neon_vst4};
11766   Function *VstNFunc = Intrinsic::getDeclaration(
11767       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11768
11769   SmallVector<Value *, 6> Ops;
11770
11771   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11772   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11773
11774   // Split the shufflevector operands into sub vectors for the new vstN call.
11775   for (unsigned i = 0; i < Factor; i++)
11776     Ops.push_back(Builder.CreateShuffleVector(
11777         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11778
11779   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11780   Builder.CreateCall(VstNFunc, Ops);
11781   return true;
11782 }
11783
11784 enum HABaseType {
11785   HA_UNKNOWN = 0,
11786   HA_FLOAT,
11787   HA_DOUBLE,
11788   HA_VECT64,
11789   HA_VECT128
11790 };
11791
11792 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11793                                    uint64_t &Members) {
11794   if (auto *ST = dyn_cast<StructType>(Ty)) {
11795     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11796       uint64_t SubMembers = 0;
11797       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11798         return false;
11799       Members += SubMembers;
11800     }
11801   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11802     uint64_t SubMembers = 0;
11803     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11804       return false;
11805     Members += SubMembers * AT->getNumElements();
11806   } else if (Ty->isFloatTy()) {
11807     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11808       return false;
11809     Members = 1;
11810     Base = HA_FLOAT;
11811   } else if (Ty->isDoubleTy()) {
11812     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11813       return false;
11814     Members = 1;
11815     Base = HA_DOUBLE;
11816   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11817     Members = 1;
11818     switch (Base) {
11819     case HA_FLOAT:
11820     case HA_DOUBLE:
11821       return false;
11822     case HA_VECT64:
11823       return VT->getBitWidth() == 64;
11824     case HA_VECT128:
11825       return VT->getBitWidth() == 128;
11826     case HA_UNKNOWN:
11827       switch (VT->getBitWidth()) {
11828       case 64:
11829         Base = HA_VECT64;
11830         return true;
11831       case 128:
11832         Base = HA_VECT128;
11833         return true;
11834       default:
11835         return false;
11836       }
11837     }
11838   }
11839
11840   return (Members > 0 && Members <= 4);
11841 }
11842
11843 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11844 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11845 /// passing according to AAPCS rules.
11846 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11847     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11848   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11849       CallingConv::ARM_AAPCS_VFP)
11850     return false;
11851
11852   HABaseType Base = HA_UNKNOWN;
11853   uint64_t Members = 0;
11854   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11855   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11856
11857   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11858   return IsHA || IsIntArray;
11859 }