[ARM] Move the store combiner function down. NFC.
[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/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "arm-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59
60 cl::opt<bool>
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62   cl::desc("Generate calls via indirect call instructions"),
63   cl::init(false));
64
65 static cl::opt<bool>
66 ARMInterworking("arm-interworking", cl::Hidden,
67   cl::desc("Enable / disable ARM interworking (for debugging only)"),
68   cl::init(true));
69
70 namespace {
71   class ARMCCState : public CCState {
72   public:
73     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75                ParmContext PC)
76         : CCState(CC, isVarArg, MF, locs, C) {
77       assert(((PC == Call) || (PC == Prologue)) &&
78              "ARMCCState users must specify whether their context is call"
79              "or prologue generation.");
80       CallOrPrologue = PC;
81     }
82   };
83 }
84
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87   ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 };
89
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91                                        MVT PromotedBitwiseVT) {
92   if (VT != PromotedLdStVT) {
93     setOperationAction(ISD::LOAD, VT, Promote);
94     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95
96     setOperationAction(ISD::STORE, VT, Promote);
97     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98   }
99
100   MVT ElemTy = VT.getVectorElementType();
101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102     setOperationAction(ISD::SETCC, VT, Custom);
103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105   if (ElemTy == MVT::i32) {
106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110   } else {
111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115   }
116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120   setOperationAction(ISD::SELECT,            VT, Expand);
121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
122   setOperationAction(ISD::VSELECT,           VT, Expand);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124   if (VT.isInteger()) {
125     setOperationAction(ISD::SHL, VT, Custom);
126     setOperationAction(ISD::SRA, VT, Custom);
127     setOperationAction(ISD::SRL, VT, Custom);
128   }
129
130   // Promote all bit-wise operations.
131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
132     setOperationAction(ISD::AND, VT, Promote);
133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134     setOperationAction(ISD::OR,  VT, Promote);
135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
136     setOperationAction(ISD::XOR, VT, Promote);
137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138   }
139
140   // Neon does not support vector divide/remainder operations.
141   setOperationAction(ISD::SDIV, VT, Expand);
142   setOperationAction(ISD::UDIV, VT, Expand);
143   setOperationAction(ISD::FDIV, VT, Expand);
144   setOperationAction(ISD::SREM, VT, Expand);
145   setOperationAction(ISD::UREM, VT, Expand);
146   setOperationAction(ISD::FREM, VT, Expand);
147 }
148
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150   addRegisterClass(VT, &ARM::DPRRegClass);
151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 }
153
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155   addRegisterClass(VT, &ARM::DPairRegClass);
156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 }
158
159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM)
160     : TargetLowering(TM) {
161   Subtarget = &TM.getSubtarget<ARMSubtarget>();
162   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
163   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
164
165   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
166
167   if (Subtarget->isTargetMachO()) {
168     // Uses VFP for Thumb libfuncs if available.
169     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
170         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
171       // Single-precision floating-point arithmetic.
172       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
173       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
174       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
175       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
176
177       // Double-precision floating-point arithmetic.
178       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
179       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
180       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
181       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
182
183       // Single-precision comparisons.
184       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
185       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
186       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
187       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
188       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
189       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
190       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
191       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
192
193       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
194       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
195       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
196       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
200       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
201
202       // Double-precision comparisons.
203       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
204       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
205       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
206       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
207       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
208       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
209       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
210       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
211
212       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
214       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
215       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
219       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
220
221       // Floating-point to integer conversions.
222       // i64 conversions are done via library routines even when generating VFP
223       // instructions, so use the same ones.
224       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
225       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
226       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
227       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
228
229       // Conversions between floating types.
230       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
231       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
232
233       // Integer to floating-point conversions.
234       // i64 conversions are done via library routines even when generating VFP
235       // instructions, so use the same ones.
236       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
237       // e.g., __floatunsidf vs. __floatunssidfvfp.
238       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
239       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
240       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
241       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
242     }
243   }
244
245   // These libcalls are not available in 32-bit.
246   setLibcallName(RTLIB::SHL_I128, nullptr);
247   setLibcallName(RTLIB::SRL_I128, nullptr);
248   setLibcallName(RTLIB::SRA_I128, nullptr);
249
250   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
251       !Subtarget->isTargetWindows()) {
252     static const struct {
253       const RTLIB::Libcall Op;
254       const char * const Name;
255       const CallingConv::ID CC;
256       const ISD::CondCode Cond;
257     } LibraryCalls[] = {
258       // Double-precision floating-point arithmetic helper functions
259       // RTABI chapter 4.1.2, Table 2
260       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264
265       // Double-precision floating-point comparison helper functions
266       // RTABI chapter 4.1.2, Table 3
267       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
269       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
275
276       // Single-precision floating-point arithmetic helper functions
277       // RTABI chapter 4.1.2, Table 4
278       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282
283       // Single-precision floating-point comparison helper functions
284       // RTABI chapter 4.1.2, Table 5
285       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
287       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
293
294       // Floating-point to integer conversions.
295       // RTABI chapter 4.1.2, Table 6
296       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304
305       // Conversions between floating types.
306       // RTABI chapter 4.1.2, Table 7
307       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310
311       // Integer to floating-point conversions.
312       // RTABI chapter 4.1.2, Table 8
313       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321
322       // Long long helper functions
323       // RTABI chapter 4.2, Table 9
324       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328
329       // Integer division functions
330       // RTABI chapter 4.3.1
331       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339
340       // Memory operations
341       // RTABI chapter 4.3.4
342       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345     };
346
347     for (const auto &LC : LibraryCalls) {
348       setLibcallName(LC.Op, LC.Name);
349       setLibcallCallingConv(LC.Op, LC.CC);
350       if (LC.Cond != ISD::SETCC_INVALID)
351         setCmpLibcallCC(LC.Op, LC.Cond);
352     }
353   }
354
355   if (Subtarget->isTargetWindows()) {
356     static const struct {
357       const RTLIB::Libcall Op;
358       const char * const Name;
359       const CallingConv::ID CC;
360     } LibraryCalls[] = {
361       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
369     };
370
371     for (const auto &LC : LibraryCalls) {
372       setLibcallName(LC.Op, LC.Name);
373       setLibcallCallingConv(LC.Op, LC.CC);
374     }
375   }
376
377   // Use divmod compiler-rt calls for iOS 5.0 and later.
378   if (Subtarget->getTargetTriple().isiOS() &&
379       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
380     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
381     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
382   }
383
384   // The half <-> float conversion functions are always soft-float, but are
385   // needed for some targets which use a hard-float calling convention by
386   // default.
387   if (Subtarget->isAAPCS_ABI()) {
388     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
391   } else {
392     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
393     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
394     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
395   }
396
397   if (Subtarget->isThumb1Only())
398     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
399   else
400     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
401   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
402       !Subtarget->isThumb1Only()) {
403     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
404     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
405   }
406
407   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
408        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
409     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
410          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
411       setTruncStoreAction((MVT::SimpleValueType)VT,
412                           (MVT::SimpleValueType)InnerVT, Expand);
413     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
414     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
415     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
416
417     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
419     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
421
422     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   if (Subtarget->hasNEON()) {
429     addDRTypeForNEON(MVT::v2f32);
430     addDRTypeForNEON(MVT::v8i8);
431     addDRTypeForNEON(MVT::v4i16);
432     addDRTypeForNEON(MVT::v2i32);
433     addDRTypeForNEON(MVT::v1i64);
434
435     addQRTypeForNEON(MVT::v4f32);
436     addQRTypeForNEON(MVT::v2f64);
437     addQRTypeForNEON(MVT::v16i8);
438     addQRTypeForNEON(MVT::v8i16);
439     addQRTypeForNEON(MVT::v4i32);
440     addQRTypeForNEON(MVT::v2i64);
441
442     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
443     // neither Neon nor VFP support any arithmetic operations on it.
444     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
445     // supported for v4f32.
446     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
447     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
448     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
449     // FIXME: Code duplication: FDIV and FREM are expanded always, see
450     // ARMTargetLowering::addTypeForNEON method for details.
451     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
452     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
453     // FIXME: Create unittest.
454     // In another words, find a way when "copysign" appears in DAG with vector
455     // operands.
456     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
457     // FIXME: Code duplication: SETCC has custom operation action, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
460     // FIXME: Create unittest for FNEG and for FABS.
461     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
462     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
463     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
464     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
465     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
467     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
469     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
470     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
471     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
472     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
473     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
474     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
475     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
476     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
477     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
478     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
480
481     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
482     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
483     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
484     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
485     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
487     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
488     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
489     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
490     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
492     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
493     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
494     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
495     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
496
497     // Mark v2f32 intrinsics.
498     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
499     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
500     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
501     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
502     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
504     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
505     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
506     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
507     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
509     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
510     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
511     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
512     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
513
514     // Neon does not support some operations on v1i64 and v2i64 types.
515     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
516     // Custom handling for some quad-vector types to detect VMULL.
517     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
518     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
519     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
520     // Custom handling for some vector types to avoid expensive expansions
521     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
522     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
523     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
524     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
525     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
526     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
527     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
528     // a destination type that is wider than the source, and nor does
529     // it have a FP_TO_[SU]INT instruction with a narrower destination than
530     // source.
531     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
532     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
533     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
534     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
535
536     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
537     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
538
539     // NEON does not have single instruction CTPOP for vectors with element
540     // types wider than 8-bits.  However, custom lowering can leverage the
541     // v8i8/v16i8 vcnt instruction.
542     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
544     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
545     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
546
547     // NEON only has FMA instructions as of VFP4.
548     if (!Subtarget->hasVFP4()) {
549       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
550       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
551     }
552
553     setTargetDAGCombine(ISD::INTRINSIC_VOID);
554     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
555     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
556     setTargetDAGCombine(ISD::SHL);
557     setTargetDAGCombine(ISD::SRL);
558     setTargetDAGCombine(ISD::SRA);
559     setTargetDAGCombine(ISD::SIGN_EXTEND);
560     setTargetDAGCombine(ISD::ZERO_EXTEND);
561     setTargetDAGCombine(ISD::ANY_EXTEND);
562     setTargetDAGCombine(ISD::SELECT_CC);
563     setTargetDAGCombine(ISD::BUILD_VECTOR);
564     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
565     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
566     setTargetDAGCombine(ISD::STORE);
567     setTargetDAGCombine(ISD::FP_TO_SINT);
568     setTargetDAGCombine(ISD::FP_TO_UINT);
569     setTargetDAGCombine(ISD::FDIV);
570
571     // It is legal to extload from v4i8 to v4i16 or v4i32.
572     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
573                   MVT::v4i16, MVT::v2i16,
574                   MVT::v2i32};
575     for (unsigned i = 0; i < 6; ++i) {
576       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
577       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
578       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
579     }
580   }
581
582   // ARM and Thumb2 support UMLAL/SMLAL.
583   if (!Subtarget->isThumb1Only())
584     setTargetDAGCombine(ISD::ADDC);
585
586   if (Subtarget->isFPOnlySP()) {
587     // When targetting a floating-point unit with only single-precision
588     // operations, f64 is legal for the few double-precision instructions which
589     // are present However, no double-precision operations other than moves,
590     // loads and stores are provided by the hardware.
591     setOperationAction(ISD::FADD,       MVT::f64, Expand);
592     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
593     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
594     setOperationAction(ISD::FMA,        MVT::f64, Expand);
595     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
596     setOperationAction(ISD::FREM,       MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
598     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
599     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
600     setOperationAction(ISD::FABS,       MVT::f64, Expand);
601     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
602     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
603     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
604     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
605     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
606     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
608     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
609     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
610     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
611     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
612     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
613     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
614     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
615     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
616     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
617     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
618   }
619
620   computeRegisterProperties();
621
622   // ARM does not have floating-point extending loads.
623   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
624   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
625
626   // ... or truncating stores
627   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
628   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
629   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
630
631   // ARM does not have i1 sign extending load.
632   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
633
634   // ARM supports all 4 flavors of integer indexed load / store.
635   if (!Subtarget->isThumb1Only()) {
636     for (unsigned im = (unsigned)ISD::PRE_INC;
637          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
638       setIndexedLoadAction(im,  MVT::i1,  Legal);
639       setIndexedLoadAction(im,  MVT::i8,  Legal);
640       setIndexedLoadAction(im,  MVT::i16, Legal);
641       setIndexedLoadAction(im,  MVT::i32, Legal);
642       setIndexedStoreAction(im, MVT::i1,  Legal);
643       setIndexedStoreAction(im, MVT::i8,  Legal);
644       setIndexedStoreAction(im, MVT::i16, Legal);
645       setIndexedStoreAction(im, MVT::i32, Legal);
646     }
647   }
648
649   setOperationAction(ISD::SADDO, MVT::i32, Custom);
650   setOperationAction(ISD::UADDO, MVT::i32, Custom);
651   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
652   setOperationAction(ISD::USUBO, MVT::i32, Custom);
653
654   // i64 operation support.
655   setOperationAction(ISD::MUL,     MVT::i64, Expand);
656   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
657   if (Subtarget->isThumb1Only()) {
658     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
659     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
660   }
661   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
662       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
663     setOperationAction(ISD::MULHS, MVT::i32, Expand);
664
665   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
666   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
667   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
668   setOperationAction(ISD::SRL,       MVT::i64, Custom);
669   setOperationAction(ISD::SRA,       MVT::i64, Custom);
670
671   if (!Subtarget->isThumb1Only()) {
672     // FIXME: We should do this for Thumb1 as well.
673     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
674     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
675     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
676     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
677   }
678
679   // ARM does not have ROTL.
680   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
681   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
682   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
683   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
684     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
685
686   // These just redirect to CTTZ and CTLZ on ARM.
687   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
688   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
689
690   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
691
692   // Only ARMv6 has BSWAP.
693   if (!Subtarget->hasV6Ops())
694     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
695
696   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
697       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
698     // These are expanded into libcalls if the cpu doesn't have HW divider.
699     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
700     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
701   }
702
703   // FIXME: Also set divmod for SREM on EABI
704   setOperationAction(ISD::SREM,  MVT::i32, Expand);
705   setOperationAction(ISD::UREM,  MVT::i32, Expand);
706   // Register based DivRem for AEABI (RTABI 4.2)
707   if (Subtarget->isTargetAEABI()) {
708     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
709     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
710     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
711     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
712     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
713     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
714     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
715     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
716
717     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
718     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
719     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
720     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
721     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
725
726     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
727     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
728   } else {
729     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
730     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
731   }
732
733   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
734   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
735   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
736   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
737   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
738
739   setOperationAction(ISD::TRAP, MVT::Other, Legal);
740
741   // Use the default implementation.
742   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
743   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
744   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
745   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
746   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
747   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
748
749   if (!Subtarget->isTargetMachO()) {
750     // Non-MachO platforms may return values in these registers via the
751     // personality function.
752     setExceptionPointerRegister(ARM::R0);
753     setExceptionSelectorRegister(ARM::R1);
754   }
755
756   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
757     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
758   else
759     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
760
761   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
762   // the default expansion. If we are targeting a single threaded system,
763   // then set them all for expand so we can lower them later into their
764   // non-atomic form.
765   if (TM.Options.ThreadModel == ThreadModel::Single)
766     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
767   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
768     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
769     // to ldrex/strex loops already.
770     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
771
772     // On v8, we have particularly efficient implementations of atomic fences
773     // if they can be combined with nearby atomic loads and stores.
774     if (!Subtarget->hasV8Ops()) {
775       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
776       setInsertFencesForAtomic(true);
777     }
778   } else {
779     // If there's anything we can use as a barrier, go through custom lowering
780     // for ATOMIC_FENCE.
781     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
782                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
783
784     // Set them all for expansion, which will force libcalls.
785     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
786     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
787     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
788     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
789     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
797     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
798     // Unordered/Monotonic case.
799     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
800     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
801   }
802
803   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
804
805   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
806   if (!Subtarget->hasV6Ops()) {
807     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
808     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
809   }
810   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
811
812   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
813       !Subtarget->isThumb1Only()) {
814     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
815     // iff target supports vfp2.
816     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
817     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
818   }
819
820   // We want to custom lower some of our intrinsics.
821   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
822   if (Subtarget->isTargetDarwin()) {
823     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
824     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
825     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
826   }
827
828   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
829   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
830   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
831   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
832   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
833   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
834   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
835   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
836   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
837
838   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
839   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
840   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
841   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
842   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
843
844   // We don't support sin/cos/fmod/copysign/pow
845   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
846   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
847   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
848   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
849   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
850   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
851   setOperationAction(ISD::FREM,      MVT::f64, Expand);
852   setOperationAction(ISD::FREM,      MVT::f32, Expand);
853   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
854       !Subtarget->isThumb1Only()) {
855     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
856     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
857   }
858   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
859   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
860
861   if (!Subtarget->hasVFP4()) {
862     setOperationAction(ISD::FMA, MVT::f64, Expand);
863     setOperationAction(ISD::FMA, MVT::f32, Expand);
864   }
865
866   // Various VFP goodness
867   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
868     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
869     if (Subtarget->hasVFP2()) {
870       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
871       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
872       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
873       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
874     }
875
876     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
877     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
878       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
879       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
880     }
881
882     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
883     if (!Subtarget->hasFP16()) {
884       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
885       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
886     }
887   }
888
889   // Combine sin / cos into one node or libcall if possible.
890   if (Subtarget->hasSinCos()) {
891     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
892     setLibcallName(RTLIB::SINCOS_F64, "sincos");
893     if (Subtarget->getTargetTriple().isiOS()) {
894       // For iOS, we don't want to the normal expansion of a libcall to
895       // sincos. We want to issue a libcall to __sincos_stret.
896       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
897       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
898     }
899   }
900
901   // FP-ARMv8 implements a lot of rounding-like FP operations.
902   if (Subtarget->hasFPARMv8()) {
903     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
904     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
905     setOperationAction(ISD::FROUND, MVT::f32, Legal);
906     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
907     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
908     setOperationAction(ISD::FRINT, MVT::f32, Legal);
909     if (!Subtarget->isFPOnlySP()) {
910       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
911       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
912       setOperationAction(ISD::FROUND, MVT::f64, Legal);
913       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
914       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
915       setOperationAction(ISD::FRINT, MVT::f64, Legal);
916     }
917   }
918   // We have target-specific dag combine patterns for the following nodes:
919   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
920   setTargetDAGCombine(ISD::ADD);
921   setTargetDAGCombine(ISD::SUB);
922   setTargetDAGCombine(ISD::MUL);
923   setTargetDAGCombine(ISD::AND);
924   setTargetDAGCombine(ISD::OR);
925   setTargetDAGCombine(ISD::XOR);
926
927   if (Subtarget->hasV6Ops())
928     setTargetDAGCombine(ISD::SRL);
929
930   setStackPointerRegisterToSaveRestore(ARM::SP);
931
932   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
933       !Subtarget->hasVFP2())
934     setSchedulingPreference(Sched::RegPressure);
935   else
936     setSchedulingPreference(Sched::Hybrid);
937
938   //// temporary - rewrite interface to use type
939   MaxStoresPerMemset = 8;
940   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
941   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
942   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
943   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
944   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
945
946   // On ARM arguments smaller than 4 bytes are extended, so all arguments
947   // are at least 4 bytes aligned.
948   setMinStackArgumentAlignment(4);
949
950   // Prefer likely predicted branches to selects on out-of-order cores.
951   PredictableSelectIsExpensive = Subtarget->isLikeA9();
952
953   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
954 }
955
956 // FIXME: It might make sense to define the representative register class as the
957 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
958 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
959 // SPR's representative would be DPR_VFP2. This should work well if register
960 // pressure tracking were modified such that a register use would increment the
961 // pressure of the register class's representative and all of it's super
962 // classes' representatives transitively. We have not implemented this because
963 // of the difficulty prior to coalescing of modeling operand register classes
964 // due to the common occurrence of cross class copies and subregister insertions
965 // and extractions.
966 std::pair<const TargetRegisterClass*, uint8_t>
967 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
968   const TargetRegisterClass *RRC = nullptr;
969   uint8_t Cost = 1;
970   switch (VT.SimpleTy) {
971   default:
972     return TargetLowering::findRepresentativeClass(VT);
973   // Use DPR as representative register class for all floating point
974   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
975   // the cost is 1 for both f32 and f64.
976   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
977   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
978     RRC = &ARM::DPRRegClass;
979     // When NEON is used for SP, only half of the register file is available
980     // because operations that define both SP and DP results will be constrained
981     // to the VFP2 class (D0-D15). We currently model this constraint prior to
982     // coalescing by double-counting the SP regs. See the FIXME above.
983     if (Subtarget->useNEONForSinglePrecisionFP())
984       Cost = 2;
985     break;
986   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
987   case MVT::v4f32: case MVT::v2f64:
988     RRC = &ARM::DPRRegClass;
989     Cost = 2;
990     break;
991   case MVT::v4i64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 4;
994     break;
995   case MVT::v8i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 8;
998     break;
999   }
1000   return std::make_pair(RRC, Cost);
1001 }
1002
1003 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1004   switch (Opcode) {
1005   default: return nullptr;
1006   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1007   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1008   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1009   case ARMISD::CALL:          return "ARMISD::CALL";
1010   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1011   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1012   case ARMISD::tCALL:         return "ARMISD::tCALL";
1013   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1014   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1015   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1016   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1017   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1018   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1019   case ARMISD::CMP:           return "ARMISD::CMP";
1020   case ARMISD::CMN:           return "ARMISD::CMN";
1021   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1022   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1023   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1024   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1025   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1026
1027   case ARMISD::CMOV:          return "ARMISD::CMOV";
1028
1029   case ARMISD::RBIT:          return "ARMISD::RBIT";
1030
1031   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1032   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1033   case ARMISD::SITOF:         return "ARMISD::SITOF";
1034   case ARMISD::UITOF:         return "ARMISD::UITOF";
1035
1036   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1037   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1038   case ARMISD::RRX:           return "ARMISD::RRX";
1039
1040   case ARMISD::ADDC:          return "ARMISD::ADDC";
1041   case ARMISD::ADDE:          return "ARMISD::ADDE";
1042   case ARMISD::SUBC:          return "ARMISD::SUBC";
1043   case ARMISD::SUBE:          return "ARMISD::SUBE";
1044
1045   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1046   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1047
1048   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1049   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1050
1051   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1052
1053   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1054
1055   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1056
1057   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1058
1059   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1060
1061   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1062
1063   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1064   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1065   case ARMISD::VCGE:          return "ARMISD::VCGE";
1066   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1067   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1068   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1069   case ARMISD::VCGT:          return "ARMISD::VCGT";
1070   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1071   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1072   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1073   case ARMISD::VTST:          return "ARMISD::VTST";
1074
1075   case ARMISD::VSHL:          return "ARMISD::VSHL";
1076   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1077   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1078   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1079   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1080   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1081   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1082   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1083   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1084   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1085   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1086   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1087   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1088   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1089   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1090   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1091   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1092   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1093   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1094   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1095   case ARMISD::VDUP:          return "ARMISD::VDUP";
1096   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1097   case ARMISD::VEXT:          return "ARMISD::VEXT";
1098   case ARMISD::VREV64:        return "ARMISD::VREV64";
1099   case ARMISD::VREV32:        return "ARMISD::VREV32";
1100   case ARMISD::VREV16:        return "ARMISD::VREV16";
1101   case ARMISD::VZIP:          return "ARMISD::VZIP";
1102   case ARMISD::VUZP:          return "ARMISD::VUZP";
1103   case ARMISD::VTRN:          return "ARMISD::VTRN";
1104   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1105   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1106   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1107   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1108   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1109   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1110   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1111   case ARMISD::FMAX:          return "ARMISD::FMAX";
1112   case ARMISD::FMIN:          return "ARMISD::FMIN";
1113   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1114   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1115   case ARMISD::BFI:           return "ARMISD::BFI";
1116   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1117   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1118   case ARMISD::VBSL:          return "ARMISD::VBSL";
1119   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1120   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1121   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1122   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1123   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1124   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1125   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1126   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1127   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1128   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1129   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1130   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1131   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1132   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1133   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1134   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1135   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1136   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1137   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1138   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1139   }
1140 }
1141
1142 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1143   if (!VT.isVector()) return getPointerTy();
1144   return VT.changeVectorElementTypeToInteger();
1145 }
1146
1147 /// getRegClassFor - Return the register class that should be used for the
1148 /// specified value type.
1149 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1150   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1151   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1152   // load / store 4 to 8 consecutive D registers.
1153   if (Subtarget->hasNEON()) {
1154     if (VT == MVT::v4i64)
1155       return &ARM::QQPRRegClass;
1156     if (VT == MVT::v8i64)
1157       return &ARM::QQQQPRRegClass;
1158   }
1159   return TargetLowering::getRegClassFor(VT);
1160 }
1161
1162 // Create a fast isel object.
1163 FastISel *
1164 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1165                                   const TargetLibraryInfo *libInfo) const {
1166   return ARM::createFastISel(funcInfo, libInfo);
1167 }
1168
1169 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1170 /// be used for loads / stores from the global.
1171 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1172   return (Subtarget->isThumb1Only() ? 127 : 4095);
1173 }
1174
1175 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1176   unsigned NumVals = N->getNumValues();
1177   if (!NumVals)
1178     return Sched::RegPressure;
1179
1180   for (unsigned i = 0; i != NumVals; ++i) {
1181     EVT VT = N->getValueType(i);
1182     if (VT == MVT::Glue || VT == MVT::Other)
1183       continue;
1184     if (VT.isFloatingPoint() || VT.isVector())
1185       return Sched::ILP;
1186   }
1187
1188   if (!N->isMachineOpcode())
1189     return Sched::RegPressure;
1190
1191   // Load are scheduled for latency even if there instruction itinerary
1192   // is not available.
1193   const TargetInstrInfo *TII =
1194       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1195   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1196
1197   if (MCID.getNumDefs() == 0)
1198     return Sched::RegPressure;
1199   if (!Itins->isEmpty() &&
1200       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1201     return Sched::ILP;
1202
1203   return Sched::RegPressure;
1204 }
1205
1206 //===----------------------------------------------------------------------===//
1207 // Lowering Code
1208 //===----------------------------------------------------------------------===//
1209
1210 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1211 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1212   switch (CC) {
1213   default: llvm_unreachable("Unknown condition code!");
1214   case ISD::SETNE:  return ARMCC::NE;
1215   case ISD::SETEQ:  return ARMCC::EQ;
1216   case ISD::SETGT:  return ARMCC::GT;
1217   case ISD::SETGE:  return ARMCC::GE;
1218   case ISD::SETLT:  return ARMCC::LT;
1219   case ISD::SETLE:  return ARMCC::LE;
1220   case ISD::SETUGT: return ARMCC::HI;
1221   case ISD::SETUGE: return ARMCC::HS;
1222   case ISD::SETULT: return ARMCC::LO;
1223   case ISD::SETULE: return ARMCC::LS;
1224   }
1225 }
1226
1227 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1228 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1229                         ARMCC::CondCodes &CondCode2) {
1230   CondCode2 = ARMCC::AL;
1231   switch (CC) {
1232   default: llvm_unreachable("Unknown FP condition!");
1233   case ISD::SETEQ:
1234   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1235   case ISD::SETGT:
1236   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1237   case ISD::SETGE:
1238   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1239   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1240   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1241   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1242   case ISD::SETO:   CondCode = ARMCC::VC; break;
1243   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1244   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1245   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1246   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1247   case ISD::SETLT:
1248   case ISD::SETULT: CondCode = ARMCC::LT; break;
1249   case ISD::SETLE:
1250   case ISD::SETULE: CondCode = ARMCC::LE; break;
1251   case ISD::SETNE:
1252   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1253   }
1254 }
1255
1256 //===----------------------------------------------------------------------===//
1257 //                      Calling Convention Implementation
1258 //===----------------------------------------------------------------------===//
1259
1260 #include "ARMGenCallingConv.inc"
1261
1262 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1263 /// account presence of floating point hardware and calling convention
1264 /// limitations, such as support for variadic functions.
1265 CallingConv::ID
1266 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1267                                            bool isVarArg) const {
1268   switch (CC) {
1269   default:
1270     llvm_unreachable("Unsupported calling convention");
1271   case CallingConv::ARM_AAPCS:
1272   case CallingConv::ARM_APCS:
1273   case CallingConv::GHC:
1274     return CC;
1275   case CallingConv::ARM_AAPCS_VFP:
1276     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1277   case CallingConv::C:
1278     if (!Subtarget->isAAPCS_ABI())
1279       return CallingConv::ARM_APCS;
1280     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1281              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1282              !isVarArg)
1283       return CallingConv::ARM_AAPCS_VFP;
1284     else
1285       return CallingConv::ARM_AAPCS;
1286   case CallingConv::Fast:
1287     if (!Subtarget->isAAPCS_ABI()) {
1288       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1289         return CallingConv::Fast;
1290       return CallingConv::ARM_APCS;
1291     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292       return CallingConv::ARM_AAPCS_VFP;
1293     else
1294       return CallingConv::ARM_AAPCS;
1295   }
1296 }
1297
1298 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1299 /// CallingConvention.
1300 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1301                                                  bool Return,
1302                                                  bool isVarArg) const {
1303   switch (getEffectiveCallingConv(CC, isVarArg)) {
1304   default:
1305     llvm_unreachable("Unsupported calling convention");
1306   case CallingConv::ARM_APCS:
1307     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1308   case CallingConv::ARM_AAPCS:
1309     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1310   case CallingConv::ARM_AAPCS_VFP:
1311     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1312   case CallingConv::Fast:
1313     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1314   case CallingConv::GHC:
1315     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1316   }
1317 }
1318
1319 /// LowerCallResult - Lower the result values of a call into the
1320 /// appropriate copies out of appropriate physical registers.
1321 SDValue
1322 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1323                                    CallingConv::ID CallConv, bool isVarArg,
1324                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1325                                    SDLoc dl, SelectionDAG &DAG,
1326                                    SmallVectorImpl<SDValue> &InVals,
1327                                    bool isThisReturn, SDValue ThisVal) const {
1328
1329   // Assign locations to each value returned by this call.
1330   SmallVector<CCValAssign, 16> RVLocs;
1331   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1332                     *DAG.getContext(), Call);
1333   CCInfo.AnalyzeCallResult(Ins,
1334                            CCAssignFnForNode(CallConv, /* Return*/ true,
1335                                              isVarArg));
1336
1337   // Copy all of the result registers out of their specified physreg.
1338   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1339     CCValAssign VA = RVLocs[i];
1340
1341     // Pass 'this' value directly from the argument to return value, to avoid
1342     // reg unit interference
1343     if (i == 0 && isThisReturn) {
1344       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1345              "unexpected return calling convention register assignment");
1346       InVals.push_back(ThisVal);
1347       continue;
1348     }
1349
1350     SDValue Val;
1351     if (VA.needsCustom()) {
1352       // Handle f64 or half of a v2f64.
1353       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1354                                       InFlag);
1355       Chain = Lo.getValue(1);
1356       InFlag = Lo.getValue(2);
1357       VA = RVLocs[++i]; // skip ahead to next loc
1358       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1359                                       InFlag);
1360       Chain = Hi.getValue(1);
1361       InFlag = Hi.getValue(2);
1362       if (!Subtarget->isLittle())
1363         std::swap (Lo, Hi);
1364       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1365
1366       if (VA.getLocVT() == MVT::v2f64) {
1367         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1368         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1369                           DAG.getConstant(0, MVT::i32));
1370
1371         VA = RVLocs[++i]; // skip ahead to next loc
1372         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1373         Chain = Lo.getValue(1);
1374         InFlag = Lo.getValue(2);
1375         VA = RVLocs[++i]; // skip ahead to next loc
1376         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1377         Chain = Hi.getValue(1);
1378         InFlag = Hi.getValue(2);
1379         if (!Subtarget->isLittle())
1380           std::swap (Lo, Hi);
1381         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1382         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1383                           DAG.getConstant(1, MVT::i32));
1384       }
1385     } else {
1386       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1387                                InFlag);
1388       Chain = Val.getValue(1);
1389       InFlag = Val.getValue(2);
1390     }
1391
1392     switch (VA.getLocInfo()) {
1393     default: llvm_unreachable("Unknown loc info!");
1394     case CCValAssign::Full: break;
1395     case CCValAssign::BCvt:
1396       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1397       break;
1398     }
1399
1400     InVals.push_back(Val);
1401   }
1402
1403   return Chain;
1404 }
1405
1406 /// LowerMemOpCallTo - Store the argument to the stack.
1407 SDValue
1408 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1409                                     SDValue StackPtr, SDValue Arg,
1410                                     SDLoc dl, SelectionDAG &DAG,
1411                                     const CCValAssign &VA,
1412                                     ISD::ArgFlagsTy Flags) const {
1413   unsigned LocMemOffset = VA.getLocMemOffset();
1414   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1415   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1416   return DAG.getStore(Chain, dl, Arg, PtrOff,
1417                       MachinePointerInfo::getStack(LocMemOffset),
1418                       false, false, 0);
1419 }
1420
1421 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1422                                          SDValue Chain, SDValue &Arg,
1423                                          RegsToPassVector &RegsToPass,
1424                                          CCValAssign &VA, CCValAssign &NextVA,
1425                                          SDValue &StackPtr,
1426                                          SmallVectorImpl<SDValue> &MemOpChains,
1427                                          ISD::ArgFlagsTy Flags) const {
1428
1429   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1430                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1431   unsigned id = Subtarget->isLittle() ? 0 : 1;
1432   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1433
1434   if (NextVA.isRegLoc())
1435     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1436   else {
1437     assert(NextVA.isMemLoc());
1438     if (!StackPtr.getNode())
1439       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1440
1441     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1442                                            dl, DAG, NextVA,
1443                                            Flags));
1444   }
1445 }
1446
1447 /// LowerCall - Lowering a call into a callseq_start <-
1448 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1449 /// nodes.
1450 SDValue
1451 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1452                              SmallVectorImpl<SDValue> &InVals) const {
1453   SelectionDAG &DAG                     = CLI.DAG;
1454   SDLoc &dl                          = CLI.DL;
1455   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1456   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1457   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1458   SDValue Chain                         = CLI.Chain;
1459   SDValue Callee                        = CLI.Callee;
1460   bool &isTailCall                      = CLI.IsTailCall;
1461   CallingConv::ID CallConv              = CLI.CallConv;
1462   bool doesNotRet                       = CLI.DoesNotReturn;
1463   bool isVarArg                         = CLI.IsVarArg;
1464
1465   MachineFunction &MF = DAG.getMachineFunction();
1466   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1467   bool isThisReturn   = false;
1468   bool isSibCall      = false;
1469
1470   // Disable tail calls if they're not supported.
1471   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1472     isTailCall = false;
1473
1474   if (isTailCall) {
1475     // Check if it's really possible to do a tail call.
1476     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1477                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1478                                                    Outs, OutVals, Ins, DAG);
1479     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1480       report_fatal_error("failed to perform tail call elimination on a call "
1481                          "site marked musttail");
1482     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1483     // detected sibcalls.
1484     if (isTailCall) {
1485       ++NumTailCalls;
1486       isSibCall = true;
1487     }
1488   }
1489
1490   // Analyze operands of the call, assigning locations to each operand.
1491   SmallVector<CCValAssign, 16> ArgLocs;
1492   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1493                     *DAG.getContext(), Call);
1494   CCInfo.AnalyzeCallOperands(Outs,
1495                              CCAssignFnForNode(CallConv, /* Return*/ false,
1496                                                isVarArg));
1497
1498   // Get a count of how many bytes are to be pushed on the stack.
1499   unsigned NumBytes = CCInfo.getNextStackOffset();
1500
1501   // For tail calls, memory operands are available in our caller's stack.
1502   if (isSibCall)
1503     NumBytes = 0;
1504
1505   // Adjust the stack pointer for the new arguments...
1506   // These operations are automatically eliminated by the prolog/epilog pass
1507   if (!isSibCall)
1508     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1509                                  dl);
1510
1511   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1512
1513   RegsToPassVector RegsToPass;
1514   SmallVector<SDValue, 8> MemOpChains;
1515
1516   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1517   // of tail call optimization, arguments are handled later.
1518   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1519        i != e;
1520        ++i, ++realArgIdx) {
1521     CCValAssign &VA = ArgLocs[i];
1522     SDValue Arg = OutVals[realArgIdx];
1523     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1524     bool isByVal = Flags.isByVal();
1525
1526     // Promote the value if needed.
1527     switch (VA.getLocInfo()) {
1528     default: llvm_unreachable("Unknown loc info!");
1529     case CCValAssign::Full: break;
1530     case CCValAssign::SExt:
1531       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1532       break;
1533     case CCValAssign::ZExt:
1534       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1535       break;
1536     case CCValAssign::AExt:
1537       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::BCvt:
1540       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1541       break;
1542     }
1543
1544     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1545     if (VA.needsCustom()) {
1546       if (VA.getLocVT() == MVT::v2f64) {
1547         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1548                                   DAG.getConstant(0, MVT::i32));
1549         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1550                                   DAG.getConstant(1, MVT::i32));
1551
1552         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1553                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1554
1555         VA = ArgLocs[++i]; // skip ahead to next loc
1556         if (VA.isRegLoc()) {
1557           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1558                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1559         } else {
1560           assert(VA.isMemLoc());
1561
1562           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1563                                                  dl, DAG, VA, Flags));
1564         }
1565       } else {
1566         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1567                          StackPtr, MemOpChains, Flags);
1568       }
1569     } else if (VA.isRegLoc()) {
1570       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1571         assert(VA.getLocVT() == MVT::i32 &&
1572                "unexpected calling convention register assignment");
1573         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1574                "unexpected use of 'returned'");
1575         isThisReturn = true;
1576       }
1577       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1578     } else if (isByVal) {
1579       assert(VA.isMemLoc());
1580       unsigned offset = 0;
1581
1582       // True if this byval aggregate will be split between registers
1583       // and memory.
1584       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1585       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1586
1587       if (CurByValIdx < ByValArgsCount) {
1588
1589         unsigned RegBegin, RegEnd;
1590         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1591
1592         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1593         unsigned int i, j;
1594         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1595           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1596           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1597           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1598                                      MachinePointerInfo(),
1599                                      false, false, false,
1600                                      DAG.InferPtrAlignment(AddArg));
1601           MemOpChains.push_back(Load.getValue(1));
1602           RegsToPass.push_back(std::make_pair(j, Load));
1603         }
1604
1605         // If parameter size outsides register area, "offset" value
1606         // helps us to calculate stack slot for remained part properly.
1607         offset = RegEnd - RegBegin;
1608
1609         CCInfo.nextInRegsParam();
1610       }
1611
1612       if (Flags.getByValSize() > 4*offset) {
1613         unsigned LocMemOffset = VA.getLocMemOffset();
1614         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1615         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1616                                   StkPtrOff);
1617         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1618         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1619         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1620                                            MVT::i32);
1621         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1622
1623         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1624         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1625         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1626                                           Ops));
1627       }
1628     } else if (!isSibCall) {
1629       assert(VA.isMemLoc());
1630
1631       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1632                                              dl, DAG, VA, Flags));
1633     }
1634   }
1635
1636   if (!MemOpChains.empty())
1637     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1638
1639   // Build a sequence of copy-to-reg nodes chained together with token chain
1640   // and flag operands which copy the outgoing args into the appropriate regs.
1641   SDValue InFlag;
1642   // Tail call byval lowering might overwrite argument registers so in case of
1643   // tail call optimization the copies to registers are lowered later.
1644   if (!isTailCall)
1645     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1646       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1647                                RegsToPass[i].second, InFlag);
1648       InFlag = Chain.getValue(1);
1649     }
1650
1651   // For tail calls lower the arguments to the 'real' stack slot.
1652   if (isTailCall) {
1653     // Force all the incoming stack arguments to be loaded from the stack
1654     // before any new outgoing arguments are stored to the stack, because the
1655     // outgoing stack slots may alias the incoming argument stack slots, and
1656     // the alias isn't otherwise explicit. This is slightly more conservative
1657     // than necessary, because it means that each store effectively depends
1658     // on every argument instead of just those arguments it would clobber.
1659
1660     // Do not flag preceding copytoreg stuff together with the following stuff.
1661     InFlag = SDValue();
1662     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1663       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1664                                RegsToPass[i].second, InFlag);
1665       InFlag = Chain.getValue(1);
1666     }
1667     InFlag = SDValue();
1668   }
1669
1670   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1671   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1672   // node so that legalize doesn't hack it.
1673   bool isDirect = false;
1674   bool isARMFunc = false;
1675   bool isLocalARMFunc = false;
1676   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1677
1678   if (EnableARMLongCalls) {
1679     assert((Subtarget->isTargetWindows() ||
1680             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1681            "long-calls with non-static relocation model!");
1682     // Handle a global address or an external symbol. If it's not one of
1683     // those, the target's already in a register, so we don't need to do
1684     // anything extra.
1685     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1686       const GlobalValue *GV = G->getGlobal();
1687       // Create a constant pool entry for the callee address
1688       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1689       ARMConstantPoolValue *CPV =
1690         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1691
1692       // Get the address of the callee into a register
1693       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1694       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1695       Callee = DAG.getLoad(getPointerTy(), dl,
1696                            DAG.getEntryNode(), CPAddr,
1697                            MachinePointerInfo::getConstantPool(),
1698                            false, false, false, 0);
1699     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1700       const char *Sym = S->getSymbol();
1701
1702       // Create a constant pool entry for the callee address
1703       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1704       ARMConstantPoolValue *CPV =
1705         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1706                                       ARMPCLabelIndex, 0);
1707       // Get the address of the callee into a register
1708       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1709       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1710       Callee = DAG.getLoad(getPointerTy(), dl,
1711                            DAG.getEntryNode(), CPAddr,
1712                            MachinePointerInfo::getConstantPool(),
1713                            false, false, false, 0);
1714     }
1715   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1716     const GlobalValue *GV = G->getGlobal();
1717     isDirect = true;
1718     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1719     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1720                    getTargetMachine().getRelocationModel() != Reloc::Static;
1721     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1722     // ARM call to a local ARM function is predicable.
1723     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1724     // tBX takes a register source operand.
1725     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1726       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1727       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1728                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1729                                                       0, ARMII::MO_NONLAZY));
1730       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1731                            MachinePointerInfo::getGOT(), false, false, true, 0);
1732     } else if (Subtarget->isTargetCOFF()) {
1733       assert(Subtarget->isTargetWindows() &&
1734              "Windows is the only supported COFF target");
1735       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1736                                  ? ARMII::MO_DLLIMPORT
1737                                  : ARMII::MO_NO_FLAG;
1738       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1739                                           TargetFlags);
1740       if (GV->hasDLLImportStorageClass())
1741         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1742                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1743                                          Callee), MachinePointerInfo::getGOT(),
1744                              false, false, false, 0);
1745     } else {
1746       // On ELF targets for PIC code, direct calls should go through the PLT
1747       unsigned OpFlags = 0;
1748       if (Subtarget->isTargetELF() &&
1749           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1750         OpFlags = ARMII::MO_PLT;
1751       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1752     }
1753   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1754     isDirect = true;
1755     bool isStub = Subtarget->isTargetMachO() &&
1756                   getTargetMachine().getRelocationModel() != Reloc::Static;
1757     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1758     // tBX takes a register source operand.
1759     const char *Sym = S->getSymbol();
1760     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1761       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1762       ARMConstantPoolValue *CPV =
1763         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1764                                       ARMPCLabelIndex, 4);
1765       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1766       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1767       Callee = DAG.getLoad(getPointerTy(), dl,
1768                            DAG.getEntryNode(), CPAddr,
1769                            MachinePointerInfo::getConstantPool(),
1770                            false, false, false, 0);
1771       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1772       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1773                            getPointerTy(), Callee, PICLabel);
1774     } else {
1775       unsigned OpFlags = 0;
1776       // On ELF targets for PIC code, direct calls should go through the PLT
1777       if (Subtarget->isTargetELF() &&
1778                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1779         OpFlags = ARMII::MO_PLT;
1780       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1781     }
1782   }
1783
1784   // FIXME: handle tail calls differently.
1785   unsigned CallOpc;
1786   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1787       AttributeSet::FunctionIndex, Attribute::MinSize);
1788   if (Subtarget->isThumb()) {
1789     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1790       CallOpc = ARMISD::CALL_NOLINK;
1791     else
1792       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1793   } else {
1794     if (!isDirect && !Subtarget->hasV5TOps())
1795       CallOpc = ARMISD::CALL_NOLINK;
1796     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1797                // Emit regular call when code size is the priority
1798                !HasMinSizeAttr)
1799       // "mov lr, pc; b _foo" to avoid confusing the RSP
1800       CallOpc = ARMISD::CALL_NOLINK;
1801     else
1802       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1803   }
1804
1805   std::vector<SDValue> Ops;
1806   Ops.push_back(Chain);
1807   Ops.push_back(Callee);
1808
1809   // Add argument registers to the end of the list so that they are known live
1810   // into the call.
1811   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1812     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1813                                   RegsToPass[i].second.getValueType()));
1814
1815   // Add a register mask operand representing the call-preserved registers.
1816   if (!isTailCall) {
1817     const uint32_t *Mask;
1818     const TargetRegisterInfo *TRI =
1819         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1820     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1821     if (isThisReturn) {
1822       // For 'this' returns, use the R0-preserving mask if applicable
1823       Mask = ARI->getThisReturnPreservedMask(CallConv);
1824       if (!Mask) {
1825         // Set isThisReturn to false if the calling convention is not one that
1826         // allows 'returned' to be modeled in this way, so LowerCallResult does
1827         // not try to pass 'this' straight through
1828         isThisReturn = false;
1829         Mask = ARI->getCallPreservedMask(CallConv);
1830       }
1831     } else
1832       Mask = ARI->getCallPreservedMask(CallConv);
1833
1834     assert(Mask && "Missing call preserved mask for calling convention");
1835     Ops.push_back(DAG.getRegisterMask(Mask));
1836   }
1837
1838   if (InFlag.getNode())
1839     Ops.push_back(InFlag);
1840
1841   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1842   if (isTailCall)
1843     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1844
1845   // Returns a chain and a flag for retval copy to use.
1846   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1847   InFlag = Chain.getValue(1);
1848
1849   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1850                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1851   if (!Ins.empty())
1852     InFlag = Chain.getValue(1);
1853
1854   // Handle result values, copying them out of physregs into vregs that we
1855   // return.
1856   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1857                          InVals, isThisReturn,
1858                          isThisReturn ? OutVals[0] : SDValue());
1859 }
1860
1861 /// HandleByVal - Every parameter *after* a byval parameter is passed
1862 /// on the stack.  Remember the next parameter register to allocate,
1863 /// and then confiscate the rest of the parameter registers to insure
1864 /// this.
1865 void
1866 ARMTargetLowering::HandleByVal(
1867     CCState *State, unsigned &size, unsigned Align) const {
1868   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1869   assert((State->getCallOrPrologue() == Prologue ||
1870           State->getCallOrPrologue() == Call) &&
1871          "unhandled ParmContext");
1872
1873   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1874     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1875       unsigned AlignInRegs = Align / 4;
1876       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1877       for (unsigned i = 0; i < Waste; ++i)
1878         reg = State->AllocateReg(GPRArgRegs, 4);
1879     }
1880     if (reg != 0) {
1881       unsigned excess = 4 * (ARM::R4 - reg);
1882
1883       // Special case when NSAA != SP and parameter size greater than size of
1884       // all remained GPR regs. In that case we can't split parameter, we must
1885       // send it to stack. We also must set NCRN to R4, so waste all
1886       // remained registers.
1887       const unsigned NSAAOffset = State->getNextStackOffset();
1888       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1889         while (State->AllocateReg(GPRArgRegs, 4))
1890           ;
1891         return;
1892       }
1893
1894       // First register for byval parameter is the first register that wasn't
1895       // allocated before this method call, so it would be "reg".
1896       // If parameter is small enough to be saved in range [reg, r4), then
1897       // the end (first after last) register would be reg + param-size-in-regs,
1898       // else parameter would be splitted between registers and stack,
1899       // end register would be r4 in this case.
1900       unsigned ByValRegBegin = reg;
1901       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1902       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1903       // Note, first register is allocated in the beginning of function already,
1904       // allocate remained amount of registers we need.
1905       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1906         State->AllocateReg(GPRArgRegs, 4);
1907       // A byval parameter that is split between registers and memory needs its
1908       // size truncated here.
1909       // In the case where the entire structure fits in registers, we set the
1910       // size in memory to zero.
1911       if (size < excess)
1912         size = 0;
1913       else
1914         size -= excess;
1915     }
1916   }
1917 }
1918
1919 /// MatchingStackOffset - Return true if the given stack call argument is
1920 /// already available in the same position (relatively) of the caller's
1921 /// incoming argument stack.
1922 static
1923 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1924                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1925                          const TargetInstrInfo *TII) {
1926   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1927   int FI = INT_MAX;
1928   if (Arg.getOpcode() == ISD::CopyFromReg) {
1929     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1930     if (!TargetRegisterInfo::isVirtualRegister(VR))
1931       return false;
1932     MachineInstr *Def = MRI->getVRegDef(VR);
1933     if (!Def)
1934       return false;
1935     if (!Flags.isByVal()) {
1936       if (!TII->isLoadFromStackSlot(Def, FI))
1937         return false;
1938     } else {
1939       return false;
1940     }
1941   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1942     if (Flags.isByVal())
1943       // ByVal argument is passed in as a pointer but it's now being
1944       // dereferenced. e.g.
1945       // define @foo(%struct.X* %A) {
1946       //   tail call @bar(%struct.X* byval %A)
1947       // }
1948       return false;
1949     SDValue Ptr = Ld->getBasePtr();
1950     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1951     if (!FINode)
1952       return false;
1953     FI = FINode->getIndex();
1954   } else
1955     return false;
1956
1957   assert(FI != INT_MAX);
1958   if (!MFI->isFixedObjectIndex(FI))
1959     return false;
1960   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1961 }
1962
1963 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1964 /// for tail call optimization. Targets which want to do tail call
1965 /// optimization should implement this function.
1966 bool
1967 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1968                                                      CallingConv::ID CalleeCC,
1969                                                      bool isVarArg,
1970                                                      bool isCalleeStructRet,
1971                                                      bool isCallerStructRet,
1972                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1973                                     const SmallVectorImpl<SDValue> &OutVals,
1974                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1975                                                      SelectionDAG& DAG) const {
1976   const Function *CallerF = DAG.getMachineFunction().getFunction();
1977   CallingConv::ID CallerCC = CallerF->getCallingConv();
1978   bool CCMatch = CallerCC == CalleeCC;
1979
1980   // Look for obvious safe cases to perform tail call optimization that do not
1981   // require ABI changes. This is what gcc calls sibcall.
1982
1983   // Do not sibcall optimize vararg calls unless the call site is not passing
1984   // any arguments.
1985   if (isVarArg && !Outs.empty())
1986     return false;
1987
1988   // Exception-handling functions need a special set of instructions to indicate
1989   // a return to the hardware. Tail-calling another function would probably
1990   // break this.
1991   if (CallerF->hasFnAttribute("interrupt"))
1992     return false;
1993
1994   // Also avoid sibcall optimization if either caller or callee uses struct
1995   // return semantics.
1996   if (isCalleeStructRet || isCallerStructRet)
1997     return false;
1998
1999   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2000   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2001   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2002   // support in the assembler and linker to be used. This would need to be
2003   // fixed to fully support tail calls in Thumb1.
2004   //
2005   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2006   // LR.  This means if we need to reload LR, it takes an extra instructions,
2007   // which outweighs the value of the tail call; but here we don't know yet
2008   // whether LR is going to be used.  Probably the right approach is to
2009   // generate the tail call here and turn it back into CALL/RET in
2010   // emitEpilogue if LR is used.
2011
2012   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2013   // but we need to make sure there are enough registers; the only valid
2014   // registers are the 4 used for parameters.  We don't currently do this
2015   // case.
2016   if (Subtarget->isThumb1Only())
2017     return false;
2018
2019   // Externally-defined functions with weak linkage should not be
2020   // tail-called on ARM when the OS does not support dynamic
2021   // pre-emption of symbols, as the AAELF spec requires normal calls
2022   // to undefined weak functions to be replaced with a NOP or jump to the
2023   // next instruction. The behaviour of branch instructions in this
2024   // situation (as used for tail calls) is implementation-defined, so we
2025   // cannot rely on the linker replacing the tail call with a return.
2026   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2027     const GlobalValue *GV = G->getGlobal();
2028     if (GV->hasExternalWeakLinkage())
2029       return false;
2030   }
2031
2032   // If the calling conventions do not match, then we'd better make sure the
2033   // results are returned in the same way as what the caller expects.
2034   if (!CCMatch) {
2035     SmallVector<CCValAssign, 16> RVLocs1;
2036     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2037                        *DAG.getContext(), Call);
2038     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2039
2040     SmallVector<CCValAssign, 16> RVLocs2;
2041     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2042                        *DAG.getContext(), Call);
2043     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2044
2045     if (RVLocs1.size() != RVLocs2.size())
2046       return false;
2047     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2048       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2049         return false;
2050       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2051         return false;
2052       if (RVLocs1[i].isRegLoc()) {
2053         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2054           return false;
2055       } else {
2056         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2057           return false;
2058       }
2059     }
2060   }
2061
2062   // If Caller's vararg or byval argument has been split between registers and
2063   // stack, do not perform tail call, since part of the argument is in caller's
2064   // local frame.
2065   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2066                                       getInfo<ARMFunctionInfo>();
2067   if (AFI_Caller->getArgRegsSaveSize())
2068     return false;
2069
2070   // If the callee takes no arguments then go on to check the results of the
2071   // call.
2072   if (!Outs.empty()) {
2073     // Check if stack adjustment is needed. For now, do not do this if any
2074     // argument is passed on the stack.
2075     SmallVector<CCValAssign, 16> ArgLocs;
2076     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2077                       *DAG.getContext(), Call);
2078     CCInfo.AnalyzeCallOperands(Outs,
2079                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2080     if (CCInfo.getNextStackOffset()) {
2081       MachineFunction &MF = DAG.getMachineFunction();
2082
2083       // Check if the arguments are already laid out in the right way as
2084       // the caller's fixed stack objects.
2085       MachineFrameInfo *MFI = MF.getFrameInfo();
2086       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2087       const TargetInstrInfo *TII =
2088           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2089       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2090            i != e;
2091            ++i, ++realArgIdx) {
2092         CCValAssign &VA = ArgLocs[i];
2093         EVT RegVT = VA.getLocVT();
2094         SDValue Arg = OutVals[realArgIdx];
2095         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2096         if (VA.getLocInfo() == CCValAssign::Indirect)
2097           return false;
2098         if (VA.needsCustom()) {
2099           // f64 and vector types are split into multiple registers or
2100           // register/stack-slot combinations.  The types will not match
2101           // the registers; give up on memory f64 refs until we figure
2102           // out what to do about this.
2103           if (!VA.isRegLoc())
2104             return false;
2105           if (!ArgLocs[++i].isRegLoc())
2106             return false;
2107           if (RegVT == MVT::v2f64) {
2108             if (!ArgLocs[++i].isRegLoc())
2109               return false;
2110             if (!ArgLocs[++i].isRegLoc())
2111               return false;
2112           }
2113         } else if (!VA.isRegLoc()) {
2114           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2115                                    MFI, MRI, TII))
2116             return false;
2117         }
2118       }
2119     }
2120   }
2121
2122   return true;
2123 }
2124
2125 bool
2126 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2127                                   MachineFunction &MF, bool isVarArg,
2128                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2129                                   LLVMContext &Context) const {
2130   SmallVector<CCValAssign, 16> RVLocs;
2131   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2132   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2133                                                     isVarArg));
2134 }
2135
2136 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2137                                     SDLoc DL, SelectionDAG &DAG) {
2138   const MachineFunction &MF = DAG.getMachineFunction();
2139   const Function *F = MF.getFunction();
2140
2141   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2142
2143   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2144   // version of the "preferred return address". These offsets affect the return
2145   // instruction if this is a return from PL1 without hypervisor extensions.
2146   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2147   //    SWI:     0      "subs pc, lr, #0"
2148   //    ABORT:   +4     "subs pc, lr, #4"
2149   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2150   // UNDEF varies depending on where the exception came from ARM or Thumb
2151   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2152
2153   int64_t LROffset;
2154   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2155       IntKind == "ABORT")
2156     LROffset = 4;
2157   else if (IntKind == "SWI" || IntKind == "UNDEF")
2158     LROffset = 0;
2159   else
2160     report_fatal_error("Unsupported interrupt attribute. If present, value "
2161                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2162
2163   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2164
2165   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2166 }
2167
2168 SDValue
2169 ARMTargetLowering::LowerReturn(SDValue Chain,
2170                                CallingConv::ID CallConv, bool isVarArg,
2171                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2172                                const SmallVectorImpl<SDValue> &OutVals,
2173                                SDLoc dl, SelectionDAG &DAG) const {
2174
2175   // CCValAssign - represent the assignment of the return value to a location.
2176   SmallVector<CCValAssign, 16> RVLocs;
2177
2178   // CCState - Info about the registers and stack slots.
2179   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2180                     *DAG.getContext(), Call);
2181
2182   // Analyze outgoing return values.
2183   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2184                                                isVarArg));
2185
2186   SDValue Flag;
2187   SmallVector<SDValue, 4> RetOps;
2188   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2189   bool isLittleEndian = Subtarget->isLittle();
2190
2191   MachineFunction &MF = DAG.getMachineFunction();
2192   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2193   AFI->setReturnRegsCount(RVLocs.size());
2194
2195   // Copy the result values into the output registers.
2196   for (unsigned i = 0, realRVLocIdx = 0;
2197        i != RVLocs.size();
2198        ++i, ++realRVLocIdx) {
2199     CCValAssign &VA = RVLocs[i];
2200     assert(VA.isRegLoc() && "Can only return in registers!");
2201
2202     SDValue Arg = OutVals[realRVLocIdx];
2203
2204     switch (VA.getLocInfo()) {
2205     default: llvm_unreachable("Unknown loc info!");
2206     case CCValAssign::Full: break;
2207     case CCValAssign::BCvt:
2208       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2209       break;
2210     }
2211
2212     if (VA.needsCustom()) {
2213       if (VA.getLocVT() == MVT::v2f64) {
2214         // Extract the first half and return it in two registers.
2215         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2216                                    DAG.getConstant(0, MVT::i32));
2217         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2218                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2219
2220         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2221                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2222                                  Flag);
2223         Flag = Chain.getValue(1);
2224         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2225         VA = RVLocs[++i]; // skip ahead to next loc
2226         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2227                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2228                                  Flag);
2229         Flag = Chain.getValue(1);
2230         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2231         VA = RVLocs[++i]; // skip ahead to next loc
2232
2233         // Extract the 2nd half and fall through to handle it as an f64 value.
2234         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2235                           DAG.getConstant(1, MVT::i32));
2236       }
2237       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2238       // available.
2239       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2240                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2241       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2242                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2243                                Flag);
2244       Flag = Chain.getValue(1);
2245       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2246       VA = RVLocs[++i]; // skip ahead to next loc
2247       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2248                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2249                                Flag);
2250     } else
2251       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2252
2253     // Guarantee that all emitted copies are
2254     // stuck together, avoiding something bad.
2255     Flag = Chain.getValue(1);
2256     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2257   }
2258
2259   // Update chain and glue.
2260   RetOps[0] = Chain;
2261   if (Flag.getNode())
2262     RetOps.push_back(Flag);
2263
2264   // CPUs which aren't M-class use a special sequence to return from
2265   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2266   // though we use "subs pc, lr, #N").
2267   //
2268   // M-class CPUs actually use a normal return sequence with a special
2269   // (hardware-provided) value in LR, so the normal code path works.
2270   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2271       !Subtarget->isMClass()) {
2272     if (Subtarget->isThumb1Only())
2273       report_fatal_error("interrupt attribute is not supported in Thumb1");
2274     return LowerInterruptReturn(RetOps, dl, DAG);
2275   }
2276
2277   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2278 }
2279
2280 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2281   if (N->getNumValues() != 1)
2282     return false;
2283   if (!N->hasNUsesOfValue(1, 0))
2284     return false;
2285
2286   SDValue TCChain = Chain;
2287   SDNode *Copy = *N->use_begin();
2288   if (Copy->getOpcode() == ISD::CopyToReg) {
2289     // If the copy has a glue operand, we conservatively assume it isn't safe to
2290     // perform a tail call.
2291     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2292       return false;
2293     TCChain = Copy->getOperand(0);
2294   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2295     SDNode *VMov = Copy;
2296     // f64 returned in a pair of GPRs.
2297     SmallPtrSet<SDNode*, 2> Copies;
2298     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2299          UI != UE; ++UI) {
2300       if (UI->getOpcode() != ISD::CopyToReg)
2301         return false;
2302       Copies.insert(*UI);
2303     }
2304     if (Copies.size() > 2)
2305       return false;
2306
2307     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2308          UI != UE; ++UI) {
2309       SDValue UseChain = UI->getOperand(0);
2310       if (Copies.count(UseChain.getNode()))
2311         // Second CopyToReg
2312         Copy = *UI;
2313       else {
2314         // We are at the top of this chain.
2315         // If the copy has a glue operand, we conservatively assume it
2316         // isn't safe to perform a tail call.
2317         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2318           return false;
2319         // First CopyToReg
2320         TCChain = UseChain;
2321       }
2322     }
2323   } else if (Copy->getOpcode() == ISD::BITCAST) {
2324     // f32 returned in a single GPR.
2325     if (!Copy->hasOneUse())
2326       return false;
2327     Copy = *Copy->use_begin();
2328     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2329       return false;
2330     // If the copy has a glue operand, we conservatively assume it isn't safe to
2331     // perform a tail call.
2332     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2333       return false;
2334     TCChain = Copy->getOperand(0);
2335   } else {
2336     return false;
2337   }
2338
2339   bool HasRet = false;
2340   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2341        UI != UE; ++UI) {
2342     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2343         UI->getOpcode() != ARMISD::INTRET_FLAG)
2344       return false;
2345     HasRet = true;
2346   }
2347
2348   if (!HasRet)
2349     return false;
2350
2351   Chain = TCChain;
2352   return true;
2353 }
2354
2355 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2356   if (!Subtarget->supportsTailCall())
2357     return false;
2358
2359   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2360     return false;
2361
2362   return !Subtarget->isThumb1Only();
2363 }
2364
2365 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2366 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2367 // one of the above mentioned nodes. It has to be wrapped because otherwise
2368 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2369 // be used to form addressing mode. These wrapped nodes will be selected
2370 // into MOVi.
2371 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2372   EVT PtrVT = Op.getValueType();
2373   // FIXME there is no actual debug info here
2374   SDLoc dl(Op);
2375   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2376   SDValue Res;
2377   if (CP->isMachineConstantPoolEntry())
2378     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2379                                     CP->getAlignment());
2380   else
2381     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2382                                     CP->getAlignment());
2383   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2384 }
2385
2386 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2387   return MachineJumpTableInfo::EK_Inline;
2388 }
2389
2390 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2391                                              SelectionDAG &DAG) const {
2392   MachineFunction &MF = DAG.getMachineFunction();
2393   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2394   unsigned ARMPCLabelIndex = 0;
2395   SDLoc DL(Op);
2396   EVT PtrVT = getPointerTy();
2397   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2398   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2399   SDValue CPAddr;
2400   if (RelocM == Reloc::Static) {
2401     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2402   } else {
2403     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2404     ARMPCLabelIndex = AFI->createPICLabelUId();
2405     ARMConstantPoolValue *CPV =
2406       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2407                                       ARMCP::CPBlockAddress, PCAdj);
2408     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2409   }
2410   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2411   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2412                                MachinePointerInfo::getConstantPool(),
2413                                false, false, false, 0);
2414   if (RelocM == Reloc::Static)
2415     return Result;
2416   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2417   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2418 }
2419
2420 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2421 SDValue
2422 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2423                                                  SelectionDAG &DAG) const {
2424   SDLoc dl(GA);
2425   EVT PtrVT = getPointerTy();
2426   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2427   MachineFunction &MF = DAG.getMachineFunction();
2428   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2429   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2430   ARMConstantPoolValue *CPV =
2431     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2432                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2433   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2434   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2435   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2436                          MachinePointerInfo::getConstantPool(),
2437                          false, false, false, 0);
2438   SDValue Chain = Argument.getValue(1);
2439
2440   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2441   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2442
2443   // call __tls_get_addr.
2444   ArgListTy Args;
2445   ArgListEntry Entry;
2446   Entry.Node = Argument;
2447   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2448   Args.push_back(Entry);
2449
2450   // FIXME: is there useful debug info available here?
2451   TargetLowering::CallLoweringInfo CLI(DAG);
2452   CLI.setDebugLoc(dl).setChain(Chain)
2453     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2454                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2455                0);
2456
2457   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2458   return CallResult.first;
2459 }
2460
2461 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2462 // "local exec" model.
2463 SDValue
2464 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2465                                         SelectionDAG &DAG,
2466                                         TLSModel::Model model) const {
2467   const GlobalValue *GV = GA->getGlobal();
2468   SDLoc dl(GA);
2469   SDValue Offset;
2470   SDValue Chain = DAG.getEntryNode();
2471   EVT PtrVT = getPointerTy();
2472   // Get the Thread Pointer
2473   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2474
2475   if (model == TLSModel::InitialExec) {
2476     MachineFunction &MF = DAG.getMachineFunction();
2477     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2478     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2479     // Initial exec model.
2480     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2481     ARMConstantPoolValue *CPV =
2482       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2483                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2484                                       true);
2485     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2486     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2487     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2488                          MachinePointerInfo::getConstantPool(),
2489                          false, false, false, 0);
2490     Chain = Offset.getValue(1);
2491
2492     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2493     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2494
2495     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2496                          MachinePointerInfo::getConstantPool(),
2497                          false, false, false, 0);
2498   } else {
2499     // local exec model
2500     assert(model == TLSModel::LocalExec);
2501     ARMConstantPoolValue *CPV =
2502       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2503     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2504     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2505     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2506                          MachinePointerInfo::getConstantPool(),
2507                          false, false, false, 0);
2508   }
2509
2510   // The address of the thread local variable is the add of the thread
2511   // pointer with the offset of the variable.
2512   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2513 }
2514
2515 SDValue
2516 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2517   // TODO: implement the "local dynamic" model
2518   assert(Subtarget->isTargetELF() &&
2519          "TLS not implemented for non-ELF targets");
2520   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2521
2522   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2523
2524   switch (model) {
2525     case TLSModel::GeneralDynamic:
2526     case TLSModel::LocalDynamic:
2527       return LowerToTLSGeneralDynamicModel(GA, DAG);
2528     case TLSModel::InitialExec:
2529     case TLSModel::LocalExec:
2530       return LowerToTLSExecModels(GA, DAG, model);
2531   }
2532   llvm_unreachable("bogus TLS model");
2533 }
2534
2535 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2536                                                  SelectionDAG &DAG) const {
2537   EVT PtrVT = getPointerTy();
2538   SDLoc dl(Op);
2539   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2540   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2541     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2542     ARMConstantPoolValue *CPV =
2543       ARMConstantPoolConstant::Create(GV,
2544                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2545     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2546     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2547     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2548                                  CPAddr,
2549                                  MachinePointerInfo::getConstantPool(),
2550                                  false, false, false, 0);
2551     SDValue Chain = Result.getValue(1);
2552     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2553     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2554     if (!UseGOTOFF)
2555       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2556                            MachinePointerInfo::getGOT(),
2557                            false, false, false, 0);
2558     return Result;
2559   }
2560
2561   // If we have T2 ops, we can materialize the address directly via movt/movw
2562   // pair. This is always cheaper.
2563   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2564     ++NumMovwMovt;
2565     // FIXME: Once remat is capable of dealing with instructions with register
2566     // operands, expand this into two nodes.
2567     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2568                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2569   } else {
2570     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2571     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2572     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2573                        MachinePointerInfo::getConstantPool(),
2574                        false, false, false, 0);
2575   }
2576 }
2577
2578 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2579                                                     SelectionDAG &DAG) const {
2580   EVT PtrVT = getPointerTy();
2581   SDLoc dl(Op);
2582   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2583   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2584
2585   if (Subtarget->useMovt(DAG.getMachineFunction()))
2586     ++NumMovwMovt;
2587
2588   // FIXME: Once remat is capable of dealing with instructions with register
2589   // operands, expand this into multiple nodes
2590   unsigned Wrapper =
2591       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2592
2593   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2594   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2595
2596   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2597     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2598                          MachinePointerInfo::getGOT(), false, false, false, 0);
2599   return Result;
2600 }
2601
2602 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2603                                                      SelectionDAG &DAG) const {
2604   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2605   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2606          "Windows on ARM expects to use movw/movt");
2607
2608   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2609   const ARMII::TOF TargetFlags =
2610     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2611   EVT PtrVT = getPointerTy();
2612   SDValue Result;
2613   SDLoc DL(Op);
2614
2615   ++NumMovwMovt;
2616
2617   // FIXME: Once remat is capable of dealing with instructions with register
2618   // operands, expand this into two nodes.
2619   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2620                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2621                                                   TargetFlags));
2622   if (GV->hasDLLImportStorageClass())
2623     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2624                          MachinePointerInfo::getGOT(), false, false, false, 0);
2625   return Result;
2626 }
2627
2628 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2629                                                     SelectionDAG &DAG) const {
2630   assert(Subtarget->isTargetELF() &&
2631          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2634   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2635   EVT PtrVT = getPointerTy();
2636   SDLoc dl(Op);
2637   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2638   ARMConstantPoolValue *CPV =
2639     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2640                                   ARMPCLabelIndex, PCAdj);
2641   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2642   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2643   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2644                                MachinePointerInfo::getConstantPool(),
2645                                false, false, false, 0);
2646   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2647   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2648 }
2649
2650 SDValue
2651 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2652   SDLoc dl(Op);
2653   SDValue Val = DAG.getConstant(0, MVT::i32);
2654   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2655                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2656                      Op.getOperand(1), Val);
2657 }
2658
2659 SDValue
2660 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2661   SDLoc dl(Op);
2662   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2663                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2664 }
2665
2666 SDValue
2667 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2668                                           const ARMSubtarget *Subtarget) const {
2669   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2670   SDLoc dl(Op);
2671   switch (IntNo) {
2672   default: return SDValue();    // Don't custom lower most intrinsics.
2673   case Intrinsic::arm_rbit: {
2674     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2675            "RBIT intrinsic must have i32 type!");
2676     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2677   }
2678   case Intrinsic::arm_thread_pointer: {
2679     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2680     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2681   }
2682   case Intrinsic::eh_sjlj_lsda: {
2683     MachineFunction &MF = DAG.getMachineFunction();
2684     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2685     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2686     EVT PtrVT = getPointerTy();
2687     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2688     SDValue CPAddr;
2689     unsigned PCAdj = (RelocM != Reloc::PIC_)
2690       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2691     ARMConstantPoolValue *CPV =
2692       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2693                                       ARMCP::CPLSDA, PCAdj);
2694     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2695     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2696     SDValue Result =
2697       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2698                   MachinePointerInfo::getConstantPool(),
2699                   false, false, false, 0);
2700
2701     if (RelocM == Reloc::PIC_) {
2702       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2703       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2704     }
2705     return Result;
2706   }
2707   case Intrinsic::arm_neon_vmulls:
2708   case Intrinsic::arm_neon_vmullu: {
2709     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2710       ? ARMISD::VMULLs : ARMISD::VMULLu;
2711     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2712                        Op.getOperand(1), Op.getOperand(2));
2713   }
2714   }
2715 }
2716
2717 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2718                                  const ARMSubtarget *Subtarget) {
2719   // FIXME: handle "fence singlethread" more efficiently.
2720   SDLoc dl(Op);
2721   if (!Subtarget->hasDataBarrier()) {
2722     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2723     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2724     // here.
2725     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2726            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2727     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2728                        DAG.getConstant(0, MVT::i32));
2729   }
2730
2731   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2732   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2733   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2734   if (Subtarget->isMClass()) {
2735     // Only a full system barrier exists in the M-class architectures.
2736     Domain = ARM_MB::SY;
2737   } else if (Subtarget->isSwift() && Ord == Release) {
2738     // Swift happens to implement ISHST barriers in a way that's compatible with
2739     // Release semantics but weaker than ISH so we'd be fools not to use
2740     // it. Beware: other processors probably don't!
2741     Domain = ARM_MB::ISHST;
2742   }
2743
2744   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2745                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2746                      DAG.getConstant(Domain, MVT::i32));
2747 }
2748
2749 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2750                              const ARMSubtarget *Subtarget) {
2751   // ARM pre v5TE and Thumb1 does not have preload instructions.
2752   if (!(Subtarget->isThumb2() ||
2753         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2754     // Just preserve the chain.
2755     return Op.getOperand(0);
2756
2757   SDLoc dl(Op);
2758   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2759   if (!isRead &&
2760       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2761     // ARMv7 with MP extension has PLDW.
2762     return Op.getOperand(0);
2763
2764   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2765   if (Subtarget->isThumb()) {
2766     // Invert the bits.
2767     isRead = ~isRead & 1;
2768     isData = ~isData & 1;
2769   }
2770
2771   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2772                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2773                      DAG.getConstant(isData, MVT::i32));
2774 }
2775
2776 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2777   MachineFunction &MF = DAG.getMachineFunction();
2778   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2779
2780   // vastart just stores the address of the VarArgsFrameIndex slot into the
2781   // memory location argument.
2782   SDLoc dl(Op);
2783   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2784   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2785   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2786   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2787                       MachinePointerInfo(SV), false, false, 0);
2788 }
2789
2790 SDValue
2791 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2792                                         SDValue &Root, SelectionDAG &DAG,
2793                                         SDLoc dl) const {
2794   MachineFunction &MF = DAG.getMachineFunction();
2795   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2796
2797   const TargetRegisterClass *RC;
2798   if (AFI->isThumb1OnlyFunction())
2799     RC = &ARM::tGPRRegClass;
2800   else
2801     RC = &ARM::GPRRegClass;
2802
2803   // Transform the arguments stored in physical registers into virtual ones.
2804   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2805   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2806
2807   SDValue ArgValue2;
2808   if (NextVA.isMemLoc()) {
2809     MachineFrameInfo *MFI = MF.getFrameInfo();
2810     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2811
2812     // Create load node to retrieve arguments from the stack.
2813     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2814     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2815                             MachinePointerInfo::getFixedStack(FI),
2816                             false, false, false, 0);
2817   } else {
2818     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2819     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2820   }
2821   if (!Subtarget->isLittle())
2822     std::swap (ArgValue, ArgValue2);
2823   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2824 }
2825
2826 void
2827 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2828                                   unsigned InRegsParamRecordIdx,
2829                                   unsigned ArgSize,
2830                                   unsigned &ArgRegsSize,
2831                                   unsigned &ArgRegsSaveSize)
2832   const {
2833   unsigned NumGPRs;
2834   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2835     unsigned RBegin, REnd;
2836     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2837     NumGPRs = REnd - RBegin;
2838   } else {
2839     unsigned int firstUnalloced;
2840     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2841                                                 sizeof(GPRArgRegs) /
2842                                                 sizeof(GPRArgRegs[0]));
2843     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2844   }
2845
2846   unsigned Align = MF.getTarget()
2847                        .getSubtargetImpl()
2848                        ->getFrameLowering()
2849                        ->getStackAlignment();
2850   ArgRegsSize = NumGPRs * 4;
2851
2852   // If parameter is split between stack and GPRs...
2853   if (NumGPRs && Align > 4 &&
2854       (ArgRegsSize < ArgSize ||
2855         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2856     // Add padding for part of param recovered from GPRs.  For example,
2857     // if Align == 8, its last byte must be at address K*8 - 1.
2858     // We need to do it, since remained (stack) part of parameter has
2859     // stack alignment, and we need to "attach" "GPRs head" without gaps
2860     // to it:
2861     // Stack:
2862     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2863     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2864     //
2865     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2866     unsigned Padding =
2867         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2868     ArgRegsSaveSize = ArgRegsSize + Padding;
2869   } else
2870     // We don't need to extend regs save size for byval parameters if they
2871     // are passed via GPRs only.
2872     ArgRegsSaveSize = ArgRegsSize;
2873 }
2874
2875 // The remaining GPRs hold either the beginning of variable-argument
2876 // data, or the beginning of an aggregate passed by value (usually
2877 // byval).  Either way, we allocate stack slots adjacent to the data
2878 // provided by our caller, and store the unallocated registers there.
2879 // If this is a variadic function, the va_list pointer will begin with
2880 // these values; otherwise, this reassembles a (byval) structure that
2881 // was split between registers and memory.
2882 // Return: The frame index registers were stored into.
2883 int
2884 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2885                                   SDLoc dl, SDValue &Chain,
2886                                   const Value *OrigArg,
2887                                   unsigned InRegsParamRecordIdx,
2888                                   unsigned OffsetFromOrigArg,
2889                                   unsigned ArgOffset,
2890                                   unsigned ArgSize,
2891                                   bool ForceMutable,
2892                                   unsigned ByValStoreOffset,
2893                                   unsigned TotalArgRegsSaveSize) const {
2894
2895   // Currently, two use-cases possible:
2896   // Case #1. Non-var-args function, and we meet first byval parameter.
2897   //          Setup first unallocated register as first byval register;
2898   //          eat all remained registers
2899   //          (these two actions are performed by HandleByVal method).
2900   //          Then, here, we initialize stack frame with
2901   //          "store-reg" instructions.
2902   // Case #2. Var-args function, that doesn't contain byval parameters.
2903   //          The same: eat all remained unallocated registers,
2904   //          initialize stack frame.
2905
2906   MachineFunction &MF = DAG.getMachineFunction();
2907   MachineFrameInfo *MFI = MF.getFrameInfo();
2908   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2909   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2910   unsigned RBegin, REnd;
2911   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2912     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2913     firstRegToSaveIndex = RBegin - ARM::R0;
2914     lastRegToSaveIndex = REnd - ARM::R0;
2915   } else {
2916     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2917       (GPRArgRegs, array_lengthof(GPRArgRegs));
2918     lastRegToSaveIndex = 4;
2919   }
2920
2921   unsigned ArgRegsSize, ArgRegsSaveSize;
2922   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2923                  ArgRegsSize, ArgRegsSaveSize);
2924
2925   // Store any by-val regs to their spots on the stack so that they may be
2926   // loaded by deferencing the result of formal parameter pointer or va_next.
2927   // Note: once stack area for byval/varargs registers
2928   // was initialized, it can't be initialized again.
2929   if (ArgRegsSaveSize) {
2930     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2931
2932     if (Padding) {
2933       assert(AFI->getStoredByValParamsPadding() == 0 &&
2934              "The only parameter may be padded.");
2935       AFI->setStoredByValParamsPadding(Padding);
2936     }
2937
2938     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2939                                             Padding +
2940                                               ByValStoreOffset -
2941                                               (int64_t)TotalArgRegsSaveSize,
2942                                             false);
2943     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2944     if (Padding) {
2945        MFI->CreateFixedObject(Padding,
2946                               ArgOffset + ByValStoreOffset -
2947                                 (int64_t)ArgRegsSaveSize,
2948                               false);
2949     }
2950
2951     SmallVector<SDValue, 4> MemOps;
2952     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2953          ++firstRegToSaveIndex, ++i) {
2954       const TargetRegisterClass *RC;
2955       if (AFI->isThumb1OnlyFunction())
2956         RC = &ARM::tGPRRegClass;
2957       else
2958         RC = &ARM::GPRRegClass;
2959
2960       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2961       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2962       SDValue Store =
2963         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2964                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2965                      false, false, 0);
2966       MemOps.push_back(Store);
2967       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2968                         DAG.getConstant(4, getPointerTy()));
2969     }
2970
2971     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2972
2973     if (!MemOps.empty())
2974       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2975     return FrameIndex;
2976   } else {
2977     if (ArgSize == 0) {
2978       // We cannot allocate a zero-byte object for the first variadic argument,
2979       // so just make up a size.
2980       ArgSize = 4;
2981     }
2982     // This will point to the next argument passed via stack.
2983     return MFI->CreateFixedObject(
2984       ArgSize, ArgOffset, !ForceMutable);
2985   }
2986 }
2987
2988 // Setup stack frame, the va_list pointer will start from.
2989 void
2990 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2991                                         SDLoc dl, SDValue &Chain,
2992                                         unsigned ArgOffset,
2993                                         unsigned TotalArgRegsSaveSize,
2994                                         bool ForceMutable) const {
2995   MachineFunction &MF = DAG.getMachineFunction();
2996   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2997
2998   // Try to store any remaining integer argument regs
2999   // to their spots on the stack so that they may be loaded by deferencing
3000   // the result of va_next.
3001   // If there is no regs to be stored, just point address after last
3002   // argument passed via stack.
3003   int FrameIndex =
3004     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3005                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3006                    0, TotalArgRegsSaveSize);
3007
3008   AFI->setVarArgsFrameIndex(FrameIndex);
3009 }
3010
3011 SDValue
3012 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3013                                         CallingConv::ID CallConv, bool isVarArg,
3014                                         const SmallVectorImpl<ISD::InputArg>
3015                                           &Ins,
3016                                         SDLoc dl, SelectionDAG &DAG,
3017                                         SmallVectorImpl<SDValue> &InVals)
3018                                           const {
3019   MachineFunction &MF = DAG.getMachineFunction();
3020   MachineFrameInfo *MFI = MF.getFrameInfo();
3021
3022   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3023
3024   // Assign locations to all of the incoming arguments.
3025   SmallVector<CCValAssign, 16> ArgLocs;
3026   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3027                     *DAG.getContext(), Prologue);
3028   CCInfo.AnalyzeFormalArguments(Ins,
3029                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3030                                                   isVarArg));
3031
3032   SmallVector<SDValue, 16> ArgValues;
3033   int lastInsIndex = -1;
3034   SDValue ArgValue;
3035   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3036   unsigned CurArgIdx = 0;
3037
3038   // Initially ArgRegsSaveSize is zero.
3039   // Then we increase this value each time we meet byval parameter.
3040   // We also increase this value in case of varargs function.
3041   AFI->setArgRegsSaveSize(0);
3042
3043   unsigned ByValStoreOffset = 0;
3044   unsigned TotalArgRegsSaveSize = 0;
3045   unsigned ArgRegsSaveSizeMaxAlign = 4;
3046
3047   // Calculate the amount of stack space that we need to allocate to store
3048   // byval and variadic arguments that are passed in registers.
3049   // We need to know this before we allocate the first byval or variadic
3050   // argument, as they will be allocated a stack slot below the CFA (Canonical
3051   // Frame Address, the stack pointer at entry to the function).
3052   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3053     CCValAssign &VA = ArgLocs[i];
3054     if (VA.isMemLoc()) {
3055       int index = VA.getValNo();
3056       if (index != lastInsIndex) {
3057         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3058         if (Flags.isByVal()) {
3059           unsigned ExtraArgRegsSize;
3060           unsigned ExtraArgRegsSaveSize;
3061           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3062                          Flags.getByValSize(),
3063                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3064
3065           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3066           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3067               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3068           CCInfo.nextInRegsParam();
3069         }
3070         lastInsIndex = index;
3071       }
3072     }
3073   }
3074   CCInfo.rewindByValRegsInfo();
3075   lastInsIndex = -1;
3076   if (isVarArg && MFI->hasVAStart()) {
3077     unsigned ExtraArgRegsSize;
3078     unsigned ExtraArgRegsSaveSize;
3079     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3080                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3081     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3082   }
3083   // If the arg regs save area contains N-byte aligned values, the
3084   // bottom of it must be at least N-byte aligned.
3085   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3086   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3087
3088   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3089     CCValAssign &VA = ArgLocs[i];
3090     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3091     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3092     // Arguments stored in registers.
3093     if (VA.isRegLoc()) {
3094       EVT RegVT = VA.getLocVT();
3095
3096       if (VA.needsCustom()) {
3097         // f64 and vector types are split up into multiple registers or
3098         // combinations of registers and stack slots.
3099         if (VA.getLocVT() == MVT::v2f64) {
3100           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3101                                                    Chain, DAG, dl);
3102           VA = ArgLocs[++i]; // skip ahead to next loc
3103           SDValue ArgValue2;
3104           if (VA.isMemLoc()) {
3105             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3106             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3107             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3108                                     MachinePointerInfo::getFixedStack(FI),
3109                                     false, false, false, 0);
3110           } else {
3111             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3112                                              Chain, DAG, dl);
3113           }
3114           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3115           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3116                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3117           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3118                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3119         } else
3120           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3121
3122       } else {
3123         const TargetRegisterClass *RC;
3124
3125         if (RegVT == MVT::f32)
3126           RC = &ARM::SPRRegClass;
3127         else if (RegVT == MVT::f64)
3128           RC = &ARM::DPRRegClass;
3129         else if (RegVT == MVT::v2f64)
3130           RC = &ARM::QPRRegClass;
3131         else if (RegVT == MVT::i32)
3132           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3133                                            : &ARM::GPRRegClass;
3134         else
3135           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3136
3137         // Transform the arguments in physical registers into virtual ones.
3138         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3139         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3140       }
3141
3142       // If this is an 8 or 16-bit value, it is really passed promoted
3143       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3144       // truncate to the right size.
3145       switch (VA.getLocInfo()) {
3146       default: llvm_unreachable("Unknown loc info!");
3147       case CCValAssign::Full: break;
3148       case CCValAssign::BCvt:
3149         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3150         break;
3151       case CCValAssign::SExt:
3152         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3153                                DAG.getValueType(VA.getValVT()));
3154         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3155         break;
3156       case CCValAssign::ZExt:
3157         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3158                                DAG.getValueType(VA.getValVT()));
3159         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3160         break;
3161       }
3162
3163       InVals.push_back(ArgValue);
3164
3165     } else { // VA.isRegLoc()
3166
3167       // sanity check
3168       assert(VA.isMemLoc());
3169       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3170
3171       int index = ArgLocs[i].getValNo();
3172
3173       // Some Ins[] entries become multiple ArgLoc[] entries.
3174       // Process them only once.
3175       if (index != lastInsIndex)
3176         {
3177           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3178           // FIXME: For now, all byval parameter objects are marked mutable.
3179           // This can be changed with more analysis.
3180           // In case of tail call optimization mark all arguments mutable.
3181           // Since they could be overwritten by lowering of arguments in case of
3182           // a tail call.
3183           if (Flags.isByVal()) {
3184             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3185
3186             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3187             int FrameIndex = StoreByValRegs(
3188                 CCInfo, DAG, dl, Chain, CurOrigArg,
3189                 CurByValIndex,
3190                 Ins[VA.getValNo()].PartOffset,
3191                 VA.getLocMemOffset(),
3192                 Flags.getByValSize(),
3193                 true /*force mutable frames*/,
3194                 ByValStoreOffset,
3195                 TotalArgRegsSaveSize);
3196             ByValStoreOffset += Flags.getByValSize();
3197             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3198             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3199             CCInfo.nextInRegsParam();
3200           } else {
3201             unsigned FIOffset = VA.getLocMemOffset();
3202             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3203                                             FIOffset, true);
3204
3205             // Create load nodes to retrieve arguments from the stack.
3206             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3207             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3208                                          MachinePointerInfo::getFixedStack(FI),
3209                                          false, false, false, 0));
3210           }
3211           lastInsIndex = index;
3212         }
3213     }
3214   }
3215
3216   // varargs
3217   if (isVarArg && MFI->hasVAStart())
3218     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3219                          CCInfo.getNextStackOffset(),
3220                          TotalArgRegsSaveSize);
3221
3222   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3223
3224   return Chain;
3225 }
3226
3227 /// isFloatingPointZero - Return true if this is +0.0.
3228 static bool isFloatingPointZero(SDValue Op) {
3229   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3230     return CFP->getValueAPF().isPosZero();
3231   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3232     // Maybe this has already been legalized into the constant pool?
3233     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3234       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3235       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3236         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3237           return CFP->getValueAPF().isPosZero();
3238     }
3239   } else if (Op->getOpcode() == ISD::BITCAST &&
3240              Op->getValueType(0) == MVT::f64) {
3241     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3242     // created by LowerConstantFP().
3243     SDValue BitcastOp = Op->getOperand(0);
3244     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3245       SDValue MoveOp = BitcastOp->getOperand(0);
3246       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3247           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3248         return true;
3249       }
3250     }
3251   }
3252   return false;
3253 }
3254
3255 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3256 /// the given operands.
3257 SDValue
3258 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3259                              SDValue &ARMcc, SelectionDAG &DAG,
3260                              SDLoc dl) const {
3261   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3262     unsigned C = RHSC->getZExtValue();
3263     if (!isLegalICmpImmediate(C)) {
3264       // Constant does not fit, try adjusting it by one?
3265       switch (CC) {
3266       default: break;
3267       case ISD::SETLT:
3268       case ISD::SETGE:
3269         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3270           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3271           RHS = DAG.getConstant(C-1, MVT::i32);
3272         }
3273         break;
3274       case ISD::SETULT:
3275       case ISD::SETUGE:
3276         if (C != 0 && isLegalICmpImmediate(C-1)) {
3277           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3278           RHS = DAG.getConstant(C-1, MVT::i32);
3279         }
3280         break;
3281       case ISD::SETLE:
3282       case ISD::SETGT:
3283         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3284           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3285           RHS = DAG.getConstant(C+1, MVT::i32);
3286         }
3287         break;
3288       case ISD::SETULE:
3289       case ISD::SETUGT:
3290         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3291           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3292           RHS = DAG.getConstant(C+1, MVT::i32);
3293         }
3294         break;
3295       }
3296     }
3297   }
3298
3299   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3300   ARMISD::NodeType CompareType;
3301   switch (CondCode) {
3302   default:
3303     CompareType = ARMISD::CMP;
3304     break;
3305   case ARMCC::EQ:
3306   case ARMCC::NE:
3307     // Uses only Z Flag
3308     CompareType = ARMISD::CMPZ;
3309     break;
3310   }
3311   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3312   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3313 }
3314
3315 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3316 SDValue
3317 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3318                              SDLoc dl) const {
3319   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3320   SDValue Cmp;
3321   if (!isFloatingPointZero(RHS))
3322     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3323   else
3324     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3325   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3326 }
3327
3328 /// duplicateCmp - Glue values can have only one use, so this function
3329 /// duplicates a comparison node.
3330 SDValue
3331 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3332   unsigned Opc = Cmp.getOpcode();
3333   SDLoc DL(Cmp);
3334   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3335     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3336
3337   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3338   Cmp = Cmp.getOperand(0);
3339   Opc = Cmp.getOpcode();
3340   if (Opc == ARMISD::CMPFP)
3341     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3342   else {
3343     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3344     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3345   }
3346   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3347 }
3348
3349 std::pair<SDValue, SDValue>
3350 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3351                                  SDValue &ARMcc) const {
3352   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3353
3354   SDValue Value, OverflowCmp;
3355   SDValue LHS = Op.getOperand(0);
3356   SDValue RHS = Op.getOperand(1);
3357
3358
3359   // FIXME: We are currently always generating CMPs because we don't support
3360   // generating CMN through the backend. This is not as good as the natural
3361   // CMP case because it causes a register dependency and cannot be folded
3362   // later.
3363
3364   switch (Op.getOpcode()) {
3365   default:
3366     llvm_unreachable("Unknown overflow instruction!");
3367   case ISD::SADDO:
3368     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3369     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3370     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3371     break;
3372   case ISD::UADDO:
3373     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3374     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3375     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3376     break;
3377   case ISD::SSUBO:
3378     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3379     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3380     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3381     break;
3382   case ISD::USUBO:
3383     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3384     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3385     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3386     break;
3387   } // switch (...)
3388
3389   return std::make_pair(Value, OverflowCmp);
3390 }
3391
3392
3393 SDValue
3394 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3395   // Let legalize expand this if it isn't a legal type yet.
3396   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3397     return SDValue();
3398
3399   SDValue Value, OverflowCmp;
3400   SDValue ARMcc;
3401   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3402   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3403   // We use 0 and 1 as false and true values.
3404   SDValue TVal = DAG.getConstant(1, MVT::i32);
3405   SDValue FVal = DAG.getConstant(0, MVT::i32);
3406   EVT VT = Op.getValueType();
3407
3408   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3409                                  ARMcc, CCR, OverflowCmp);
3410
3411   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3412   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3413 }
3414
3415
3416 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3417   SDValue Cond = Op.getOperand(0);
3418   SDValue SelectTrue = Op.getOperand(1);
3419   SDValue SelectFalse = Op.getOperand(2);
3420   SDLoc dl(Op);
3421   unsigned Opc = Cond.getOpcode();
3422
3423   if (Cond.getResNo() == 1 &&
3424       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3425        Opc == ISD::USUBO)) {
3426     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3427       return SDValue();
3428
3429     SDValue Value, OverflowCmp;
3430     SDValue ARMcc;
3431     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3432     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3433     EVT VT = Op.getValueType();
3434
3435     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3436                    OverflowCmp, DAG);
3437   }
3438
3439   // Convert:
3440   //
3441   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3442   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3443   //
3444   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3445     const ConstantSDNode *CMOVTrue =
3446       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3447     const ConstantSDNode *CMOVFalse =
3448       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3449
3450     if (CMOVTrue && CMOVFalse) {
3451       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3452       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3453
3454       SDValue True;
3455       SDValue False;
3456       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3457         True = SelectTrue;
3458         False = SelectFalse;
3459       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3460         True = SelectFalse;
3461         False = SelectTrue;
3462       }
3463
3464       if (True.getNode() && False.getNode()) {
3465         EVT VT = Op.getValueType();
3466         SDValue ARMcc = Cond.getOperand(2);
3467         SDValue CCR = Cond.getOperand(3);
3468         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3469         assert(True.getValueType() == VT);
3470         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3471       }
3472     }
3473   }
3474
3475   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3476   // undefined bits before doing a full-word comparison with zero.
3477   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3478                      DAG.getConstant(1, Cond.getValueType()));
3479
3480   return DAG.getSelectCC(dl, Cond,
3481                          DAG.getConstant(0, Cond.getValueType()),
3482                          SelectTrue, SelectFalse, ISD::SETNE);
3483 }
3484
3485 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3486   if (CC == ISD::SETNE)
3487     return ISD::SETEQ;
3488   return ISD::getSetCCInverse(CC, true);
3489 }
3490
3491 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3492                                  bool &swpCmpOps, bool &swpVselOps) {
3493   // Start by selecting the GE condition code for opcodes that return true for
3494   // 'equality'
3495   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3496       CC == ISD::SETULE)
3497     CondCode = ARMCC::GE;
3498
3499   // and GT for opcodes that return false for 'equality'.
3500   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3501            CC == ISD::SETULT)
3502     CondCode = ARMCC::GT;
3503
3504   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3505   // to swap the compare operands.
3506   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3507       CC == ISD::SETULT)
3508     swpCmpOps = true;
3509
3510   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3511   // If we have an unordered opcode, we need to swap the operands to the VSEL
3512   // instruction (effectively negating the condition).
3513   //
3514   // This also has the effect of swapping which one of 'less' or 'greater'
3515   // returns true, so we also swap the compare operands. It also switches
3516   // whether we return true for 'equality', so we compensate by picking the
3517   // opposite condition code to our original choice.
3518   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3519       CC == ISD::SETUGT) {
3520     swpCmpOps = !swpCmpOps;
3521     swpVselOps = !swpVselOps;
3522     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3523   }
3524
3525   // 'ordered' is 'anything but unordered', so use the VS condition code and
3526   // swap the VSEL operands.
3527   if (CC == ISD::SETO) {
3528     CondCode = ARMCC::VS;
3529     swpVselOps = true;
3530   }
3531
3532   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3533   // code and swap the VSEL operands.
3534   if (CC == ISD::SETUNE) {
3535     CondCode = ARMCC::EQ;
3536     swpVselOps = true;
3537   }
3538 }
3539
3540 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3541                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3542                                    SDValue Cmp, SelectionDAG &DAG) const {
3543   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3544     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3545                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3546     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3547                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3548
3549     SDValue TrueLow = TrueVal.getValue(0);
3550     SDValue TrueHigh = TrueVal.getValue(1);
3551     SDValue FalseLow = FalseVal.getValue(0);
3552     SDValue FalseHigh = FalseVal.getValue(1);
3553
3554     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3555                               ARMcc, CCR, Cmp);
3556     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3557                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3558
3559     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3560   } else {
3561     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3562                        Cmp);
3563   }
3564 }
3565
3566 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3567   EVT VT = Op.getValueType();
3568   SDValue LHS = Op.getOperand(0);
3569   SDValue RHS = Op.getOperand(1);
3570   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3571   SDValue TrueVal = Op.getOperand(2);
3572   SDValue FalseVal = Op.getOperand(3);
3573   SDLoc dl(Op);
3574
3575   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3576     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3577                                                     dl);
3578
3579     // If softenSetCCOperands only returned one value, we should compare it to
3580     // zero.
3581     if (!RHS.getNode()) {
3582       RHS = DAG.getConstant(0, LHS.getValueType());
3583       CC = ISD::SETNE;
3584     }
3585   }
3586
3587   if (LHS.getValueType() == MVT::i32) {
3588     // Try to generate VSEL on ARMv8.
3589     // The VSEL instruction can't use all the usual ARM condition
3590     // codes: it only has two bits to select the condition code, so it's
3591     // constrained to use only GE, GT, VS and EQ.
3592     //
3593     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3594     // swap the operands of the previous compare instruction (effectively
3595     // inverting the compare condition, swapping 'less' and 'greater') and
3596     // sometimes need to swap the operands to the VSEL (which inverts the
3597     // condition in the sense of firing whenever the previous condition didn't)
3598     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3599                                       TrueVal.getValueType() == MVT::f64)) {
3600       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3601       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3602           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3603         CC = getInverseCCForVSEL(CC);
3604         std::swap(TrueVal, FalseVal);
3605       }
3606     }
3607
3608     SDValue ARMcc;
3609     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3610     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3611     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3612   }
3613
3614   ARMCC::CondCodes CondCode, CondCode2;
3615   FPCCToARMCC(CC, CondCode, CondCode2);
3616
3617   // Try to generate VSEL on ARMv8.
3618   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3619                                     TrueVal.getValueType() == MVT::f64)) {
3620     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3621     // same operands, as follows:
3622     //   c = fcmp [ogt, olt, ugt, ult] a, b
3623     //   select c, a, b
3624     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3625     // handled differently than the original code sequence.
3626     if (getTargetMachine().Options.UnsafeFPMath) {
3627       if (LHS == TrueVal && RHS == FalseVal) {
3628         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3629           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3630         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3631           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3632       } else if (LHS == FalseVal && RHS == TrueVal) {
3633         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3634           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3635         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3636           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3637       }
3638     }
3639
3640     bool swpCmpOps = false;
3641     bool swpVselOps = false;
3642     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3643
3644     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3645         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3646       if (swpCmpOps)
3647         std::swap(LHS, RHS);
3648       if (swpVselOps)
3649         std::swap(TrueVal, FalseVal);
3650     }
3651   }
3652
3653   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3654   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3655   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3656   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3657   if (CondCode2 != ARMCC::AL) {
3658     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3659     // FIXME: Needs another CMP because flag can have but one use.
3660     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3661     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3662   }
3663   return Result;
3664 }
3665
3666 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3667 /// to morph to an integer compare sequence.
3668 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3669                            const ARMSubtarget *Subtarget) {
3670   SDNode *N = Op.getNode();
3671   if (!N->hasOneUse())
3672     // Otherwise it requires moving the value from fp to integer registers.
3673     return false;
3674   if (!N->getNumValues())
3675     return false;
3676   EVT VT = Op.getValueType();
3677   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3678     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3679     // vmrs are very slow, e.g. cortex-a8.
3680     return false;
3681
3682   if (isFloatingPointZero(Op)) {
3683     SeenZero = true;
3684     return true;
3685   }
3686   return ISD::isNormalLoad(N);
3687 }
3688
3689 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3690   if (isFloatingPointZero(Op))
3691     return DAG.getConstant(0, MVT::i32);
3692
3693   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3694     return DAG.getLoad(MVT::i32, SDLoc(Op),
3695                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3696                        Ld->isVolatile(), Ld->isNonTemporal(),
3697                        Ld->isInvariant(), Ld->getAlignment());
3698
3699   llvm_unreachable("Unknown VFP cmp argument!");
3700 }
3701
3702 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3703                            SDValue &RetVal1, SDValue &RetVal2) {
3704   if (isFloatingPointZero(Op)) {
3705     RetVal1 = DAG.getConstant(0, MVT::i32);
3706     RetVal2 = DAG.getConstant(0, MVT::i32);
3707     return;
3708   }
3709
3710   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3711     SDValue Ptr = Ld->getBasePtr();
3712     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3713                           Ld->getChain(), Ptr,
3714                           Ld->getPointerInfo(),
3715                           Ld->isVolatile(), Ld->isNonTemporal(),
3716                           Ld->isInvariant(), Ld->getAlignment());
3717
3718     EVT PtrType = Ptr.getValueType();
3719     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3720     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3721                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3722     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3723                           Ld->getChain(), NewPtr,
3724                           Ld->getPointerInfo().getWithOffset(4),
3725                           Ld->isVolatile(), Ld->isNonTemporal(),
3726                           Ld->isInvariant(), NewAlign);
3727     return;
3728   }
3729
3730   llvm_unreachable("Unknown VFP cmp argument!");
3731 }
3732
3733 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3734 /// f32 and even f64 comparisons to integer ones.
3735 SDValue
3736 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3737   SDValue Chain = Op.getOperand(0);
3738   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3739   SDValue LHS = Op.getOperand(2);
3740   SDValue RHS = Op.getOperand(3);
3741   SDValue Dest = Op.getOperand(4);
3742   SDLoc dl(Op);
3743
3744   bool LHSSeenZero = false;
3745   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3746   bool RHSSeenZero = false;
3747   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3748   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3749     // If unsafe fp math optimization is enabled and there are no other uses of
3750     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3751     // to an integer comparison.
3752     if (CC == ISD::SETOEQ)
3753       CC = ISD::SETEQ;
3754     else if (CC == ISD::SETUNE)
3755       CC = ISD::SETNE;
3756
3757     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3758     SDValue ARMcc;
3759     if (LHS.getValueType() == MVT::f32) {
3760       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3761                         bitcastf32Toi32(LHS, DAG), Mask);
3762       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3763                         bitcastf32Toi32(RHS, DAG), Mask);
3764       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3765       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3766       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3767                          Chain, Dest, ARMcc, CCR, Cmp);
3768     }
3769
3770     SDValue LHS1, LHS2;
3771     SDValue RHS1, RHS2;
3772     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3773     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3774     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3775     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3776     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3777     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3778     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3779     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3780     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3781   }
3782
3783   return SDValue();
3784 }
3785
3786 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3787   SDValue Chain = Op.getOperand(0);
3788   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3789   SDValue LHS = Op.getOperand(2);
3790   SDValue RHS = Op.getOperand(3);
3791   SDValue Dest = Op.getOperand(4);
3792   SDLoc dl(Op);
3793
3794   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3795     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3796                                                     dl);
3797
3798     // If softenSetCCOperands only returned one value, we should compare it to
3799     // zero.
3800     if (!RHS.getNode()) {
3801       RHS = DAG.getConstant(0, LHS.getValueType());
3802       CC = ISD::SETNE;
3803     }
3804   }
3805
3806   if (LHS.getValueType() == MVT::i32) {
3807     SDValue ARMcc;
3808     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811                        Chain, Dest, ARMcc, CCR, Cmp);
3812   }
3813
3814   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3815
3816   if (getTargetMachine().Options.UnsafeFPMath &&
3817       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3818        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3819     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3820     if (Result.getNode())
3821       return Result;
3822   }
3823
3824   ARMCC::CondCodes CondCode, CondCode2;
3825   FPCCToARMCC(CC, CondCode, CondCode2);
3826
3827   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3828   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3829   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3830   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3831   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3832   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3833   if (CondCode2 != ARMCC::AL) {
3834     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3835     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3836     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3837   }
3838   return Res;
3839 }
3840
3841 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3842   SDValue Chain = Op.getOperand(0);
3843   SDValue Table = Op.getOperand(1);
3844   SDValue Index = Op.getOperand(2);
3845   SDLoc dl(Op);
3846
3847   EVT PTy = getPointerTy();
3848   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3849   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3850   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3851   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3852   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3853   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3854   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3855   if (Subtarget->isThumb2()) {
3856     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3857     // which does another jump to the destination. This also makes it easier
3858     // to translate it to TBB / TBH later.
3859     // FIXME: This might not work if the function is extremely large.
3860     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3861                        Addr, Op.getOperand(2), JTI, UId);
3862   }
3863   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3864     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3865                        MachinePointerInfo::getJumpTable(),
3866                        false, false, false, 0);
3867     Chain = Addr.getValue(1);
3868     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3869     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3870   } else {
3871     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3872                        MachinePointerInfo::getJumpTable(),
3873                        false, false, false, 0);
3874     Chain = Addr.getValue(1);
3875     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3876   }
3877 }
3878
3879 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3880   EVT VT = Op.getValueType();
3881   SDLoc dl(Op);
3882
3883   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3884     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3885       return Op;
3886     return DAG.UnrollVectorOp(Op.getNode());
3887   }
3888
3889   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3890          "Invalid type for custom lowering!");
3891   if (VT != MVT::v4i16)
3892     return DAG.UnrollVectorOp(Op.getNode());
3893
3894   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3895   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3896 }
3897
3898 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3899   EVT VT = Op.getValueType();
3900   if (VT.isVector())
3901     return LowerVectorFP_TO_INT(Op, DAG);
3902
3903   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3904     RTLIB::Libcall LC;
3905     if (Op.getOpcode() == ISD::FP_TO_SINT)
3906       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3907                               Op.getValueType());
3908     else
3909       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3910                               Op.getValueType());
3911     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3912                        /*isSigned*/ false, SDLoc(Op)).first;
3913   }
3914
3915   SDLoc dl(Op);
3916   unsigned Opc;
3917
3918   switch (Op.getOpcode()) {
3919   default: llvm_unreachable("Invalid opcode!");
3920   case ISD::FP_TO_SINT:
3921     Opc = ARMISD::FTOSI;
3922     break;
3923   case ISD::FP_TO_UINT:
3924     Opc = ARMISD::FTOUI;
3925     break;
3926   }
3927   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3928   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3929 }
3930
3931 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3932   EVT VT = Op.getValueType();
3933   SDLoc dl(Op);
3934
3935   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3936     if (VT.getVectorElementType() == MVT::f32)
3937       return Op;
3938     return DAG.UnrollVectorOp(Op.getNode());
3939   }
3940
3941   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3942          "Invalid type for custom lowering!");
3943   if (VT != MVT::v4f32)
3944     return DAG.UnrollVectorOp(Op.getNode());
3945
3946   unsigned CastOpc;
3947   unsigned Opc;
3948   switch (Op.getOpcode()) {
3949   default: llvm_unreachable("Invalid opcode!");
3950   case ISD::SINT_TO_FP:
3951     CastOpc = ISD::SIGN_EXTEND;
3952     Opc = ISD::SINT_TO_FP;
3953     break;
3954   case ISD::UINT_TO_FP:
3955     CastOpc = ISD::ZERO_EXTEND;
3956     Opc = ISD::UINT_TO_FP;
3957     break;
3958   }
3959
3960   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3961   return DAG.getNode(Opc, dl, VT, Op);
3962 }
3963
3964 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3965   EVT VT = Op.getValueType();
3966   if (VT.isVector())
3967     return LowerVectorINT_TO_FP(Op, DAG);
3968
3969   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3970     RTLIB::Libcall LC;
3971     if (Op.getOpcode() == ISD::SINT_TO_FP)
3972       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3973                               Op.getValueType());
3974     else
3975       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3976                               Op.getValueType());
3977     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3978                        /*isSigned*/ false, SDLoc(Op)).first;
3979   }
3980
3981   SDLoc dl(Op);
3982   unsigned Opc;
3983
3984   switch (Op.getOpcode()) {
3985   default: llvm_unreachable("Invalid opcode!");
3986   case ISD::SINT_TO_FP:
3987     Opc = ARMISD::SITOF;
3988     break;
3989   case ISD::UINT_TO_FP:
3990     Opc = ARMISD::UITOF;
3991     break;
3992   }
3993
3994   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3995   return DAG.getNode(Opc, dl, VT, Op);
3996 }
3997
3998 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3999   // Implement fcopysign with a fabs and a conditional fneg.
4000   SDValue Tmp0 = Op.getOperand(0);
4001   SDValue Tmp1 = Op.getOperand(1);
4002   SDLoc dl(Op);
4003   EVT VT = Op.getValueType();
4004   EVT SrcVT = Tmp1.getValueType();
4005   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4006     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4007   bool UseNEON = !InGPR && Subtarget->hasNEON();
4008
4009   if (UseNEON) {
4010     // Use VBSL to copy the sign bit.
4011     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4012     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4013                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4014     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4015     if (VT == MVT::f64)
4016       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4017                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4018                          DAG.getConstant(32, MVT::i32));
4019     else /*if (VT == MVT::f32)*/
4020       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4021     if (SrcVT == MVT::f32) {
4022       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4023       if (VT == MVT::f64)
4024         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4025                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4026                            DAG.getConstant(32, MVT::i32));
4027     } else if (VT == MVT::f32)
4028       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4029                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4030                          DAG.getConstant(32, MVT::i32));
4031     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4032     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4033
4034     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4035                                             MVT::i32);
4036     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4037     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4038                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4039
4040     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4041                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4042                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4043     if (VT == MVT::f32) {
4044       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4045       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4046                         DAG.getConstant(0, MVT::i32));
4047     } else {
4048       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4049     }
4050
4051     return Res;
4052   }
4053
4054   // Bitcast operand 1 to i32.
4055   if (SrcVT == MVT::f64)
4056     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4057                        Tmp1).getValue(1);
4058   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4059
4060   // Or in the signbit with integer operations.
4061   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4062   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4063   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4064   if (VT == MVT::f32) {
4065     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4066                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4067     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4068                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4069   }
4070
4071   // f64: Or the high part with signbit and then combine two parts.
4072   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4073                      Tmp0);
4074   SDValue Lo = Tmp0.getValue(0);
4075   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4076   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4077   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4078 }
4079
4080 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4081   MachineFunction &MF = DAG.getMachineFunction();
4082   MachineFrameInfo *MFI = MF.getFrameInfo();
4083   MFI->setReturnAddressIsTaken(true);
4084
4085   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4086     return SDValue();
4087
4088   EVT VT = Op.getValueType();
4089   SDLoc dl(Op);
4090   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4091   if (Depth) {
4092     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4093     SDValue Offset = DAG.getConstant(4, MVT::i32);
4094     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4095                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4096                        MachinePointerInfo(), false, false, false, 0);
4097   }
4098
4099   // Return LR, which contains the return address. Mark it an implicit live-in.
4100   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4101   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4102 }
4103
4104 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4105   const ARMBaseRegisterInfo &ARI =
4106     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4107   MachineFunction &MF = DAG.getMachineFunction();
4108   MachineFrameInfo *MFI = MF.getFrameInfo();
4109   MFI->setFrameAddressIsTaken(true);
4110
4111   EVT VT = Op.getValueType();
4112   SDLoc dl(Op);  // FIXME probably not meaningful
4113   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4114   unsigned FrameReg = ARI.getFrameRegister(MF);
4115   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4116   while (Depth--)
4117     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4118                             MachinePointerInfo(),
4119                             false, false, false, 0);
4120   return FrameAddr;
4121 }
4122
4123 // FIXME? Maybe this could be a TableGen attribute on some registers and
4124 // this table could be generated automatically from RegInfo.
4125 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4126                                               EVT VT) const {
4127   unsigned Reg = StringSwitch<unsigned>(RegName)
4128                        .Case("sp", ARM::SP)
4129                        .Default(0);
4130   if (Reg)
4131     return Reg;
4132   report_fatal_error("Invalid register name global variable");
4133 }
4134
4135 /// ExpandBITCAST - If the target supports VFP, this function is called to
4136 /// expand a bit convert where either the source or destination type is i64 to
4137 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4138 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4139 /// vectors), since the legalizer won't know what to do with that.
4140 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4142   SDLoc dl(N);
4143   SDValue Op = N->getOperand(0);
4144
4145   // This function is only supposed to be called for i64 types, either as the
4146   // source or destination of the bit convert.
4147   EVT SrcVT = Op.getValueType();
4148   EVT DstVT = N->getValueType(0);
4149   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4150          "ExpandBITCAST called for non-i64 type");
4151
4152   // Turn i64->f64 into VMOVDRR.
4153   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4154     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155                              DAG.getConstant(0, MVT::i32));
4156     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4157                              DAG.getConstant(1, MVT::i32));
4158     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4159                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4160   }
4161
4162   // Turn f64->i64 into VMOVRRD.
4163   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4164     SDValue Cvt;
4165     if (TLI.isBigEndian() && SrcVT.isVector() &&
4166         SrcVT.getVectorNumElements() > 1)
4167       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168                         DAG.getVTList(MVT::i32, MVT::i32),
4169                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4170     else
4171       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4172                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4173     // Merge the pieces into a single i64 value.
4174     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4175   }
4176
4177   return SDValue();
4178 }
4179
4180 /// getZeroVector - Returns a vector of specified type with all zero elements.
4181 /// Zero vectors are used to represent vector negation and in those cases
4182 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4183 /// not support i64 elements, so sometimes the zero vectors will need to be
4184 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4185 /// zero vector.
4186 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4187   assert(VT.isVector() && "Expected a vector type");
4188   // The canonical modified immediate encoding of a zero vector is....0!
4189   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4190   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4191   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4192   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4193 }
4194
4195 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4196 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4197 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4198                                                 SelectionDAG &DAG) const {
4199   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4200   EVT VT = Op.getValueType();
4201   unsigned VTBits = VT.getSizeInBits();
4202   SDLoc dl(Op);
4203   SDValue ShOpLo = Op.getOperand(0);
4204   SDValue ShOpHi = Op.getOperand(1);
4205   SDValue ShAmt  = Op.getOperand(2);
4206   SDValue ARMcc;
4207   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4208
4209   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4210
4211   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4212                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4213   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4214   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4215                                    DAG.getConstant(VTBits, MVT::i32));
4216   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4217   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4218   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4219
4220   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4221   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4222                           ARMcc, DAG, dl);
4223   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4224   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4225                            CCR, Cmp);
4226
4227   SDValue Ops[2] = { Lo, Hi };
4228   return DAG.getMergeValues(Ops, dl);
4229 }
4230
4231 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4232 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4233 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4234                                                SelectionDAG &DAG) const {
4235   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4236   EVT VT = Op.getValueType();
4237   unsigned VTBits = VT.getSizeInBits();
4238   SDLoc dl(Op);
4239   SDValue ShOpLo = Op.getOperand(0);
4240   SDValue ShOpHi = Op.getOperand(1);
4241   SDValue ShAmt  = Op.getOperand(2);
4242   SDValue ARMcc;
4243
4244   assert(Op.getOpcode() == ISD::SHL_PARTS);
4245   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4247   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4248   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249                                    DAG.getConstant(VTBits, MVT::i32));
4250   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4251   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4252
4253   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4254   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4256                           ARMcc, DAG, dl);
4257   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4258   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4259                            CCR, Cmp);
4260
4261   SDValue Ops[2] = { Lo, Hi };
4262   return DAG.getMergeValues(Ops, dl);
4263 }
4264
4265 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4266                                             SelectionDAG &DAG) const {
4267   // The rounding mode is in bits 23:22 of the FPSCR.
4268   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4269   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4270   // so that the shift + and get folded into a bitfield extract.
4271   SDLoc dl(Op);
4272   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4273                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4274                                               MVT::i32));
4275   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4276                                   DAG.getConstant(1U << 22, MVT::i32));
4277   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4278                               DAG.getConstant(22, MVT::i32));
4279   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4280                      DAG.getConstant(3, MVT::i32));
4281 }
4282
4283 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4284                          const ARMSubtarget *ST) {
4285   EVT VT = N->getValueType(0);
4286   SDLoc dl(N);
4287
4288   if (!ST->hasV6T2Ops())
4289     return SDValue();
4290
4291   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4292   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4293 }
4294
4295 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4296 /// for each 16-bit element from operand, repeated.  The basic idea is to
4297 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4298 ///
4299 /// Trace for v4i16:
4300 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4301 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4302 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4303 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4304 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4305 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4306 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4307 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4308 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4309   EVT VT = N->getValueType(0);
4310   SDLoc DL(N);
4311
4312   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4313   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4314   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4315   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4316   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4317   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4318 }
4319
4320 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4321 /// bit-count for each 16-bit element from the operand.  We need slightly
4322 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4323 /// 64/128-bit registers.
4324 ///
4325 /// Trace for v4i16:
4326 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4327 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4328 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4329 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4330 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4331   EVT VT = N->getValueType(0);
4332   SDLoc DL(N);
4333
4334   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4335   if (VT.is64BitVector()) {
4336     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4337     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4338                        DAG.getIntPtrConstant(0));
4339   } else {
4340     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4341                                     BitCounts, DAG.getIntPtrConstant(0));
4342     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4343   }
4344 }
4345
4346 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4347 /// bit-count for each 32-bit element from the operand.  The idea here is
4348 /// to split the vector into 16-bit elements, leverage the 16-bit count
4349 /// routine, and then combine the results.
4350 ///
4351 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4352 /// input    = [v0    v1    ] (vi: 32-bit elements)
4353 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4354 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4355 /// vrev: N0 = [k1 k0 k3 k2 ]
4356 ///            [k0 k1 k2 k3 ]
4357 ///       N1 =+[k1 k0 k3 k2 ]
4358 ///            [k0 k2 k1 k3 ]
4359 ///       N2 =+[k1 k3 k0 k2 ]
4360 ///            [k0    k2    k1    k3    ]
4361 /// Extended =+[k1    k3    k0    k2    ]
4362 ///            [k0    k2    ]
4363 /// Extracted=+[k1    k3    ]
4364 ///
4365 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4366   EVT VT = N->getValueType(0);
4367   SDLoc DL(N);
4368
4369   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4370
4371   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4372   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4373   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4374   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4375   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4376
4377   if (VT.is64BitVector()) {
4378     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4379     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4380                        DAG.getIntPtrConstant(0));
4381   } else {
4382     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4383                                     DAG.getIntPtrConstant(0));
4384     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4385   }
4386 }
4387
4388 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4389                           const ARMSubtarget *ST) {
4390   EVT VT = N->getValueType(0);
4391
4392   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4393   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4394           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4395          "Unexpected type for custom ctpop lowering");
4396
4397   if (VT.getVectorElementType() == MVT::i32)
4398     return lowerCTPOP32BitElements(N, DAG);
4399   else
4400     return lowerCTPOP16BitElements(N, DAG);
4401 }
4402
4403 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4404                           const ARMSubtarget *ST) {
4405   EVT VT = N->getValueType(0);
4406   SDLoc dl(N);
4407
4408   if (!VT.isVector())
4409     return SDValue();
4410
4411   // Lower vector shifts on NEON to use VSHL.
4412   assert(ST->hasNEON() && "unexpected vector shift");
4413
4414   // Left shifts translate directly to the vshiftu intrinsic.
4415   if (N->getOpcode() == ISD::SHL)
4416     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4417                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4418                        N->getOperand(0), N->getOperand(1));
4419
4420   assert((N->getOpcode() == ISD::SRA ||
4421           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4422
4423   // NEON uses the same intrinsics for both left and right shifts.  For
4424   // right shifts, the shift amounts are negative, so negate the vector of
4425   // shift amounts.
4426   EVT ShiftVT = N->getOperand(1).getValueType();
4427   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4428                                      getZeroVector(ShiftVT, DAG, dl),
4429                                      N->getOperand(1));
4430   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4431                              Intrinsic::arm_neon_vshifts :
4432                              Intrinsic::arm_neon_vshiftu);
4433   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4434                      DAG.getConstant(vshiftInt, MVT::i32),
4435                      N->getOperand(0), NegatedCount);
4436 }
4437
4438 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4439                                 const ARMSubtarget *ST) {
4440   EVT VT = N->getValueType(0);
4441   SDLoc dl(N);
4442
4443   // We can get here for a node like i32 = ISD::SHL i32, i64
4444   if (VT != MVT::i64)
4445     return SDValue();
4446
4447   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4448          "Unknown shift to lower!");
4449
4450   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4451   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4452       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4453     return SDValue();
4454
4455   // If we are in thumb mode, we don't have RRX.
4456   if (ST->isThumb1Only()) return SDValue();
4457
4458   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4459   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4460                            DAG.getConstant(0, MVT::i32));
4461   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4462                            DAG.getConstant(1, MVT::i32));
4463
4464   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4465   // captures the result into a carry flag.
4466   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4467   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4468
4469   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4470   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4471
4472   // Merge the pieces into a single i64 value.
4473  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4474 }
4475
4476 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4477   SDValue TmpOp0, TmpOp1;
4478   bool Invert = false;
4479   bool Swap = false;
4480   unsigned Opc = 0;
4481
4482   SDValue Op0 = Op.getOperand(0);
4483   SDValue Op1 = Op.getOperand(1);
4484   SDValue CC = Op.getOperand(2);
4485   EVT VT = Op.getValueType();
4486   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4487   SDLoc dl(Op);
4488
4489   if (Op1.getValueType().isFloatingPoint()) {
4490     switch (SetCCOpcode) {
4491     default: llvm_unreachable("Illegal FP comparison");
4492     case ISD::SETUNE:
4493     case ISD::SETNE:  Invert = true; // Fallthrough
4494     case ISD::SETOEQ:
4495     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4496     case ISD::SETOLT:
4497     case ISD::SETLT: Swap = true; // Fallthrough
4498     case ISD::SETOGT:
4499     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4500     case ISD::SETOLE:
4501     case ISD::SETLE:  Swap = true; // Fallthrough
4502     case ISD::SETOGE:
4503     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4504     case ISD::SETUGE: Swap = true; // Fallthrough
4505     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4506     case ISD::SETUGT: Swap = true; // Fallthrough
4507     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4508     case ISD::SETUEQ: Invert = true; // Fallthrough
4509     case ISD::SETONE:
4510       // Expand this to (OLT | OGT).
4511       TmpOp0 = Op0;
4512       TmpOp1 = Op1;
4513       Opc = ISD::OR;
4514       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4515       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4516       break;
4517     case ISD::SETUO: Invert = true; // Fallthrough
4518     case ISD::SETO:
4519       // Expand this to (OLT | OGE).
4520       TmpOp0 = Op0;
4521       TmpOp1 = Op1;
4522       Opc = ISD::OR;
4523       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4524       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4525       break;
4526     }
4527   } else {
4528     // Integer comparisons.
4529     switch (SetCCOpcode) {
4530     default: llvm_unreachable("Illegal integer comparison");
4531     case ISD::SETNE:  Invert = true;
4532     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4533     case ISD::SETLT:  Swap = true;
4534     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4535     case ISD::SETLE:  Swap = true;
4536     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4537     case ISD::SETULT: Swap = true;
4538     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4539     case ISD::SETULE: Swap = true;
4540     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4541     }
4542
4543     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4544     if (Opc == ARMISD::VCEQ) {
4545
4546       SDValue AndOp;
4547       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4548         AndOp = Op0;
4549       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4550         AndOp = Op1;
4551
4552       // Ignore bitconvert.
4553       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4554         AndOp = AndOp.getOperand(0);
4555
4556       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4557         Opc = ARMISD::VTST;
4558         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4559         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4560         Invert = !Invert;
4561       }
4562     }
4563   }
4564
4565   if (Swap)
4566     std::swap(Op0, Op1);
4567
4568   // If one of the operands is a constant vector zero, attempt to fold the
4569   // comparison to a specialized compare-against-zero form.
4570   SDValue SingleOp;
4571   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4572     SingleOp = Op0;
4573   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4574     if (Opc == ARMISD::VCGE)
4575       Opc = ARMISD::VCLEZ;
4576     else if (Opc == ARMISD::VCGT)
4577       Opc = ARMISD::VCLTZ;
4578     SingleOp = Op1;
4579   }
4580
4581   SDValue Result;
4582   if (SingleOp.getNode()) {
4583     switch (Opc) {
4584     case ARMISD::VCEQ:
4585       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4586     case ARMISD::VCGE:
4587       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4588     case ARMISD::VCLEZ:
4589       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4590     case ARMISD::VCGT:
4591       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4592     case ARMISD::VCLTZ:
4593       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4594     default:
4595       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4596     }
4597   } else {
4598      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4599   }
4600
4601   if (Invert)
4602     Result = DAG.getNOT(dl, Result, VT);
4603
4604   return Result;
4605 }
4606
4607 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4608 /// valid vector constant for a NEON instruction with a "modified immediate"
4609 /// operand (e.g., VMOV).  If so, return the encoded value.
4610 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4611                                  unsigned SplatBitSize, SelectionDAG &DAG,
4612                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4613   unsigned OpCmode, Imm;
4614
4615   // SplatBitSize is set to the smallest size that splats the vector, so a
4616   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4617   // immediate instructions others than VMOV do not support the 8-bit encoding
4618   // of a zero vector, and the default encoding of zero is supposed to be the
4619   // 32-bit version.
4620   if (SplatBits == 0)
4621     SplatBitSize = 32;
4622
4623   switch (SplatBitSize) {
4624   case 8:
4625     if (type != VMOVModImm)
4626       return SDValue();
4627     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4628     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4629     OpCmode = 0xe;
4630     Imm = SplatBits;
4631     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4632     break;
4633
4634   case 16:
4635     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4636     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4637     if ((SplatBits & ~0xff) == 0) {
4638       // Value = 0x00nn: Op=x, Cmode=100x.
4639       OpCmode = 0x8;
4640       Imm = SplatBits;
4641       break;
4642     }
4643     if ((SplatBits & ~0xff00) == 0) {
4644       // Value = 0xnn00: Op=x, Cmode=101x.
4645       OpCmode = 0xa;
4646       Imm = SplatBits >> 8;
4647       break;
4648     }
4649     return SDValue();
4650
4651   case 32:
4652     // NEON's 32-bit VMOV supports splat values where:
4653     // * only one byte is nonzero, or
4654     // * the least significant byte is 0xff and the second byte is nonzero, or
4655     // * the least significant 2 bytes are 0xff and the third is nonzero.
4656     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4657     if ((SplatBits & ~0xff) == 0) {
4658       // Value = 0x000000nn: Op=x, Cmode=000x.
4659       OpCmode = 0;
4660       Imm = SplatBits;
4661       break;
4662     }
4663     if ((SplatBits & ~0xff00) == 0) {
4664       // Value = 0x0000nn00: Op=x, Cmode=001x.
4665       OpCmode = 0x2;
4666       Imm = SplatBits >> 8;
4667       break;
4668     }
4669     if ((SplatBits & ~0xff0000) == 0) {
4670       // Value = 0x00nn0000: Op=x, Cmode=010x.
4671       OpCmode = 0x4;
4672       Imm = SplatBits >> 16;
4673       break;
4674     }
4675     if ((SplatBits & ~0xff000000) == 0) {
4676       // Value = 0xnn000000: Op=x, Cmode=011x.
4677       OpCmode = 0x6;
4678       Imm = SplatBits >> 24;
4679       break;
4680     }
4681
4682     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4683     if (type == OtherModImm) return SDValue();
4684
4685     if ((SplatBits & ~0xffff) == 0 &&
4686         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4687       // Value = 0x0000nnff: Op=x, Cmode=1100.
4688       OpCmode = 0xc;
4689       Imm = SplatBits >> 8;
4690       break;
4691     }
4692
4693     if ((SplatBits & ~0xffffff) == 0 &&
4694         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4695       // Value = 0x00nnffff: Op=x, Cmode=1101.
4696       OpCmode = 0xd;
4697       Imm = SplatBits >> 16;
4698       break;
4699     }
4700
4701     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4702     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4703     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4704     // and fall through here to test for a valid 64-bit splat.  But, then the
4705     // caller would also need to check and handle the change in size.
4706     return SDValue();
4707
4708   case 64: {
4709     if (type != VMOVModImm)
4710       return SDValue();
4711     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4712     uint64_t BitMask = 0xff;
4713     uint64_t Val = 0;
4714     unsigned ImmMask = 1;
4715     Imm = 0;
4716     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4717       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4718         Val |= BitMask;
4719         Imm |= ImmMask;
4720       } else if ((SplatBits & BitMask) != 0) {
4721         return SDValue();
4722       }
4723       BitMask <<= 8;
4724       ImmMask <<= 1;
4725     }
4726
4727     if (DAG.getTargetLoweringInfo().isBigEndian())
4728       // swap higher and lower 32 bit word
4729       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4730
4731     // Op=1, Cmode=1110.
4732     OpCmode = 0x1e;
4733     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4734     break;
4735   }
4736
4737   default:
4738     llvm_unreachable("unexpected size for isNEONModifiedImm");
4739   }
4740
4741   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4742   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4743 }
4744
4745 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4746                                            const ARMSubtarget *ST) const {
4747   if (!ST->hasVFP3())
4748     return SDValue();
4749
4750   bool IsDouble = Op.getValueType() == MVT::f64;
4751   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4752
4753   // Use the default (constant pool) lowering for double constants when we have
4754   // an SP-only FPU
4755   if (IsDouble && Subtarget->isFPOnlySP())
4756     return SDValue();
4757
4758   // Try splatting with a VMOV.f32...
4759   APFloat FPVal = CFP->getValueAPF();
4760   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4761
4762   if (ImmVal != -1) {
4763     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4764       // We have code in place to select a valid ConstantFP already, no need to
4765       // do any mangling.
4766       return Op;
4767     }
4768
4769     // It's a float and we are trying to use NEON operations where
4770     // possible. Lower it to a splat followed by an extract.
4771     SDLoc DL(Op);
4772     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4773     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4774                                       NewVal);
4775     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4776                        DAG.getConstant(0, MVT::i32));
4777   }
4778
4779   // The rest of our options are NEON only, make sure that's allowed before
4780   // proceeding..
4781   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4782     return SDValue();
4783
4784   EVT VMovVT;
4785   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4786
4787   // It wouldn't really be worth bothering for doubles except for one very
4788   // important value, which does happen to match: 0.0. So make sure we don't do
4789   // anything stupid.
4790   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4791     return SDValue();
4792
4793   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4794   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4795                                      false, VMOVModImm);
4796   if (NewVal != SDValue()) {
4797     SDLoc DL(Op);
4798     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4799                                       NewVal);
4800     if (IsDouble)
4801       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4802
4803     // It's a float: cast and extract a vector element.
4804     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4805                                        VecConstant);
4806     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4807                        DAG.getConstant(0, MVT::i32));
4808   }
4809
4810   // Finally, try a VMVN.i32
4811   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4812                              false, VMVNModImm);
4813   if (NewVal != SDValue()) {
4814     SDLoc DL(Op);
4815     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4816
4817     if (IsDouble)
4818       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4819
4820     // It's a float: cast and extract a vector element.
4821     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4822                                        VecConstant);
4823     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4824                        DAG.getConstant(0, MVT::i32));
4825   }
4826
4827   return SDValue();
4828 }
4829
4830 // check if an VEXT instruction can handle the shuffle mask when the
4831 // vector sources of the shuffle are the same.
4832 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4833   unsigned NumElts = VT.getVectorNumElements();
4834
4835   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4836   if (M[0] < 0)
4837     return false;
4838
4839   Imm = M[0];
4840
4841   // If this is a VEXT shuffle, the immediate value is the index of the first
4842   // element.  The other shuffle indices must be the successive elements after
4843   // the first one.
4844   unsigned ExpectedElt = Imm;
4845   for (unsigned i = 1; i < NumElts; ++i) {
4846     // Increment the expected index.  If it wraps around, just follow it
4847     // back to index zero and keep going.
4848     ++ExpectedElt;
4849     if (ExpectedElt == NumElts)
4850       ExpectedElt = 0;
4851
4852     if (M[i] < 0) continue; // ignore UNDEF indices
4853     if (ExpectedElt != static_cast<unsigned>(M[i]))
4854       return false;
4855   }
4856
4857   return true;
4858 }
4859
4860
4861 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4862                        bool &ReverseVEXT, unsigned &Imm) {
4863   unsigned NumElts = VT.getVectorNumElements();
4864   ReverseVEXT = false;
4865
4866   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4867   if (M[0] < 0)
4868     return false;
4869
4870   Imm = M[0];
4871
4872   // If this is a VEXT shuffle, the immediate value is the index of the first
4873   // element.  The other shuffle indices must be the successive elements after
4874   // the first one.
4875   unsigned ExpectedElt = Imm;
4876   for (unsigned i = 1; i < NumElts; ++i) {
4877     // Increment the expected index.  If it wraps around, it may still be
4878     // a VEXT but the source vectors must be swapped.
4879     ExpectedElt += 1;
4880     if (ExpectedElt == NumElts * 2) {
4881       ExpectedElt = 0;
4882       ReverseVEXT = true;
4883     }
4884
4885     if (M[i] < 0) continue; // ignore UNDEF indices
4886     if (ExpectedElt != static_cast<unsigned>(M[i]))
4887       return false;
4888   }
4889
4890   // Adjust the index value if the source operands will be swapped.
4891   if (ReverseVEXT)
4892     Imm -= NumElts;
4893
4894   return true;
4895 }
4896
4897 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4898 /// instruction with the specified blocksize.  (The order of the elements
4899 /// within each block of the vector is reversed.)
4900 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4901   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4902          "Only possible block sizes for VREV are: 16, 32, 64");
4903
4904   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4905   if (EltSz == 64)
4906     return false;
4907
4908   unsigned NumElts = VT.getVectorNumElements();
4909   unsigned BlockElts = M[0] + 1;
4910   // If the first shuffle index is UNDEF, be optimistic.
4911   if (M[0] < 0)
4912     BlockElts = BlockSize / EltSz;
4913
4914   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4915     return false;
4916
4917   for (unsigned i = 0; i < NumElts; ++i) {
4918     if (M[i] < 0) continue; // ignore UNDEF indices
4919     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4920       return false;
4921   }
4922
4923   return true;
4924 }
4925
4926 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4927   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4928   // range, then 0 is placed into the resulting vector. So pretty much any mask
4929   // of 8 elements can work here.
4930   return VT == MVT::v8i8 && M.size() == 8;
4931 }
4932
4933 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4934   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4935   if (EltSz == 64)
4936     return false;
4937
4938   unsigned NumElts = VT.getVectorNumElements();
4939   WhichResult = (M[0] == 0 ? 0 : 1);
4940   for (unsigned i = 0; i < NumElts; i += 2) {
4941     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4942         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4943       return false;
4944   }
4945   return true;
4946 }
4947
4948 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4949 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4950 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4951 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4952   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4953   if (EltSz == 64)
4954     return false;
4955
4956   unsigned NumElts = VT.getVectorNumElements();
4957   WhichResult = (M[0] == 0 ? 0 : 1);
4958   for (unsigned i = 0; i < NumElts; i += 2) {
4959     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4960         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4961       return false;
4962   }
4963   return true;
4964 }
4965
4966 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4967   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4968   if (EltSz == 64)
4969     return false;
4970
4971   unsigned NumElts = VT.getVectorNumElements();
4972   WhichResult = (M[0] == 0 ? 0 : 1);
4973   for (unsigned i = 0; i != NumElts; ++i) {
4974     if (M[i] < 0) continue; // ignore UNDEF indices
4975     if ((unsigned) M[i] != 2 * i + WhichResult)
4976       return false;
4977   }
4978
4979   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4980   if (VT.is64BitVector() && EltSz == 32)
4981     return false;
4982
4983   return true;
4984 }
4985
4986 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4987 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4988 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4989 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4990   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4991   if (EltSz == 64)
4992     return false;
4993
4994   unsigned Half = VT.getVectorNumElements() / 2;
4995   WhichResult = (M[0] == 0 ? 0 : 1);
4996   for (unsigned j = 0; j != 2; ++j) {
4997     unsigned Idx = WhichResult;
4998     for (unsigned i = 0; i != Half; ++i) {
4999       int MIdx = M[i + j * Half];
5000       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5001         return false;
5002       Idx += 2;
5003     }
5004   }
5005
5006   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5007   if (VT.is64BitVector() && EltSz == 32)
5008     return false;
5009
5010   return true;
5011 }
5012
5013 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5014   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5015   if (EltSz == 64)
5016     return false;
5017
5018   unsigned NumElts = VT.getVectorNumElements();
5019   WhichResult = (M[0] == 0 ? 0 : 1);
5020   unsigned Idx = WhichResult * NumElts / 2;
5021   for (unsigned i = 0; i != NumElts; i += 2) {
5022     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5023         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5024       return false;
5025     Idx += 1;
5026   }
5027
5028   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5029   if (VT.is64BitVector() && EltSz == 32)
5030     return false;
5031
5032   return true;
5033 }
5034
5035 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5036 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5037 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5038 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5039   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5040   if (EltSz == 64)
5041     return false;
5042
5043   unsigned NumElts = VT.getVectorNumElements();
5044   WhichResult = (M[0] == 0 ? 0 : 1);
5045   unsigned Idx = WhichResult * NumElts / 2;
5046   for (unsigned i = 0; i != NumElts; i += 2) {
5047     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5048         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5049       return false;
5050     Idx += 1;
5051   }
5052
5053   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5054   if (VT.is64BitVector() && EltSz == 32)
5055     return false;
5056
5057   return true;
5058 }
5059
5060 /// \return true if this is a reverse operation on an vector.
5061 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5062   unsigned NumElts = VT.getVectorNumElements();
5063   // Make sure the mask has the right size.
5064   if (NumElts != M.size())
5065       return false;
5066
5067   // Look for <15, ..., 3, -1, 1, 0>.
5068   for (unsigned i = 0; i != NumElts; ++i)
5069     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5070       return false;
5071
5072   return true;
5073 }
5074
5075 // If N is an integer constant that can be moved into a register in one
5076 // instruction, return an SDValue of such a constant (will become a MOV
5077 // instruction).  Otherwise return null.
5078 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5079                                      const ARMSubtarget *ST, SDLoc dl) {
5080   uint64_t Val;
5081   if (!isa<ConstantSDNode>(N))
5082     return SDValue();
5083   Val = cast<ConstantSDNode>(N)->getZExtValue();
5084
5085   if (ST->isThumb1Only()) {
5086     if (Val <= 255 || ~Val <= 255)
5087       return DAG.getConstant(Val, MVT::i32);
5088   } else {
5089     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5090       return DAG.getConstant(Val, MVT::i32);
5091   }
5092   return SDValue();
5093 }
5094
5095 // If this is a case we can't handle, return null and let the default
5096 // expansion code take care of it.
5097 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5098                                              const ARMSubtarget *ST) const {
5099   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5100   SDLoc dl(Op);
5101   EVT VT = Op.getValueType();
5102
5103   APInt SplatBits, SplatUndef;
5104   unsigned SplatBitSize;
5105   bool HasAnyUndefs;
5106   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5107     if (SplatBitSize <= 64) {
5108       // Check if an immediate VMOV works.
5109       EVT VmovVT;
5110       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5111                                       SplatUndef.getZExtValue(), SplatBitSize,
5112                                       DAG, VmovVT, VT.is128BitVector(),
5113                                       VMOVModImm);
5114       if (Val.getNode()) {
5115         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5116         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5117       }
5118
5119       // Try an immediate VMVN.
5120       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5121       Val = isNEONModifiedImm(NegatedImm,
5122                                       SplatUndef.getZExtValue(), SplatBitSize,
5123                                       DAG, VmovVT, VT.is128BitVector(),
5124                                       VMVNModImm);
5125       if (Val.getNode()) {
5126         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5127         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5128       }
5129
5130       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5131       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5132         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5133         if (ImmVal != -1) {
5134           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5135           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5136         }
5137       }
5138     }
5139   }
5140
5141   // Scan through the operands to see if only one value is used.
5142   //
5143   // As an optimisation, even if more than one value is used it may be more
5144   // profitable to splat with one value then change some lanes.
5145   //
5146   // Heuristically we decide to do this if the vector has a "dominant" value,
5147   // defined as splatted to more than half of the lanes.
5148   unsigned NumElts = VT.getVectorNumElements();
5149   bool isOnlyLowElement = true;
5150   bool usesOnlyOneValue = true;
5151   bool hasDominantValue = false;
5152   bool isConstant = true;
5153
5154   // Map of the number of times a particular SDValue appears in the
5155   // element list.
5156   DenseMap<SDValue, unsigned> ValueCounts;
5157   SDValue Value;
5158   for (unsigned i = 0; i < NumElts; ++i) {
5159     SDValue V = Op.getOperand(i);
5160     if (V.getOpcode() == ISD::UNDEF)
5161       continue;
5162     if (i > 0)
5163       isOnlyLowElement = false;
5164     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5165       isConstant = false;
5166
5167     ValueCounts.insert(std::make_pair(V, 0));
5168     unsigned &Count = ValueCounts[V];
5169
5170     // Is this value dominant? (takes up more than half of the lanes)
5171     if (++Count > (NumElts / 2)) {
5172       hasDominantValue = true;
5173       Value = V;
5174     }
5175   }
5176   if (ValueCounts.size() != 1)
5177     usesOnlyOneValue = false;
5178   if (!Value.getNode() && ValueCounts.size() > 0)
5179     Value = ValueCounts.begin()->first;
5180
5181   if (ValueCounts.size() == 0)
5182     return DAG.getUNDEF(VT);
5183
5184   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5185   // Keep going if we are hitting this case.
5186   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5187     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5188
5189   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5190
5191   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5192   // i32 and try again.
5193   if (hasDominantValue && EltSize <= 32) {
5194     if (!isConstant) {
5195       SDValue N;
5196
5197       // If we are VDUPing a value that comes directly from a vector, that will
5198       // cause an unnecessary move to and from a GPR, where instead we could
5199       // just use VDUPLANE. We can only do this if the lane being extracted
5200       // is at a constant index, as the VDUP from lane instructions only have
5201       // constant-index forms.
5202       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5203           isa<ConstantSDNode>(Value->getOperand(1))) {
5204         // We need to create a new undef vector to use for the VDUPLANE if the
5205         // size of the vector from which we get the value is different than the
5206         // size of the vector that we need to create. We will insert the element
5207         // such that the register coalescer will remove unnecessary copies.
5208         if (VT != Value->getOperand(0).getValueType()) {
5209           ConstantSDNode *constIndex;
5210           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5211           assert(constIndex && "The index is not a constant!");
5212           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5213                              VT.getVectorNumElements();
5214           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5215                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5216                         Value, DAG.getConstant(index, MVT::i32)),
5217                            DAG.getConstant(index, MVT::i32));
5218         } else
5219           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5220                         Value->getOperand(0), Value->getOperand(1));
5221       } else
5222         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5223
5224       if (!usesOnlyOneValue) {
5225         // The dominant value was splatted as 'N', but we now have to insert
5226         // all differing elements.
5227         for (unsigned I = 0; I < NumElts; ++I) {
5228           if (Op.getOperand(I) == Value)
5229             continue;
5230           SmallVector<SDValue, 3> Ops;
5231           Ops.push_back(N);
5232           Ops.push_back(Op.getOperand(I));
5233           Ops.push_back(DAG.getConstant(I, MVT::i32));
5234           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5235         }
5236       }
5237       return N;
5238     }
5239     if (VT.getVectorElementType().isFloatingPoint()) {
5240       SmallVector<SDValue, 8> Ops;
5241       for (unsigned i = 0; i < NumElts; ++i)
5242         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5243                                   Op.getOperand(i)));
5244       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5245       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5246       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5247       if (Val.getNode())
5248         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5249     }
5250     if (usesOnlyOneValue) {
5251       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5252       if (isConstant && Val.getNode())
5253         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5254     }
5255   }
5256
5257   // If all elements are constants and the case above didn't get hit, fall back
5258   // to the default expansion, which will generate a load from the constant
5259   // pool.
5260   if (isConstant)
5261     return SDValue();
5262
5263   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5264   if (NumElts >= 4) {
5265     SDValue shuffle = ReconstructShuffle(Op, DAG);
5266     if (shuffle != SDValue())
5267       return shuffle;
5268   }
5269
5270   // Vectors with 32- or 64-bit elements can be built by directly assigning
5271   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5272   // will be legalized.
5273   if (EltSize >= 32) {
5274     // Do the expansion with floating-point types, since that is what the VFP
5275     // registers are defined to use, and since i64 is not legal.
5276     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5277     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5278     SmallVector<SDValue, 8> Ops;
5279     for (unsigned i = 0; i < NumElts; ++i)
5280       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5281     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5282     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5283   }
5284
5285   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5286   // know the default expansion would otherwise fall back on something even
5287   // worse. For a vector with one or two non-undef values, that's
5288   // scalar_to_vector for the elements followed by a shuffle (provided the
5289   // shuffle is valid for the target) and materialization element by element
5290   // on the stack followed by a load for everything else.
5291   if (!isConstant && !usesOnlyOneValue) {
5292     SDValue Vec = DAG.getUNDEF(VT);
5293     for (unsigned i = 0 ; i < NumElts; ++i) {
5294       SDValue V = Op.getOperand(i);
5295       if (V.getOpcode() == ISD::UNDEF)
5296         continue;
5297       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5298       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5299     }
5300     return Vec;
5301   }
5302
5303   return SDValue();
5304 }
5305
5306 // Gather data to see if the operation can be modelled as a
5307 // shuffle in combination with VEXTs.
5308 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5309                                               SelectionDAG &DAG) const {
5310   SDLoc dl(Op);
5311   EVT VT = Op.getValueType();
5312   unsigned NumElts = VT.getVectorNumElements();
5313
5314   SmallVector<SDValue, 2> SourceVecs;
5315   SmallVector<unsigned, 2> MinElts;
5316   SmallVector<unsigned, 2> MaxElts;
5317
5318   for (unsigned i = 0; i < NumElts; ++i) {
5319     SDValue V = Op.getOperand(i);
5320     if (V.getOpcode() == ISD::UNDEF)
5321       continue;
5322     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5323       // A shuffle can only come from building a vector from various
5324       // elements of other vectors.
5325       return SDValue();
5326     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5327                VT.getVectorElementType()) {
5328       // This code doesn't know how to handle shuffles where the vector
5329       // element types do not match (this happens because type legalization
5330       // promotes the return type of EXTRACT_VECTOR_ELT).
5331       // FIXME: It might be appropriate to extend this code to handle
5332       // mismatched types.
5333       return SDValue();
5334     }
5335
5336     // Record this extraction against the appropriate vector if possible...
5337     SDValue SourceVec = V.getOperand(0);
5338     // If the element number isn't a constant, we can't effectively
5339     // analyze what's going on.
5340     if (!isa<ConstantSDNode>(V.getOperand(1)))
5341       return SDValue();
5342     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5343     bool FoundSource = false;
5344     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5345       if (SourceVecs[j] == SourceVec) {
5346         if (MinElts[j] > EltNo)
5347           MinElts[j] = EltNo;
5348         if (MaxElts[j] < EltNo)
5349           MaxElts[j] = EltNo;
5350         FoundSource = true;
5351         break;
5352       }
5353     }
5354
5355     // Or record a new source if not...
5356     if (!FoundSource) {
5357       SourceVecs.push_back(SourceVec);
5358       MinElts.push_back(EltNo);
5359       MaxElts.push_back(EltNo);
5360     }
5361   }
5362
5363   // Currently only do something sane when at most two source vectors
5364   // involved.
5365   if (SourceVecs.size() > 2)
5366     return SDValue();
5367
5368   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5369   int VEXTOffsets[2] = {0, 0};
5370
5371   // This loop extracts the usage patterns of the source vectors
5372   // and prepares appropriate SDValues for a shuffle if possible.
5373   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5374     if (SourceVecs[i].getValueType() == VT) {
5375       // No VEXT necessary
5376       ShuffleSrcs[i] = SourceVecs[i];
5377       VEXTOffsets[i] = 0;
5378       continue;
5379     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5380       // It probably isn't worth padding out a smaller vector just to
5381       // break it down again in a shuffle.
5382       return SDValue();
5383     }
5384
5385     // Since only 64-bit and 128-bit vectors are legal on ARM and
5386     // we've eliminated the other cases...
5387     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5388            "unexpected vector sizes in ReconstructShuffle");
5389
5390     if (MaxElts[i] - MinElts[i] >= NumElts) {
5391       // Span too large for a VEXT to cope
5392       return SDValue();
5393     }
5394
5395     if (MinElts[i] >= NumElts) {
5396       // The extraction can just take the second half
5397       VEXTOffsets[i] = NumElts;
5398       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5399                                    SourceVecs[i],
5400                                    DAG.getIntPtrConstant(NumElts));
5401     } else if (MaxElts[i] < NumElts) {
5402       // The extraction can just take the first half
5403       VEXTOffsets[i] = 0;
5404       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5405                                    SourceVecs[i],
5406                                    DAG.getIntPtrConstant(0));
5407     } else {
5408       // An actual VEXT is needed
5409       VEXTOffsets[i] = MinElts[i];
5410       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5411                                      SourceVecs[i],
5412                                      DAG.getIntPtrConstant(0));
5413       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5414                                      SourceVecs[i],
5415                                      DAG.getIntPtrConstant(NumElts));
5416       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5417                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5418     }
5419   }
5420
5421   SmallVector<int, 8> Mask;
5422
5423   for (unsigned i = 0; i < NumElts; ++i) {
5424     SDValue Entry = Op.getOperand(i);
5425     if (Entry.getOpcode() == ISD::UNDEF) {
5426       Mask.push_back(-1);
5427       continue;
5428     }
5429
5430     SDValue ExtractVec = Entry.getOperand(0);
5431     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5432                                           .getOperand(1))->getSExtValue();
5433     if (ExtractVec == SourceVecs[0]) {
5434       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5435     } else {
5436       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5437     }
5438   }
5439
5440   // Final check before we try to produce nonsense...
5441   if (isShuffleMaskLegal(Mask, VT))
5442     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5443                                 &Mask[0]);
5444
5445   return SDValue();
5446 }
5447
5448 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5449 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5450 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5451 /// are assumed to be legal.
5452 bool
5453 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5454                                       EVT VT) const {
5455   if (VT.getVectorNumElements() == 4 &&
5456       (VT.is128BitVector() || VT.is64BitVector())) {
5457     unsigned PFIndexes[4];
5458     for (unsigned i = 0; i != 4; ++i) {
5459       if (M[i] < 0)
5460         PFIndexes[i] = 8;
5461       else
5462         PFIndexes[i] = M[i];
5463     }
5464
5465     // Compute the index in the perfect shuffle table.
5466     unsigned PFTableIndex =
5467       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5468     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5469     unsigned Cost = (PFEntry >> 30);
5470
5471     if (Cost <= 4)
5472       return true;
5473   }
5474
5475   bool ReverseVEXT;
5476   unsigned Imm, WhichResult;
5477
5478   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5479   return (EltSize >= 32 ||
5480           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5481           isVREVMask(M, VT, 64) ||
5482           isVREVMask(M, VT, 32) ||
5483           isVREVMask(M, VT, 16) ||
5484           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5485           isVTBLMask(M, VT) ||
5486           isVTRNMask(M, VT, WhichResult) ||
5487           isVUZPMask(M, VT, WhichResult) ||
5488           isVZIPMask(M, VT, WhichResult) ||
5489           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5490           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5491           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5492           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5493 }
5494
5495 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5496 /// the specified operations to build the shuffle.
5497 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5498                                       SDValue RHS, SelectionDAG &DAG,
5499                                       SDLoc dl) {
5500   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5501   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5502   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5503
5504   enum {
5505     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5506     OP_VREV,
5507     OP_VDUP0,
5508     OP_VDUP1,
5509     OP_VDUP2,
5510     OP_VDUP3,
5511     OP_VEXT1,
5512     OP_VEXT2,
5513     OP_VEXT3,
5514     OP_VUZPL, // VUZP, left result
5515     OP_VUZPR, // VUZP, right result
5516     OP_VZIPL, // VZIP, left result
5517     OP_VZIPR, // VZIP, right result
5518     OP_VTRNL, // VTRN, left result
5519     OP_VTRNR  // VTRN, right result
5520   };
5521
5522   if (OpNum == OP_COPY) {
5523     if (LHSID == (1*9+2)*9+3) return LHS;
5524     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5525     return RHS;
5526   }
5527
5528   SDValue OpLHS, OpRHS;
5529   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5530   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5531   EVT VT = OpLHS.getValueType();
5532
5533   switch (OpNum) {
5534   default: llvm_unreachable("Unknown shuffle opcode!");
5535   case OP_VREV:
5536     // VREV divides the vector in half and swaps within the half.
5537     if (VT.getVectorElementType() == MVT::i32 ||
5538         VT.getVectorElementType() == MVT::f32)
5539       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5540     // vrev <4 x i16> -> VREV32
5541     if (VT.getVectorElementType() == MVT::i16)
5542       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5543     // vrev <4 x i8> -> VREV16
5544     assert(VT.getVectorElementType() == MVT::i8);
5545     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5546   case OP_VDUP0:
5547   case OP_VDUP1:
5548   case OP_VDUP2:
5549   case OP_VDUP3:
5550     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5551                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5552   case OP_VEXT1:
5553   case OP_VEXT2:
5554   case OP_VEXT3:
5555     return DAG.getNode(ARMISD::VEXT, dl, VT,
5556                        OpLHS, OpRHS,
5557                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5558   case OP_VUZPL:
5559   case OP_VUZPR:
5560     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5561                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5562   case OP_VZIPL:
5563   case OP_VZIPR:
5564     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5565                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5566   case OP_VTRNL:
5567   case OP_VTRNR:
5568     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5569                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5570   }
5571 }
5572
5573 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5574                                        ArrayRef<int> ShuffleMask,
5575                                        SelectionDAG &DAG) {
5576   // Check to see if we can use the VTBL instruction.
5577   SDValue V1 = Op.getOperand(0);
5578   SDValue V2 = Op.getOperand(1);
5579   SDLoc DL(Op);
5580
5581   SmallVector<SDValue, 8> VTBLMask;
5582   for (ArrayRef<int>::iterator
5583          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5584     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5585
5586   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5587     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5588                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5589
5590   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5591                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5592 }
5593
5594 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5595                                                       SelectionDAG &DAG) {
5596   SDLoc DL(Op);
5597   SDValue OpLHS = Op.getOperand(0);
5598   EVT VT = OpLHS.getValueType();
5599
5600   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5601          "Expect an v8i16/v16i8 type");
5602   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5603   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5604   // extract the first 8 bytes into the top double word and the last 8 bytes
5605   // into the bottom double word. The v8i16 case is similar.
5606   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5607   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5608                      DAG.getConstant(ExtractNum, MVT::i32));
5609 }
5610
5611 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5612   SDValue V1 = Op.getOperand(0);
5613   SDValue V2 = Op.getOperand(1);
5614   SDLoc dl(Op);
5615   EVT VT = Op.getValueType();
5616   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5617
5618   // Convert shuffles that are directly supported on NEON to target-specific
5619   // DAG nodes, instead of keeping them as shuffles and matching them again
5620   // during code selection.  This is more efficient and avoids the possibility
5621   // of inconsistencies between legalization and selection.
5622   // FIXME: floating-point vectors should be canonicalized to integer vectors
5623   // of the same time so that they get CSEd properly.
5624   ArrayRef<int> ShuffleMask = SVN->getMask();
5625
5626   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5627   if (EltSize <= 32) {
5628     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5629       int Lane = SVN->getSplatIndex();
5630       // If this is undef splat, generate it via "just" vdup, if possible.
5631       if (Lane == -1) Lane = 0;
5632
5633       // Test if V1 is a SCALAR_TO_VECTOR.
5634       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5635         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5636       }
5637       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5638       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5639       // reaches it).
5640       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5641           !isa<ConstantSDNode>(V1.getOperand(0))) {
5642         bool IsScalarToVector = true;
5643         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5644           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5645             IsScalarToVector = false;
5646             break;
5647           }
5648         if (IsScalarToVector)
5649           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5650       }
5651       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5652                          DAG.getConstant(Lane, MVT::i32));
5653     }
5654
5655     bool ReverseVEXT;
5656     unsigned Imm;
5657     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5658       if (ReverseVEXT)
5659         std::swap(V1, V2);
5660       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5661                          DAG.getConstant(Imm, MVT::i32));
5662     }
5663
5664     if (isVREVMask(ShuffleMask, VT, 64))
5665       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5666     if (isVREVMask(ShuffleMask, VT, 32))
5667       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5668     if (isVREVMask(ShuffleMask, VT, 16))
5669       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5670
5671     if (V2->getOpcode() == ISD::UNDEF &&
5672         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5673       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5674                          DAG.getConstant(Imm, MVT::i32));
5675     }
5676
5677     // Check for Neon shuffles that modify both input vectors in place.
5678     // If both results are used, i.e., if there are two shuffles with the same
5679     // source operands and with masks corresponding to both results of one of
5680     // these operations, DAG memoization will ensure that a single node is
5681     // used for both shuffles.
5682     unsigned WhichResult;
5683     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5684       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5685                          V1, V2).getValue(WhichResult);
5686     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5687       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5688                          V1, V2).getValue(WhichResult);
5689     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5690       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5691                          V1, V2).getValue(WhichResult);
5692
5693     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5694       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5695                          V1, V1).getValue(WhichResult);
5696     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5697       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5698                          V1, V1).getValue(WhichResult);
5699     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5700       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5701                          V1, V1).getValue(WhichResult);
5702   }
5703
5704   // If the shuffle is not directly supported and it has 4 elements, use
5705   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5706   unsigned NumElts = VT.getVectorNumElements();
5707   if (NumElts == 4) {
5708     unsigned PFIndexes[4];
5709     for (unsigned i = 0; i != 4; ++i) {
5710       if (ShuffleMask[i] < 0)
5711         PFIndexes[i] = 8;
5712       else
5713         PFIndexes[i] = ShuffleMask[i];
5714     }
5715
5716     // Compute the index in the perfect shuffle table.
5717     unsigned PFTableIndex =
5718       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5719     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5720     unsigned Cost = (PFEntry >> 30);
5721
5722     if (Cost <= 4)
5723       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5724   }
5725
5726   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5727   if (EltSize >= 32) {
5728     // Do the expansion with floating-point types, since that is what the VFP
5729     // registers are defined to use, and since i64 is not legal.
5730     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5731     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5732     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5733     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5734     SmallVector<SDValue, 8> Ops;
5735     for (unsigned i = 0; i < NumElts; ++i) {
5736       if (ShuffleMask[i] < 0)
5737         Ops.push_back(DAG.getUNDEF(EltVT));
5738       else
5739         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5740                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5741                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5742                                                   MVT::i32)));
5743     }
5744     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5745     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5746   }
5747
5748   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5749     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5750
5751   if (VT == MVT::v8i8) {
5752     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5753     if (NewOp.getNode())
5754       return NewOp;
5755   }
5756
5757   return SDValue();
5758 }
5759
5760 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5761   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5762   SDValue Lane = Op.getOperand(2);
5763   if (!isa<ConstantSDNode>(Lane))
5764     return SDValue();
5765
5766   return Op;
5767 }
5768
5769 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5770   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5771   SDValue Lane = Op.getOperand(1);
5772   if (!isa<ConstantSDNode>(Lane))
5773     return SDValue();
5774
5775   SDValue Vec = Op.getOperand(0);
5776   if (Op.getValueType() == MVT::i32 &&
5777       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5778     SDLoc dl(Op);
5779     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5780   }
5781
5782   return Op;
5783 }
5784
5785 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5786   // The only time a CONCAT_VECTORS operation can have legal types is when
5787   // two 64-bit vectors are concatenated to a 128-bit vector.
5788   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5789          "unexpected CONCAT_VECTORS");
5790   SDLoc dl(Op);
5791   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5792   SDValue Op0 = Op.getOperand(0);
5793   SDValue Op1 = Op.getOperand(1);
5794   if (Op0.getOpcode() != ISD::UNDEF)
5795     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5796                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5797                       DAG.getIntPtrConstant(0));
5798   if (Op1.getOpcode() != ISD::UNDEF)
5799     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5800                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5801                       DAG.getIntPtrConstant(1));
5802   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5803 }
5804
5805 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5806 /// element has been zero/sign-extended, depending on the isSigned parameter,
5807 /// from an integer type half its size.
5808 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5809                                    bool isSigned) {
5810   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5811   EVT VT = N->getValueType(0);
5812   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5813     SDNode *BVN = N->getOperand(0).getNode();
5814     if (BVN->getValueType(0) != MVT::v4i32 ||
5815         BVN->getOpcode() != ISD::BUILD_VECTOR)
5816       return false;
5817     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5818     unsigned HiElt = 1 - LoElt;
5819     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5820     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5821     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5822     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5823     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5824       return false;
5825     if (isSigned) {
5826       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5827           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5828         return true;
5829     } else {
5830       if (Hi0->isNullValue() && Hi1->isNullValue())
5831         return true;
5832     }
5833     return false;
5834   }
5835
5836   if (N->getOpcode() != ISD::BUILD_VECTOR)
5837     return false;
5838
5839   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5840     SDNode *Elt = N->getOperand(i).getNode();
5841     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5842       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5843       unsigned HalfSize = EltSize / 2;
5844       if (isSigned) {
5845         if (!isIntN(HalfSize, C->getSExtValue()))
5846           return false;
5847       } else {
5848         if (!isUIntN(HalfSize, C->getZExtValue()))
5849           return false;
5850       }
5851       continue;
5852     }
5853     return false;
5854   }
5855
5856   return true;
5857 }
5858
5859 /// isSignExtended - Check if a node is a vector value that is sign-extended
5860 /// or a constant BUILD_VECTOR with sign-extended elements.
5861 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5862   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5863     return true;
5864   if (isExtendedBUILD_VECTOR(N, DAG, true))
5865     return true;
5866   return false;
5867 }
5868
5869 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5870 /// or a constant BUILD_VECTOR with zero-extended elements.
5871 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5872   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5873     return true;
5874   if (isExtendedBUILD_VECTOR(N, DAG, false))
5875     return true;
5876   return false;
5877 }
5878
5879 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5880   if (OrigVT.getSizeInBits() >= 64)
5881     return OrigVT;
5882
5883   assert(OrigVT.isSimple() && "Expecting a simple value type");
5884
5885   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5886   switch (OrigSimpleTy) {
5887   default: llvm_unreachable("Unexpected Vector Type");
5888   case MVT::v2i8:
5889   case MVT::v2i16:
5890      return MVT::v2i32;
5891   case MVT::v4i8:
5892     return  MVT::v4i16;
5893   }
5894 }
5895
5896 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5897 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5898 /// We insert the required extension here to get the vector to fill a D register.
5899 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5900                                             const EVT &OrigTy,
5901                                             const EVT &ExtTy,
5902                                             unsigned ExtOpcode) {
5903   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5904   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5905   // 64-bits we need to insert a new extension so that it will be 64-bits.
5906   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5907   if (OrigTy.getSizeInBits() >= 64)
5908     return N;
5909
5910   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5911   EVT NewVT = getExtensionTo64Bits(OrigTy);
5912
5913   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5914 }
5915
5916 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5917 /// does not do any sign/zero extension. If the original vector is less
5918 /// than 64 bits, an appropriate extension will be added after the load to
5919 /// reach a total size of 64 bits. We have to add the extension separately
5920 /// because ARM does not have a sign/zero extending load for vectors.
5921 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5922   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5923
5924   // The load already has the right type.
5925   if (ExtendedTy == LD->getMemoryVT())
5926     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5927                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5928                 LD->isNonTemporal(), LD->isInvariant(),
5929                 LD->getAlignment());
5930
5931   // We need to create a zextload/sextload. We cannot just create a load
5932   // followed by a zext/zext node because LowerMUL is also run during normal
5933   // operation legalization where we can't create illegal types.
5934   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5935                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5936                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5937                         LD->isNonTemporal(), LD->getAlignment());
5938 }
5939
5940 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5941 /// extending load, or BUILD_VECTOR with extended elements, return the
5942 /// unextended value. The unextended vector should be 64 bits so that it can
5943 /// be used as an operand to a VMULL instruction. If the original vector size
5944 /// before extension is less than 64 bits we add a an extension to resize
5945 /// the vector to 64 bits.
5946 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5947   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5948     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5949                                         N->getOperand(0)->getValueType(0),
5950                                         N->getValueType(0),
5951                                         N->getOpcode());
5952
5953   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5954     return SkipLoadExtensionForVMULL(LD, DAG);
5955
5956   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5957   // have been legalized as a BITCAST from v4i32.
5958   if (N->getOpcode() == ISD::BITCAST) {
5959     SDNode *BVN = N->getOperand(0).getNode();
5960     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5961            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5962     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5963     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5964                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5965   }
5966   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5967   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5968   EVT VT = N->getValueType(0);
5969   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5970   unsigned NumElts = VT.getVectorNumElements();
5971   MVT TruncVT = MVT::getIntegerVT(EltSize);
5972   SmallVector<SDValue, 8> Ops;
5973   for (unsigned i = 0; i != NumElts; ++i) {
5974     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5975     const APInt &CInt = C->getAPIntValue();
5976     // Element types smaller than 32 bits are not legal, so use i32 elements.
5977     // The values are implicitly truncated so sext vs. zext doesn't matter.
5978     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5979   }
5980   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5981                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5982 }
5983
5984 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5985   unsigned Opcode = N->getOpcode();
5986   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5987     SDNode *N0 = N->getOperand(0).getNode();
5988     SDNode *N1 = N->getOperand(1).getNode();
5989     return N0->hasOneUse() && N1->hasOneUse() &&
5990       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5991   }
5992   return false;
5993 }
5994
5995 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5996   unsigned Opcode = N->getOpcode();
5997   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5998     SDNode *N0 = N->getOperand(0).getNode();
5999     SDNode *N1 = N->getOperand(1).getNode();
6000     return N0->hasOneUse() && N1->hasOneUse() &&
6001       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6002   }
6003   return false;
6004 }
6005
6006 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6007   // Multiplications are only custom-lowered for 128-bit vectors so that
6008   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6009   EVT VT = Op.getValueType();
6010   assert(VT.is128BitVector() && VT.isInteger() &&
6011          "unexpected type for custom-lowering ISD::MUL");
6012   SDNode *N0 = Op.getOperand(0).getNode();
6013   SDNode *N1 = Op.getOperand(1).getNode();
6014   unsigned NewOpc = 0;
6015   bool isMLA = false;
6016   bool isN0SExt = isSignExtended(N0, DAG);
6017   bool isN1SExt = isSignExtended(N1, DAG);
6018   if (isN0SExt && isN1SExt)
6019     NewOpc = ARMISD::VMULLs;
6020   else {
6021     bool isN0ZExt = isZeroExtended(N0, DAG);
6022     bool isN1ZExt = isZeroExtended(N1, DAG);
6023     if (isN0ZExt && isN1ZExt)
6024       NewOpc = ARMISD::VMULLu;
6025     else if (isN1SExt || isN1ZExt) {
6026       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6027       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6028       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6029         NewOpc = ARMISD::VMULLs;
6030         isMLA = true;
6031       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6032         NewOpc = ARMISD::VMULLu;
6033         isMLA = true;
6034       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6035         std::swap(N0, N1);
6036         NewOpc = ARMISD::VMULLu;
6037         isMLA = true;
6038       }
6039     }
6040
6041     if (!NewOpc) {
6042       if (VT == MVT::v2i64)
6043         // Fall through to expand this.  It is not legal.
6044         return SDValue();
6045       else
6046         // Other vector multiplications are legal.
6047         return Op;
6048     }
6049   }
6050
6051   // Legalize to a VMULL instruction.
6052   SDLoc DL(Op);
6053   SDValue Op0;
6054   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6055   if (!isMLA) {
6056     Op0 = SkipExtensionForVMULL(N0, DAG);
6057     assert(Op0.getValueType().is64BitVector() &&
6058            Op1.getValueType().is64BitVector() &&
6059            "unexpected types for extended operands to VMULL");
6060     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6061   }
6062
6063   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6064   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6065   //   vmull q0, d4, d6
6066   //   vmlal q0, d5, d6
6067   // is faster than
6068   //   vaddl q0, d4, d5
6069   //   vmovl q1, d6
6070   //   vmul  q0, q0, q1
6071   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6072   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6073   EVT Op1VT = Op1.getValueType();
6074   return DAG.getNode(N0->getOpcode(), DL, VT,
6075                      DAG.getNode(NewOpc, DL, VT,
6076                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6077                      DAG.getNode(NewOpc, DL, VT,
6078                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6079 }
6080
6081 static SDValue
6082 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6083   // Convert to float
6084   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6085   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6086   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6087   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6088   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6089   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6090   // Get reciprocal estimate.
6091   // float4 recip = vrecpeq_f32(yf);
6092   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6093                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6094   // Because char has a smaller range than uchar, we can actually get away
6095   // without any newton steps.  This requires that we use a weird bias
6096   // of 0xb000, however (again, this has been exhaustively tested).
6097   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6098   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6099   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6100   Y = DAG.getConstant(0xb000, MVT::i32);
6101   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6102   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6103   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6104   // Convert back to short.
6105   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6106   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6107   return X;
6108 }
6109
6110 static SDValue
6111 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6112   SDValue N2;
6113   // Convert to float.
6114   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6115   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6116   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6117   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6118   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6119   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6120
6121   // Use reciprocal estimate and one refinement step.
6122   // float4 recip = vrecpeq_f32(yf);
6123   // recip *= vrecpsq_f32(yf, recip);
6124   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6125                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6126   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6127                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6128                    N1, N2);
6129   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6130   // Because short has a smaller range than ushort, we can actually get away
6131   // with only a single newton step.  This requires that we use a weird bias
6132   // of 89, however (again, this has been exhaustively tested).
6133   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6134   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6135   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6136   N1 = DAG.getConstant(0x89, MVT::i32);
6137   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6138   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6139   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6140   // Convert back to integer and return.
6141   // return vmovn_s32(vcvt_s32_f32(result));
6142   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6143   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6144   return N0;
6145 }
6146
6147 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6148   EVT VT = Op.getValueType();
6149   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6150          "unexpected type for custom-lowering ISD::SDIV");
6151
6152   SDLoc dl(Op);
6153   SDValue N0 = Op.getOperand(0);
6154   SDValue N1 = Op.getOperand(1);
6155   SDValue N2, N3;
6156
6157   if (VT == MVT::v8i8) {
6158     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6159     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6160
6161     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6162                      DAG.getIntPtrConstant(4));
6163     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6164                      DAG.getIntPtrConstant(4));
6165     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6166                      DAG.getIntPtrConstant(0));
6167     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6168                      DAG.getIntPtrConstant(0));
6169
6170     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6171     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6172
6173     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6174     N0 = LowerCONCAT_VECTORS(N0, DAG);
6175
6176     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6177     return N0;
6178   }
6179   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6180 }
6181
6182 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6183   EVT VT = Op.getValueType();
6184   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6185          "unexpected type for custom-lowering ISD::UDIV");
6186
6187   SDLoc dl(Op);
6188   SDValue N0 = Op.getOperand(0);
6189   SDValue N1 = Op.getOperand(1);
6190   SDValue N2, N3;
6191
6192   if (VT == MVT::v8i8) {
6193     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6194     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6195
6196     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6197                      DAG.getIntPtrConstant(4));
6198     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6199                      DAG.getIntPtrConstant(4));
6200     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6201                      DAG.getIntPtrConstant(0));
6202     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6203                      DAG.getIntPtrConstant(0));
6204
6205     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6206     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6207
6208     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6209     N0 = LowerCONCAT_VECTORS(N0, DAG);
6210
6211     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6212                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6213                      N0);
6214     return N0;
6215   }
6216
6217   // v4i16 sdiv ... Convert to float.
6218   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6219   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6220   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6221   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6222   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6223   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6224
6225   // Use reciprocal estimate and two refinement steps.
6226   // float4 recip = vrecpeq_f32(yf);
6227   // recip *= vrecpsq_f32(yf, recip);
6228   // recip *= vrecpsq_f32(yf, recip);
6229   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6230                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6231   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6232                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6233                    BN1, N2);
6234   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6235   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6236                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6237                    BN1, N2);
6238   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6239   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6240   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6241   // and that it will never cause us to return an answer too large).
6242   // float4 result = as_float4(as_int4(xf*recip) + 2);
6243   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6244   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6245   N1 = DAG.getConstant(2, MVT::i32);
6246   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6247   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6248   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6249   // Convert back to integer and return.
6250   // return vmovn_u32(vcvt_s32_f32(result));
6251   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6252   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6253   return N0;
6254 }
6255
6256 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6257   EVT VT = Op.getNode()->getValueType(0);
6258   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6259
6260   unsigned Opc;
6261   bool ExtraOp = false;
6262   switch (Op.getOpcode()) {
6263   default: llvm_unreachable("Invalid code");
6264   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6265   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6266   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6267   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6268   }
6269
6270   if (!ExtraOp)
6271     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6272                        Op.getOperand(1));
6273   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6274                      Op.getOperand(1), Op.getOperand(2));
6275 }
6276
6277 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6278   assert(Subtarget->isTargetDarwin());
6279
6280   // For iOS, we want to call an alternative entry point: __sincos_stret,
6281   // return values are passed via sret.
6282   SDLoc dl(Op);
6283   SDValue Arg = Op.getOperand(0);
6284   EVT ArgVT = Arg.getValueType();
6285   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6286
6287   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6288   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6289
6290   // Pair of floats / doubles used to pass the result.
6291   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6292
6293   // Create stack object for sret.
6294   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6295   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6296   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6297   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6298
6299   ArgListTy Args;
6300   ArgListEntry Entry;
6301
6302   Entry.Node = SRet;
6303   Entry.Ty = RetTy->getPointerTo();
6304   Entry.isSExt = false;
6305   Entry.isZExt = false;
6306   Entry.isSRet = true;
6307   Args.push_back(Entry);
6308
6309   Entry.Node = Arg;
6310   Entry.Ty = ArgTy;
6311   Entry.isSExt = false;
6312   Entry.isZExt = false;
6313   Args.push_back(Entry);
6314
6315   const char *LibcallName  = (ArgVT == MVT::f64)
6316   ? "__sincos_stret" : "__sincosf_stret";
6317   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6318
6319   TargetLowering::CallLoweringInfo CLI(DAG);
6320   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6321     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6322                std::move(Args), 0)
6323     .setDiscardResult();
6324
6325   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6326
6327   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6328                                 MachinePointerInfo(), false, false, false, 0);
6329
6330   // Address of cos field.
6331   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6332                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6333   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6334                                 MachinePointerInfo(), false, false, false, 0);
6335
6336   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6337   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6338                      LoadSin.getValue(0), LoadCos.getValue(0));
6339 }
6340
6341 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6342   // Monotonic load/store is legal for all targets
6343   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6344     return Op;
6345
6346   // Acquire/Release load/store is not legal for targets without a
6347   // dmb or equivalent available.
6348   return SDValue();
6349 }
6350
6351 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6352                                     SmallVectorImpl<SDValue> &Results,
6353                                     SelectionDAG &DAG,
6354                                     const ARMSubtarget *Subtarget) {
6355   SDLoc DL(N);
6356   SDValue Cycles32, OutChain;
6357
6358   if (Subtarget->hasPerfMon()) {
6359     // Under Power Management extensions, the cycle-count is:
6360     //    mrc p15, #0, <Rt>, c9, c13, #0
6361     SDValue Ops[] = { N->getOperand(0), // Chain
6362                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6363                       DAG.getConstant(15, MVT::i32),
6364                       DAG.getConstant(0, MVT::i32),
6365                       DAG.getConstant(9, MVT::i32),
6366                       DAG.getConstant(13, MVT::i32),
6367                       DAG.getConstant(0, MVT::i32)
6368     };
6369
6370     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6371                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6372     OutChain = Cycles32.getValue(1);
6373   } else {
6374     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6375     // there are older ARM CPUs that have implementation-specific ways of
6376     // obtaining this information (FIXME!).
6377     Cycles32 = DAG.getConstant(0, MVT::i32);
6378     OutChain = DAG.getEntryNode();
6379   }
6380
6381
6382   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6383                                  Cycles32, DAG.getConstant(0, MVT::i32));
6384   Results.push_back(Cycles64);
6385   Results.push_back(OutChain);
6386 }
6387
6388 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6389   switch (Op.getOpcode()) {
6390   default: llvm_unreachable("Don't know how to custom lower this!");
6391   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6392   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6393   case ISD::GlobalAddress:
6394     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6395     default: llvm_unreachable("unknown object format");
6396     case Triple::COFF:
6397       return LowerGlobalAddressWindows(Op, DAG);
6398     case Triple::ELF:
6399       return LowerGlobalAddressELF(Op, DAG);
6400     case Triple::MachO:
6401       return LowerGlobalAddressDarwin(Op, DAG);
6402     }
6403   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6404   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6405   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6406   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6407   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6408   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6409   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6410   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6411   case ISD::SINT_TO_FP:
6412   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6413   case ISD::FP_TO_SINT:
6414   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6415   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6416   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6417   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6418   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6419   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6420   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6421   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6422                                                                Subtarget);
6423   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6424   case ISD::SHL:
6425   case ISD::SRL:
6426   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6427   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6428   case ISD::SRL_PARTS:
6429   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6430   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6431   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6432   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6433   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6434   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6435   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6436   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6437   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6438   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6439   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6440   case ISD::MUL:           return LowerMUL(Op, DAG);
6441   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6442   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6443   case ISD::ADDC:
6444   case ISD::ADDE:
6445   case ISD::SUBC:
6446   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6447   case ISD::SADDO:
6448   case ISD::UADDO:
6449   case ISD::SSUBO:
6450   case ISD::USUBO:
6451     return LowerXALUO(Op, DAG);
6452   case ISD::ATOMIC_LOAD:
6453   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6454   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6455   case ISD::SDIVREM:
6456   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6457   case ISD::DYNAMIC_STACKALLOC:
6458     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6459       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6460     llvm_unreachable("Don't know how to custom lower this!");
6461   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6462   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6463   }
6464 }
6465
6466 /// ReplaceNodeResults - Replace the results of node with an illegal result
6467 /// type with new values built out of custom code.
6468 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6469                                            SmallVectorImpl<SDValue>&Results,
6470                                            SelectionDAG &DAG) const {
6471   SDValue Res;
6472   switch (N->getOpcode()) {
6473   default:
6474     llvm_unreachable("Don't know how to custom expand this!");
6475   case ISD::BITCAST:
6476     Res = ExpandBITCAST(N, DAG);
6477     break;
6478   case ISD::SRL:
6479   case ISD::SRA:
6480     Res = Expand64BitShift(N, DAG, Subtarget);
6481     break;
6482   case ISD::READCYCLECOUNTER:
6483     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6484     return;
6485   }
6486   if (Res.getNode())
6487     Results.push_back(Res);
6488 }
6489
6490 //===----------------------------------------------------------------------===//
6491 //                           ARM Scheduler Hooks
6492 //===----------------------------------------------------------------------===//
6493
6494 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6495 /// registers the function context.
6496 void ARMTargetLowering::
6497 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6498                        MachineBasicBlock *DispatchBB, int FI) const {
6499   const TargetInstrInfo *TII =
6500       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6501   DebugLoc dl = MI->getDebugLoc();
6502   MachineFunction *MF = MBB->getParent();
6503   MachineRegisterInfo *MRI = &MF->getRegInfo();
6504   MachineConstantPool *MCP = MF->getConstantPool();
6505   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6506   const Function *F = MF->getFunction();
6507
6508   bool isThumb = Subtarget->isThumb();
6509   bool isThumb2 = Subtarget->isThumb2();
6510
6511   unsigned PCLabelId = AFI->createPICLabelUId();
6512   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6513   ARMConstantPoolValue *CPV =
6514     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6515   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6516
6517   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6518                                            : &ARM::GPRRegClass;
6519
6520   // Grab constant pool and fixed stack memory operands.
6521   MachineMemOperand *CPMMO =
6522     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6523                              MachineMemOperand::MOLoad, 4, 4);
6524
6525   MachineMemOperand *FIMMOSt =
6526     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6527                              MachineMemOperand::MOStore, 4, 4);
6528
6529   // Load the address of the dispatch MBB into the jump buffer.
6530   if (isThumb2) {
6531     // Incoming value: jbuf
6532     //   ldr.n  r5, LCPI1_1
6533     //   orr    r5, r5, #1
6534     //   add    r5, pc
6535     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6536     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6537     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6538                    .addConstantPoolIndex(CPI)
6539                    .addMemOperand(CPMMO));
6540     // Set the low bit because of thumb mode.
6541     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6542     AddDefaultCC(
6543       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6544                      .addReg(NewVReg1, RegState::Kill)
6545                      .addImm(0x01)));
6546     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6547     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6548       .addReg(NewVReg2, RegState::Kill)
6549       .addImm(PCLabelId);
6550     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6551                    .addReg(NewVReg3, RegState::Kill)
6552                    .addFrameIndex(FI)
6553                    .addImm(36)  // &jbuf[1] :: pc
6554                    .addMemOperand(FIMMOSt));
6555   } else if (isThumb) {
6556     // Incoming value: jbuf
6557     //   ldr.n  r1, LCPI1_4
6558     //   add    r1, pc
6559     //   mov    r2, #1
6560     //   orrs   r1, r2
6561     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6562     //   str    r1, [r2]
6563     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6564     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6565                    .addConstantPoolIndex(CPI)
6566                    .addMemOperand(CPMMO));
6567     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6568     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6569       .addReg(NewVReg1, RegState::Kill)
6570       .addImm(PCLabelId);
6571     // Set the low bit because of thumb mode.
6572     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6573     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6574                    .addReg(ARM::CPSR, RegState::Define)
6575                    .addImm(1));
6576     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6577     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6578                    .addReg(ARM::CPSR, RegState::Define)
6579                    .addReg(NewVReg2, RegState::Kill)
6580                    .addReg(NewVReg3, RegState::Kill));
6581     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6582     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6583             .addFrameIndex(FI)
6584             .addImm(36); // &jbuf[1] :: pc
6585     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6586                    .addReg(NewVReg4, RegState::Kill)
6587                    .addReg(NewVReg5, RegState::Kill)
6588                    .addImm(0)
6589                    .addMemOperand(FIMMOSt));
6590   } else {
6591     // Incoming value: jbuf
6592     //   ldr  r1, LCPI1_1
6593     //   add  r1, pc, r1
6594     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6595     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6596     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6597                    .addConstantPoolIndex(CPI)
6598                    .addImm(0)
6599                    .addMemOperand(CPMMO));
6600     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6601     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6602                    .addReg(NewVReg1, RegState::Kill)
6603                    .addImm(PCLabelId));
6604     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6605                    .addReg(NewVReg2, RegState::Kill)
6606                    .addFrameIndex(FI)
6607                    .addImm(36)  // &jbuf[1] :: pc
6608                    .addMemOperand(FIMMOSt));
6609   }
6610 }
6611
6612 MachineBasicBlock *ARMTargetLowering::
6613 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6614   const TargetInstrInfo *TII =
6615       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6616   DebugLoc dl = MI->getDebugLoc();
6617   MachineFunction *MF = MBB->getParent();
6618   MachineRegisterInfo *MRI = &MF->getRegInfo();
6619   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6620   MachineFrameInfo *MFI = MF->getFrameInfo();
6621   int FI = MFI->getFunctionContextIndex();
6622
6623   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6624                                                         : &ARM::GPRnopcRegClass;
6625
6626   // Get a mapping of the call site numbers to all of the landing pads they're
6627   // associated with.
6628   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6629   unsigned MaxCSNum = 0;
6630   MachineModuleInfo &MMI = MF->getMMI();
6631   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6632        ++BB) {
6633     if (!BB->isLandingPad()) continue;
6634
6635     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6636     // pad.
6637     for (MachineBasicBlock::iterator
6638            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6639       if (!II->isEHLabel()) continue;
6640
6641       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6642       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6643
6644       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6645       for (SmallVectorImpl<unsigned>::iterator
6646              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6647            CSI != CSE; ++CSI) {
6648         CallSiteNumToLPad[*CSI].push_back(BB);
6649         MaxCSNum = std::max(MaxCSNum, *CSI);
6650       }
6651       break;
6652     }
6653   }
6654
6655   // Get an ordered list of the machine basic blocks for the jump table.
6656   std::vector<MachineBasicBlock*> LPadList;
6657   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6658   LPadList.reserve(CallSiteNumToLPad.size());
6659   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6660     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6661     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6662            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6663       LPadList.push_back(*II);
6664       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6665     }
6666   }
6667
6668   assert(!LPadList.empty() &&
6669          "No landing pad destinations for the dispatch jump table!");
6670
6671   // Create the jump table and associated information.
6672   MachineJumpTableInfo *JTI =
6673     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6674   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6675   unsigned UId = AFI->createJumpTableUId();
6676   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6677
6678   // Create the MBBs for the dispatch code.
6679
6680   // Shove the dispatch's address into the return slot in the function context.
6681   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6682   DispatchBB->setIsLandingPad();
6683
6684   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6685   unsigned trap_opcode;
6686   if (Subtarget->isThumb())
6687     trap_opcode = ARM::tTRAP;
6688   else
6689     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6690
6691   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6692   DispatchBB->addSuccessor(TrapBB);
6693
6694   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6695   DispatchBB->addSuccessor(DispContBB);
6696
6697   // Insert and MBBs.
6698   MF->insert(MF->end(), DispatchBB);
6699   MF->insert(MF->end(), DispContBB);
6700   MF->insert(MF->end(), TrapBB);
6701
6702   // Insert code into the entry block that creates and registers the function
6703   // context.
6704   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6705
6706   MachineMemOperand *FIMMOLd =
6707     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6708                              MachineMemOperand::MOLoad |
6709                              MachineMemOperand::MOVolatile, 4, 4);
6710
6711   MachineInstrBuilder MIB;
6712   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6713
6714   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6715   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6716
6717   // Add a register mask with no preserved registers.  This results in all
6718   // registers being marked as clobbered.
6719   MIB.addRegMask(RI.getNoPreservedMask());
6720
6721   unsigned NumLPads = LPadList.size();
6722   if (Subtarget->isThumb2()) {
6723     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6724     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6725                    .addFrameIndex(FI)
6726                    .addImm(4)
6727                    .addMemOperand(FIMMOLd));
6728
6729     if (NumLPads < 256) {
6730       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6731                      .addReg(NewVReg1)
6732                      .addImm(LPadList.size()));
6733     } else {
6734       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6735       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6736                      .addImm(NumLPads & 0xFFFF));
6737
6738       unsigned VReg2 = VReg1;
6739       if ((NumLPads & 0xFFFF0000) != 0) {
6740         VReg2 = MRI->createVirtualRegister(TRC);
6741         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6742                        .addReg(VReg1)
6743                        .addImm(NumLPads >> 16));
6744       }
6745
6746       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6747                      .addReg(NewVReg1)
6748                      .addReg(VReg2));
6749     }
6750
6751     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6752       .addMBB(TrapBB)
6753       .addImm(ARMCC::HI)
6754       .addReg(ARM::CPSR);
6755
6756     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6757     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6758                    .addJumpTableIndex(MJTI)
6759                    .addImm(UId));
6760
6761     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6762     AddDefaultCC(
6763       AddDefaultPred(
6764         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6765         .addReg(NewVReg3, RegState::Kill)
6766         .addReg(NewVReg1)
6767         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6768
6769     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6770       .addReg(NewVReg4, RegState::Kill)
6771       .addReg(NewVReg1)
6772       .addJumpTableIndex(MJTI)
6773       .addImm(UId);
6774   } else if (Subtarget->isThumb()) {
6775     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6776     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6777                    .addFrameIndex(FI)
6778                    .addImm(1)
6779                    .addMemOperand(FIMMOLd));
6780
6781     if (NumLPads < 256) {
6782       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6783                      .addReg(NewVReg1)
6784                      .addImm(NumLPads));
6785     } else {
6786       MachineConstantPool *ConstantPool = MF->getConstantPool();
6787       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6788       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6789
6790       // MachineConstantPool wants an explicit alignment.
6791       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6792       if (Align == 0)
6793         Align = getDataLayout()->getTypeAllocSize(C->getType());
6794       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6795
6796       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6797       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6798                      .addReg(VReg1, RegState::Define)
6799                      .addConstantPoolIndex(Idx));
6800       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6801                      .addReg(NewVReg1)
6802                      .addReg(VReg1));
6803     }
6804
6805     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6806       .addMBB(TrapBB)
6807       .addImm(ARMCC::HI)
6808       .addReg(ARM::CPSR);
6809
6810     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6811     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6812                    .addReg(ARM::CPSR, RegState::Define)
6813                    .addReg(NewVReg1)
6814                    .addImm(2));
6815
6816     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6817     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6818                    .addJumpTableIndex(MJTI)
6819                    .addImm(UId));
6820
6821     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6822     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6823                    .addReg(ARM::CPSR, RegState::Define)
6824                    .addReg(NewVReg2, RegState::Kill)
6825                    .addReg(NewVReg3));
6826
6827     MachineMemOperand *JTMMOLd =
6828       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6829                                MachineMemOperand::MOLoad, 4, 4);
6830
6831     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6832     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6833                    .addReg(NewVReg4, RegState::Kill)
6834                    .addImm(0)
6835                    .addMemOperand(JTMMOLd));
6836
6837     unsigned NewVReg6 = NewVReg5;
6838     if (RelocM == Reloc::PIC_) {
6839       NewVReg6 = MRI->createVirtualRegister(TRC);
6840       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6841                      .addReg(ARM::CPSR, RegState::Define)
6842                      .addReg(NewVReg5, RegState::Kill)
6843                      .addReg(NewVReg3));
6844     }
6845
6846     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6847       .addReg(NewVReg6, RegState::Kill)
6848       .addJumpTableIndex(MJTI)
6849       .addImm(UId);
6850   } else {
6851     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6852     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6853                    .addFrameIndex(FI)
6854                    .addImm(4)
6855                    .addMemOperand(FIMMOLd));
6856
6857     if (NumLPads < 256) {
6858       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6859                      .addReg(NewVReg1)
6860                      .addImm(NumLPads));
6861     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6862       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6863       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6864                      .addImm(NumLPads & 0xFFFF));
6865
6866       unsigned VReg2 = VReg1;
6867       if ((NumLPads & 0xFFFF0000) != 0) {
6868         VReg2 = MRI->createVirtualRegister(TRC);
6869         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6870                        .addReg(VReg1)
6871                        .addImm(NumLPads >> 16));
6872       }
6873
6874       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6875                      .addReg(NewVReg1)
6876                      .addReg(VReg2));
6877     } else {
6878       MachineConstantPool *ConstantPool = MF->getConstantPool();
6879       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6880       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6881
6882       // MachineConstantPool wants an explicit alignment.
6883       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6884       if (Align == 0)
6885         Align = getDataLayout()->getTypeAllocSize(C->getType());
6886       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6887
6888       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6889       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6890                      .addReg(VReg1, RegState::Define)
6891                      .addConstantPoolIndex(Idx)
6892                      .addImm(0));
6893       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6894                      .addReg(NewVReg1)
6895                      .addReg(VReg1, RegState::Kill));
6896     }
6897
6898     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6899       .addMBB(TrapBB)
6900       .addImm(ARMCC::HI)
6901       .addReg(ARM::CPSR);
6902
6903     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6904     AddDefaultCC(
6905       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6906                      .addReg(NewVReg1)
6907                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6908     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6909     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6910                    .addJumpTableIndex(MJTI)
6911                    .addImm(UId));
6912
6913     MachineMemOperand *JTMMOLd =
6914       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6915                                MachineMemOperand::MOLoad, 4, 4);
6916     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6917     AddDefaultPred(
6918       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6919       .addReg(NewVReg3, RegState::Kill)
6920       .addReg(NewVReg4)
6921       .addImm(0)
6922       .addMemOperand(JTMMOLd));
6923
6924     if (RelocM == Reloc::PIC_) {
6925       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6926         .addReg(NewVReg5, RegState::Kill)
6927         .addReg(NewVReg4)
6928         .addJumpTableIndex(MJTI)
6929         .addImm(UId);
6930     } else {
6931       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6932         .addReg(NewVReg5, RegState::Kill)
6933         .addJumpTableIndex(MJTI)
6934         .addImm(UId);
6935     }
6936   }
6937
6938   // Add the jump table entries as successors to the MBB.
6939   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6940   for (std::vector<MachineBasicBlock*>::iterator
6941          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6942     MachineBasicBlock *CurMBB = *I;
6943     if (SeenMBBs.insert(CurMBB).second)
6944       DispContBB->addSuccessor(CurMBB);
6945   }
6946
6947   // N.B. the order the invoke BBs are processed in doesn't matter here.
6948   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6949   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6950   for (MachineBasicBlock *BB : InvokeBBs) {
6951
6952     // Remove the landing pad successor from the invoke block and replace it
6953     // with the new dispatch block.
6954     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6955                                                   BB->succ_end());
6956     while (!Successors.empty()) {
6957       MachineBasicBlock *SMBB = Successors.pop_back_val();
6958       if (SMBB->isLandingPad()) {
6959         BB->removeSuccessor(SMBB);
6960         MBBLPads.push_back(SMBB);
6961       }
6962     }
6963
6964     BB->addSuccessor(DispatchBB);
6965
6966     // Find the invoke call and mark all of the callee-saved registers as
6967     // 'implicit defined' so that they're spilled. This prevents code from
6968     // moving instructions to before the EH block, where they will never be
6969     // executed.
6970     for (MachineBasicBlock::reverse_iterator
6971            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6972       if (!II->isCall()) continue;
6973
6974       DenseMap<unsigned, bool> DefRegs;
6975       for (MachineInstr::mop_iterator
6976              OI = II->operands_begin(), OE = II->operands_end();
6977            OI != OE; ++OI) {
6978         if (!OI->isReg()) continue;
6979         DefRegs[OI->getReg()] = true;
6980       }
6981
6982       MachineInstrBuilder MIB(*MF, &*II);
6983
6984       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6985         unsigned Reg = SavedRegs[i];
6986         if (Subtarget->isThumb2() &&
6987             !ARM::tGPRRegClass.contains(Reg) &&
6988             !ARM::hGPRRegClass.contains(Reg))
6989           continue;
6990         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6991           continue;
6992         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6993           continue;
6994         if (!DefRegs[Reg])
6995           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6996       }
6997
6998       break;
6999     }
7000   }
7001
7002   // Mark all former landing pads as non-landing pads. The dispatch is the only
7003   // landing pad now.
7004   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7005          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7006     (*I)->setIsLandingPad(false);
7007
7008   // The instruction is gone now.
7009   MI->eraseFromParent();
7010
7011   return MBB;
7012 }
7013
7014 static
7015 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7016   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7017        E = MBB->succ_end(); I != E; ++I)
7018     if (*I != Succ)
7019       return *I;
7020   llvm_unreachable("Expecting a BB with two successors!");
7021 }
7022
7023 /// Return the load opcode for a given load size. If load size >= 8,
7024 /// neon opcode will be returned.
7025 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7026   if (LdSize >= 8)
7027     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7028                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7029   if (IsThumb1)
7030     return LdSize == 4 ? ARM::tLDRi
7031                        : LdSize == 2 ? ARM::tLDRHi
7032                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7033   if (IsThumb2)
7034     return LdSize == 4 ? ARM::t2LDR_POST
7035                        : LdSize == 2 ? ARM::t2LDRH_POST
7036                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7037   return LdSize == 4 ? ARM::LDR_POST_IMM
7038                      : LdSize == 2 ? ARM::LDRH_POST
7039                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7040 }
7041
7042 /// Return the store opcode for a given store size. If store size >= 8,
7043 /// neon opcode will be returned.
7044 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7045   if (StSize >= 8)
7046     return StSize == 16 ? ARM::VST1q32wb_fixed
7047                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7048   if (IsThumb1)
7049     return StSize == 4 ? ARM::tSTRi
7050                        : StSize == 2 ? ARM::tSTRHi
7051                                      : StSize == 1 ? ARM::tSTRBi : 0;
7052   if (IsThumb2)
7053     return StSize == 4 ? ARM::t2STR_POST
7054                        : StSize == 2 ? ARM::t2STRH_POST
7055                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7056   return StSize == 4 ? ARM::STR_POST_IMM
7057                      : StSize == 2 ? ARM::STRH_POST
7058                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7059 }
7060
7061 /// Emit a post-increment load operation with given size. The instructions
7062 /// will be added to BB at Pos.
7063 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7064                        const TargetInstrInfo *TII, DebugLoc dl,
7065                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7066                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7067   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7068   assert(LdOpc != 0 && "Should have a load opcode");
7069   if (LdSize >= 8) {
7070     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7071                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7072                        .addImm(0));
7073   } else if (IsThumb1) {
7074     // load + update AddrIn
7075     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7076                        .addReg(AddrIn).addImm(0));
7077     MachineInstrBuilder MIB =
7078         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7079     MIB = AddDefaultT1CC(MIB);
7080     MIB.addReg(AddrIn).addImm(LdSize);
7081     AddDefaultPred(MIB);
7082   } else if (IsThumb2) {
7083     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7084                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7085                        .addImm(LdSize));
7086   } else { // arm
7087     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7088                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7089                        .addReg(0).addImm(LdSize));
7090   }
7091 }
7092
7093 /// Emit a post-increment store operation with given size. The instructions
7094 /// will be added to BB at Pos.
7095 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7096                        const TargetInstrInfo *TII, DebugLoc dl,
7097                        unsigned StSize, unsigned Data, unsigned AddrIn,
7098                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7099   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7100   assert(StOpc != 0 && "Should have a store opcode");
7101   if (StSize >= 8) {
7102     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7103                        .addReg(AddrIn).addImm(0).addReg(Data));
7104   } else if (IsThumb1) {
7105     // store + update AddrIn
7106     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7107                        .addReg(AddrIn).addImm(0));
7108     MachineInstrBuilder MIB =
7109         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7110     MIB = AddDefaultT1CC(MIB);
7111     MIB.addReg(AddrIn).addImm(StSize);
7112     AddDefaultPred(MIB);
7113   } else if (IsThumb2) {
7114     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7115                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7116   } else { // arm
7117     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7118                        .addReg(Data).addReg(AddrIn).addReg(0)
7119                        .addImm(StSize));
7120   }
7121 }
7122
7123 MachineBasicBlock *
7124 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7125                                    MachineBasicBlock *BB) const {
7126   // This pseudo instruction has 3 operands: dst, src, size
7127   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7128   // Otherwise, we will generate unrolled scalar copies.
7129   const TargetInstrInfo *TII =
7130       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7131   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7132   MachineFunction::iterator It = BB;
7133   ++It;
7134
7135   unsigned dest = MI->getOperand(0).getReg();
7136   unsigned src = MI->getOperand(1).getReg();
7137   unsigned SizeVal = MI->getOperand(2).getImm();
7138   unsigned Align = MI->getOperand(3).getImm();
7139   DebugLoc dl = MI->getDebugLoc();
7140
7141   MachineFunction *MF = BB->getParent();
7142   MachineRegisterInfo &MRI = MF->getRegInfo();
7143   unsigned UnitSize = 0;
7144   const TargetRegisterClass *TRC = nullptr;
7145   const TargetRegisterClass *VecTRC = nullptr;
7146
7147   bool IsThumb1 = Subtarget->isThumb1Only();
7148   bool IsThumb2 = Subtarget->isThumb2();
7149
7150   if (Align & 1) {
7151     UnitSize = 1;
7152   } else if (Align & 2) {
7153     UnitSize = 2;
7154   } else {
7155     // Check whether we can use NEON instructions.
7156     if (!MF->getFunction()->getAttributes().
7157           hasAttribute(AttributeSet::FunctionIndex,
7158                        Attribute::NoImplicitFloat) &&
7159         Subtarget->hasNEON()) {
7160       if ((Align % 16 == 0) && SizeVal >= 16)
7161         UnitSize = 16;
7162       else if ((Align % 8 == 0) && SizeVal >= 8)
7163         UnitSize = 8;
7164     }
7165     // Can't use NEON instructions.
7166     if (UnitSize == 0)
7167       UnitSize = 4;
7168   }
7169
7170   // Select the correct opcode and register class for unit size load/store
7171   bool IsNeon = UnitSize >= 8;
7172   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7173   if (IsNeon)
7174     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7175                             : UnitSize == 8 ? &ARM::DPRRegClass
7176                                             : nullptr;
7177
7178   unsigned BytesLeft = SizeVal % UnitSize;
7179   unsigned LoopSize = SizeVal - BytesLeft;
7180
7181   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7182     // Use LDR and STR to copy.
7183     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7184     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7185     unsigned srcIn = src;
7186     unsigned destIn = dest;
7187     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7188       unsigned srcOut = MRI.createVirtualRegister(TRC);
7189       unsigned destOut = MRI.createVirtualRegister(TRC);
7190       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7191       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7192                  IsThumb1, IsThumb2);
7193       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7194                  IsThumb1, IsThumb2);
7195       srcIn = srcOut;
7196       destIn = destOut;
7197     }
7198
7199     // Handle the leftover bytes with LDRB and STRB.
7200     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7201     // [destOut] = STRB_POST(scratch, destIn, 1)
7202     for (unsigned i = 0; i < BytesLeft; i++) {
7203       unsigned srcOut = MRI.createVirtualRegister(TRC);
7204       unsigned destOut = MRI.createVirtualRegister(TRC);
7205       unsigned scratch = MRI.createVirtualRegister(TRC);
7206       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7207                  IsThumb1, IsThumb2);
7208       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7209                  IsThumb1, IsThumb2);
7210       srcIn = srcOut;
7211       destIn = destOut;
7212     }
7213     MI->eraseFromParent();   // The instruction is gone now.
7214     return BB;
7215   }
7216
7217   // Expand the pseudo op to a loop.
7218   // thisMBB:
7219   //   ...
7220   //   movw varEnd, # --> with thumb2
7221   //   movt varEnd, #
7222   //   ldrcp varEnd, idx --> without thumb2
7223   //   fallthrough --> loopMBB
7224   // loopMBB:
7225   //   PHI varPhi, varEnd, varLoop
7226   //   PHI srcPhi, src, srcLoop
7227   //   PHI destPhi, dst, destLoop
7228   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7229   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7230   //   subs varLoop, varPhi, #UnitSize
7231   //   bne loopMBB
7232   //   fallthrough --> exitMBB
7233   // exitMBB:
7234   //   epilogue to handle left-over bytes
7235   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7236   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7237   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7238   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7239   MF->insert(It, loopMBB);
7240   MF->insert(It, exitMBB);
7241
7242   // Transfer the remainder of BB and its successor edges to exitMBB.
7243   exitMBB->splice(exitMBB->begin(), BB,
7244                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7245   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7246
7247   // Load an immediate to varEnd.
7248   unsigned varEnd = MRI.createVirtualRegister(TRC);
7249   if (IsThumb2) {
7250     unsigned Vtmp = varEnd;
7251     if ((LoopSize & 0xFFFF0000) != 0)
7252       Vtmp = MRI.createVirtualRegister(TRC);
7253     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7254                        .addImm(LoopSize & 0xFFFF));
7255
7256     if ((LoopSize & 0xFFFF0000) != 0)
7257       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7258                          .addReg(Vtmp).addImm(LoopSize >> 16));
7259   } else {
7260     MachineConstantPool *ConstantPool = MF->getConstantPool();
7261     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7262     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7263
7264     // MachineConstantPool wants an explicit alignment.
7265     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7266     if (Align == 0)
7267       Align = getDataLayout()->getTypeAllocSize(C->getType());
7268     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7269
7270     if (IsThumb1)
7271       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7272           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7273     else
7274       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7275           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7276   }
7277   BB->addSuccessor(loopMBB);
7278
7279   // Generate the loop body:
7280   //   varPhi = PHI(varLoop, varEnd)
7281   //   srcPhi = PHI(srcLoop, src)
7282   //   destPhi = PHI(destLoop, dst)
7283   MachineBasicBlock *entryBB = BB;
7284   BB = loopMBB;
7285   unsigned varLoop = MRI.createVirtualRegister(TRC);
7286   unsigned varPhi = MRI.createVirtualRegister(TRC);
7287   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7288   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7289   unsigned destLoop = MRI.createVirtualRegister(TRC);
7290   unsigned destPhi = MRI.createVirtualRegister(TRC);
7291
7292   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7293     .addReg(varLoop).addMBB(loopMBB)
7294     .addReg(varEnd).addMBB(entryBB);
7295   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7296     .addReg(srcLoop).addMBB(loopMBB)
7297     .addReg(src).addMBB(entryBB);
7298   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7299     .addReg(destLoop).addMBB(loopMBB)
7300     .addReg(dest).addMBB(entryBB);
7301
7302   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7303   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7304   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7305   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7306              IsThumb1, IsThumb2);
7307   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7308              IsThumb1, IsThumb2);
7309
7310   // Decrement loop variable by UnitSize.
7311   if (IsThumb1) {
7312     MachineInstrBuilder MIB =
7313         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7314     MIB = AddDefaultT1CC(MIB);
7315     MIB.addReg(varPhi).addImm(UnitSize);
7316     AddDefaultPred(MIB);
7317   } else {
7318     MachineInstrBuilder MIB =
7319         BuildMI(*BB, BB->end(), dl,
7320                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7321     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7322     MIB->getOperand(5).setReg(ARM::CPSR);
7323     MIB->getOperand(5).setIsDef(true);
7324   }
7325   BuildMI(*BB, BB->end(), dl,
7326           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7327       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7328
7329   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7330   BB->addSuccessor(loopMBB);
7331   BB->addSuccessor(exitMBB);
7332
7333   // Add epilogue to handle BytesLeft.
7334   BB = exitMBB;
7335   MachineInstr *StartOfExit = exitMBB->begin();
7336
7337   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7338   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7339   unsigned srcIn = srcLoop;
7340   unsigned destIn = destLoop;
7341   for (unsigned i = 0; i < BytesLeft; i++) {
7342     unsigned srcOut = MRI.createVirtualRegister(TRC);
7343     unsigned destOut = MRI.createVirtualRegister(TRC);
7344     unsigned scratch = MRI.createVirtualRegister(TRC);
7345     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7346                IsThumb1, IsThumb2);
7347     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7348                IsThumb1, IsThumb2);
7349     srcIn = srcOut;
7350     destIn = destOut;
7351   }
7352
7353   MI->eraseFromParent();   // The instruction is gone now.
7354   return BB;
7355 }
7356
7357 MachineBasicBlock *
7358 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7359                                        MachineBasicBlock *MBB) const {
7360   const TargetMachine &TM = getTargetMachine();
7361   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7362   DebugLoc DL = MI->getDebugLoc();
7363
7364   assert(Subtarget->isTargetWindows() &&
7365          "__chkstk is only supported on Windows");
7366   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7367
7368   // __chkstk takes the number of words to allocate on the stack in R4, and
7369   // returns the stack adjustment in number of bytes in R4.  This will not
7370   // clober any other registers (other than the obvious lr).
7371   //
7372   // Although, technically, IP should be considered a register which may be
7373   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7374   // thumb-2 environment, so there is no interworking required.  As a result, we
7375   // do not expect a veneer to be emitted by the linker, clobbering IP.
7376   //
7377   // Each module receives its own copy of __chkstk, so no import thunk is
7378   // required, again, ensuring that IP is not clobbered.
7379   //
7380   // Finally, although some linkers may theoretically provide a trampoline for
7381   // out of range calls (which is quite common due to a 32M range limitation of
7382   // branches for Thumb), we can generate the long-call version via
7383   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7384   // IP.
7385
7386   switch (TM.getCodeModel()) {
7387   case CodeModel::Small:
7388   case CodeModel::Medium:
7389   case CodeModel::Default:
7390   case CodeModel::Kernel:
7391     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7392       .addImm((unsigned)ARMCC::AL).addReg(0)
7393       .addExternalSymbol("__chkstk")
7394       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7395       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7396       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7397     break;
7398   case CodeModel::Large:
7399   case CodeModel::JITDefault: {
7400     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7401     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7402
7403     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7404       .addExternalSymbol("__chkstk");
7405     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7406       .addImm((unsigned)ARMCC::AL).addReg(0)
7407       .addReg(Reg, RegState::Kill)
7408       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7409       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7410       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7411     break;
7412   }
7413   }
7414
7415   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7416                                       ARM::SP)
7417                               .addReg(ARM::SP).addReg(ARM::R4)));
7418
7419   MI->eraseFromParent();
7420   return MBB;
7421 }
7422
7423 MachineBasicBlock *
7424 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7425                                                MachineBasicBlock *BB) const {
7426   const TargetInstrInfo *TII =
7427       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7428   DebugLoc dl = MI->getDebugLoc();
7429   bool isThumb2 = Subtarget->isThumb2();
7430   switch (MI->getOpcode()) {
7431   default: {
7432     MI->dump();
7433     llvm_unreachable("Unexpected instr type to insert");
7434   }
7435   // The Thumb2 pre-indexed stores have the same MI operands, they just
7436   // define them differently in the .td files from the isel patterns, so
7437   // they need pseudos.
7438   case ARM::t2STR_preidx:
7439     MI->setDesc(TII->get(ARM::t2STR_PRE));
7440     return BB;
7441   case ARM::t2STRB_preidx:
7442     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7443     return BB;
7444   case ARM::t2STRH_preidx:
7445     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7446     return BB;
7447
7448   case ARM::STRi_preidx:
7449   case ARM::STRBi_preidx: {
7450     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7451       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7452     // Decode the offset.
7453     unsigned Offset = MI->getOperand(4).getImm();
7454     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7455     Offset = ARM_AM::getAM2Offset(Offset);
7456     if (isSub)
7457       Offset = -Offset;
7458
7459     MachineMemOperand *MMO = *MI->memoperands_begin();
7460     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7461       .addOperand(MI->getOperand(0))  // Rn_wb
7462       .addOperand(MI->getOperand(1))  // Rt
7463       .addOperand(MI->getOperand(2))  // Rn
7464       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7465       .addOperand(MI->getOperand(5))  // pred
7466       .addOperand(MI->getOperand(6))
7467       .addMemOperand(MMO);
7468     MI->eraseFromParent();
7469     return BB;
7470   }
7471   case ARM::STRr_preidx:
7472   case ARM::STRBr_preidx:
7473   case ARM::STRH_preidx: {
7474     unsigned NewOpc;
7475     switch (MI->getOpcode()) {
7476     default: llvm_unreachable("unexpected opcode!");
7477     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7478     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7479     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7480     }
7481     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7482     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7483       MIB.addOperand(MI->getOperand(i));
7484     MI->eraseFromParent();
7485     return BB;
7486   }
7487
7488   case ARM::tMOVCCr_pseudo: {
7489     // To "insert" a SELECT_CC instruction, we actually have to insert the
7490     // diamond control-flow pattern.  The incoming instruction knows the
7491     // destination vreg to set, the condition code register to branch on, the
7492     // true/false values to select between, and a branch opcode to use.
7493     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7494     MachineFunction::iterator It = BB;
7495     ++It;
7496
7497     //  thisMBB:
7498     //  ...
7499     //   TrueVal = ...
7500     //   cmpTY ccX, r1, r2
7501     //   bCC copy1MBB
7502     //   fallthrough --> copy0MBB
7503     MachineBasicBlock *thisMBB  = BB;
7504     MachineFunction *F = BB->getParent();
7505     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7506     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7507     F->insert(It, copy0MBB);
7508     F->insert(It, sinkMBB);
7509
7510     // Transfer the remainder of BB and its successor edges to sinkMBB.
7511     sinkMBB->splice(sinkMBB->begin(), BB,
7512                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7513     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7514
7515     BB->addSuccessor(copy0MBB);
7516     BB->addSuccessor(sinkMBB);
7517
7518     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7519       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7520
7521     //  copy0MBB:
7522     //   %FalseValue = ...
7523     //   # fallthrough to sinkMBB
7524     BB = copy0MBB;
7525
7526     // Update machine-CFG edges
7527     BB->addSuccessor(sinkMBB);
7528
7529     //  sinkMBB:
7530     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7531     //  ...
7532     BB = sinkMBB;
7533     BuildMI(*BB, BB->begin(), dl,
7534             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7535       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7536       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7537
7538     MI->eraseFromParent();   // The pseudo instruction is gone now.
7539     return BB;
7540   }
7541
7542   case ARM::BCCi64:
7543   case ARM::BCCZi64: {
7544     // If there is an unconditional branch to the other successor, remove it.
7545     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7546
7547     // Compare both parts that make up the double comparison separately for
7548     // equality.
7549     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7550
7551     unsigned LHS1 = MI->getOperand(1).getReg();
7552     unsigned LHS2 = MI->getOperand(2).getReg();
7553     if (RHSisZero) {
7554       AddDefaultPred(BuildMI(BB, dl,
7555                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7556                      .addReg(LHS1).addImm(0));
7557       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7558         .addReg(LHS2).addImm(0)
7559         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7560     } else {
7561       unsigned RHS1 = MI->getOperand(3).getReg();
7562       unsigned RHS2 = MI->getOperand(4).getReg();
7563       AddDefaultPred(BuildMI(BB, dl,
7564                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7565                      .addReg(LHS1).addReg(RHS1));
7566       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7567         .addReg(LHS2).addReg(RHS2)
7568         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7569     }
7570
7571     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7572     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7573     if (MI->getOperand(0).getImm() == ARMCC::NE)
7574       std::swap(destMBB, exitMBB);
7575
7576     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7577       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7578     if (isThumb2)
7579       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7580     else
7581       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7582
7583     MI->eraseFromParent();   // The pseudo instruction is gone now.
7584     return BB;
7585   }
7586
7587   case ARM::Int_eh_sjlj_setjmp:
7588   case ARM::Int_eh_sjlj_setjmp_nofp:
7589   case ARM::tInt_eh_sjlj_setjmp:
7590   case ARM::t2Int_eh_sjlj_setjmp:
7591   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7592     EmitSjLjDispatchBlock(MI, BB);
7593     return BB;
7594
7595   case ARM::ABS:
7596   case ARM::t2ABS: {
7597     // To insert an ABS instruction, we have to insert the
7598     // diamond control-flow pattern.  The incoming instruction knows the
7599     // source vreg to test against 0, the destination vreg to set,
7600     // the condition code register to branch on, the
7601     // true/false values to select between, and a branch opcode to use.
7602     // It transforms
7603     //     V1 = ABS V0
7604     // into
7605     //     V2 = MOVS V0
7606     //     BCC                      (branch to SinkBB if V0 >= 0)
7607     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7608     //     SinkBB: V1 = PHI(V2, V3)
7609     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7610     MachineFunction::iterator BBI = BB;
7611     ++BBI;
7612     MachineFunction *Fn = BB->getParent();
7613     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7614     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7615     Fn->insert(BBI, RSBBB);
7616     Fn->insert(BBI, SinkBB);
7617
7618     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7619     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7620     bool isThumb2 = Subtarget->isThumb2();
7621     MachineRegisterInfo &MRI = Fn->getRegInfo();
7622     // In Thumb mode S must not be specified if source register is the SP or
7623     // PC and if destination register is the SP, so restrict register class
7624     unsigned NewRsbDstReg =
7625       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7626
7627     // Transfer the remainder of BB and its successor edges to sinkMBB.
7628     SinkBB->splice(SinkBB->begin(), BB,
7629                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7630     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7631
7632     BB->addSuccessor(RSBBB);
7633     BB->addSuccessor(SinkBB);
7634
7635     // fall through to SinkMBB
7636     RSBBB->addSuccessor(SinkBB);
7637
7638     // insert a cmp at the end of BB
7639     AddDefaultPred(BuildMI(BB, dl,
7640                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7641                    .addReg(ABSSrcReg).addImm(0));
7642
7643     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7644     BuildMI(BB, dl,
7645       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7646       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7647
7648     // insert rsbri in RSBBB
7649     // Note: BCC and rsbri will be converted into predicated rsbmi
7650     // by if-conversion pass
7651     BuildMI(*RSBBB, RSBBB->begin(), dl,
7652       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7653       .addReg(ABSSrcReg, RegState::Kill)
7654       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7655
7656     // insert PHI in SinkBB,
7657     // reuse ABSDstReg to not change uses of ABS instruction
7658     BuildMI(*SinkBB, SinkBB->begin(), dl,
7659       TII->get(ARM::PHI), ABSDstReg)
7660       .addReg(NewRsbDstReg).addMBB(RSBBB)
7661       .addReg(ABSSrcReg).addMBB(BB);
7662
7663     // remove ABS instruction
7664     MI->eraseFromParent();
7665
7666     // return last added BB
7667     return SinkBB;
7668   }
7669   case ARM::COPY_STRUCT_BYVAL_I32:
7670     ++NumLoopByVals;
7671     return EmitStructByval(MI, BB);
7672   case ARM::WIN__CHKSTK:
7673     return EmitLowered__chkstk(MI, BB);
7674   }
7675 }
7676
7677 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7678                                                       SDNode *Node) const {
7679   const MCInstrDesc *MCID = &MI->getDesc();
7680   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7681   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7682   // operand is still set to noreg. If needed, set the optional operand's
7683   // register to CPSR, and remove the redundant implicit def.
7684   //
7685   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7686
7687   // Rename pseudo opcodes.
7688   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7689   if (NewOpc) {
7690     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7691         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7692     MCID = &TII->get(NewOpc);
7693
7694     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7695            "converted opcode should be the same except for cc_out");
7696
7697     MI->setDesc(*MCID);
7698
7699     // Add the optional cc_out operand
7700     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7701   }
7702   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7703
7704   // Any ARM instruction that sets the 's' bit should specify an optional
7705   // "cc_out" operand in the last operand position.
7706   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7707     assert(!NewOpc && "Optional cc_out operand required");
7708     return;
7709   }
7710   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7711   // since we already have an optional CPSR def.
7712   bool definesCPSR = false;
7713   bool deadCPSR = false;
7714   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7715        i != e; ++i) {
7716     const MachineOperand &MO = MI->getOperand(i);
7717     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7718       definesCPSR = true;
7719       if (MO.isDead())
7720         deadCPSR = true;
7721       MI->RemoveOperand(i);
7722       break;
7723     }
7724   }
7725   if (!definesCPSR) {
7726     assert(!NewOpc && "Optional cc_out operand required");
7727     return;
7728   }
7729   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7730   if (deadCPSR) {
7731     assert(!MI->getOperand(ccOutIdx).getReg() &&
7732            "expect uninitialized optional cc_out operand");
7733     return;
7734   }
7735
7736   // If this instruction was defined with an optional CPSR def and its dag node
7737   // had a live implicit CPSR def, then activate the optional CPSR def.
7738   MachineOperand &MO = MI->getOperand(ccOutIdx);
7739   MO.setReg(ARM::CPSR);
7740   MO.setIsDef(true);
7741 }
7742
7743 //===----------------------------------------------------------------------===//
7744 //                           ARM Optimization Hooks
7745 //===----------------------------------------------------------------------===//
7746
7747 // Helper function that checks if N is a null or all ones constant.
7748 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7749   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7750   if (!C)
7751     return false;
7752   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7753 }
7754
7755 // Return true if N is conditionally 0 or all ones.
7756 // Detects these expressions where cc is an i1 value:
7757 //
7758 //   (select cc 0, y)   [AllOnes=0]
7759 //   (select cc y, 0)   [AllOnes=0]
7760 //   (zext cc)          [AllOnes=0]
7761 //   (sext cc)          [AllOnes=0/1]
7762 //   (select cc -1, y)  [AllOnes=1]
7763 //   (select cc y, -1)  [AllOnes=1]
7764 //
7765 // Invert is set when N is the null/all ones constant when CC is false.
7766 // OtherOp is set to the alternative value of N.
7767 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7768                                        SDValue &CC, bool &Invert,
7769                                        SDValue &OtherOp,
7770                                        SelectionDAG &DAG) {
7771   switch (N->getOpcode()) {
7772   default: return false;
7773   case ISD::SELECT: {
7774     CC = N->getOperand(0);
7775     SDValue N1 = N->getOperand(1);
7776     SDValue N2 = N->getOperand(2);
7777     if (isZeroOrAllOnes(N1, AllOnes)) {
7778       Invert = false;
7779       OtherOp = N2;
7780       return true;
7781     }
7782     if (isZeroOrAllOnes(N2, AllOnes)) {
7783       Invert = true;
7784       OtherOp = N1;
7785       return true;
7786     }
7787     return false;
7788   }
7789   case ISD::ZERO_EXTEND:
7790     // (zext cc) can never be the all ones value.
7791     if (AllOnes)
7792       return false;
7793     // Fall through.
7794   case ISD::SIGN_EXTEND: {
7795     EVT VT = N->getValueType(0);
7796     CC = N->getOperand(0);
7797     if (CC.getValueType() != MVT::i1)
7798       return false;
7799     Invert = !AllOnes;
7800     if (AllOnes)
7801       // When looking for an AllOnes constant, N is an sext, and the 'other'
7802       // value is 0.
7803       OtherOp = DAG.getConstant(0, VT);
7804     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7805       // When looking for a 0 constant, N can be zext or sext.
7806       OtherOp = DAG.getConstant(1, VT);
7807     else
7808       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7809     return true;
7810   }
7811   }
7812 }
7813
7814 // Combine a constant select operand into its use:
7815 //
7816 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7817 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7818 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7819 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7820 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7821 //
7822 // The transform is rejected if the select doesn't have a constant operand that
7823 // is null, or all ones when AllOnes is set.
7824 //
7825 // Also recognize sext/zext from i1:
7826 //
7827 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7828 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7829 //
7830 // These transformations eventually create predicated instructions.
7831 //
7832 // @param N       The node to transform.
7833 // @param Slct    The N operand that is a select.
7834 // @param OtherOp The other N operand (x above).
7835 // @param DCI     Context.
7836 // @param AllOnes Require the select constant to be all ones instead of null.
7837 // @returns The new node, or SDValue() on failure.
7838 static
7839 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7840                             TargetLowering::DAGCombinerInfo &DCI,
7841                             bool AllOnes = false) {
7842   SelectionDAG &DAG = DCI.DAG;
7843   EVT VT = N->getValueType(0);
7844   SDValue NonConstantVal;
7845   SDValue CCOp;
7846   bool SwapSelectOps;
7847   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7848                                   NonConstantVal, DAG))
7849     return SDValue();
7850
7851   // Slct is now know to be the desired identity constant when CC is true.
7852   SDValue TrueVal = OtherOp;
7853   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7854                                  OtherOp, NonConstantVal);
7855   // Unless SwapSelectOps says CC should be false.
7856   if (SwapSelectOps)
7857     std::swap(TrueVal, FalseVal);
7858
7859   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7860                      CCOp, TrueVal, FalseVal);
7861 }
7862
7863 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7864 static
7865 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7866                                        TargetLowering::DAGCombinerInfo &DCI) {
7867   SDValue N0 = N->getOperand(0);
7868   SDValue N1 = N->getOperand(1);
7869   if (N0.getNode()->hasOneUse()) {
7870     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7871     if (Result.getNode())
7872       return Result;
7873   }
7874   if (N1.getNode()->hasOneUse()) {
7875     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7876     if (Result.getNode())
7877       return Result;
7878   }
7879   return SDValue();
7880 }
7881
7882 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7883 // (only after legalization).
7884 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7885                                  TargetLowering::DAGCombinerInfo &DCI,
7886                                  const ARMSubtarget *Subtarget) {
7887
7888   // Only perform optimization if after legalize, and if NEON is available. We
7889   // also expected both operands to be BUILD_VECTORs.
7890   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7891       || N0.getOpcode() != ISD::BUILD_VECTOR
7892       || N1.getOpcode() != ISD::BUILD_VECTOR)
7893     return SDValue();
7894
7895   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7896   EVT VT = N->getValueType(0);
7897   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7898     return SDValue();
7899
7900   // Check that the vector operands are of the right form.
7901   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7902   // operands, where N is the size of the formed vector.
7903   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7904   // index such that we have a pair wise add pattern.
7905
7906   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7907   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7908     return SDValue();
7909   SDValue Vec = N0->getOperand(0)->getOperand(0);
7910   SDNode *V = Vec.getNode();
7911   unsigned nextIndex = 0;
7912
7913   // For each operands to the ADD which are BUILD_VECTORs,
7914   // check to see if each of their operands are an EXTRACT_VECTOR with
7915   // the same vector and appropriate index.
7916   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7917     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7918         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7919
7920       SDValue ExtVec0 = N0->getOperand(i);
7921       SDValue ExtVec1 = N1->getOperand(i);
7922
7923       // First operand is the vector, verify its the same.
7924       if (V != ExtVec0->getOperand(0).getNode() ||
7925           V != ExtVec1->getOperand(0).getNode())
7926         return SDValue();
7927
7928       // Second is the constant, verify its correct.
7929       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7930       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7931
7932       // For the constant, we want to see all the even or all the odd.
7933       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7934           || C1->getZExtValue() != nextIndex+1)
7935         return SDValue();
7936
7937       // Increment index.
7938       nextIndex+=2;
7939     } else
7940       return SDValue();
7941   }
7942
7943   // Create VPADDL node.
7944   SelectionDAG &DAG = DCI.DAG;
7945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7946
7947   // Build operand list.
7948   SmallVector<SDValue, 8> Ops;
7949   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7950                                 TLI.getPointerTy()));
7951
7952   // Input is the vector.
7953   Ops.push_back(Vec);
7954
7955   // Get widened type and narrowed type.
7956   MVT widenType;
7957   unsigned numElem = VT.getVectorNumElements();
7958   
7959   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7960   switch (inputLaneType.getSimpleVT().SimpleTy) {
7961     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7962     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7963     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7964     default:
7965       llvm_unreachable("Invalid vector element type for padd optimization.");
7966   }
7967
7968   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7969   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7970   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7971 }
7972
7973 static SDValue findMUL_LOHI(SDValue V) {
7974   if (V->getOpcode() == ISD::UMUL_LOHI ||
7975       V->getOpcode() == ISD::SMUL_LOHI)
7976     return V;
7977   return SDValue();
7978 }
7979
7980 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7981                                      TargetLowering::DAGCombinerInfo &DCI,
7982                                      const ARMSubtarget *Subtarget) {
7983
7984   if (Subtarget->isThumb1Only()) return SDValue();
7985
7986   // Only perform the checks after legalize when the pattern is available.
7987   if (DCI.isBeforeLegalize()) return SDValue();
7988
7989   // Look for multiply add opportunities.
7990   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7991   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7992   // a glue link from the first add to the second add.
7993   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7994   // a S/UMLAL instruction.
7995   //          loAdd   UMUL_LOHI
7996   //            \    / :lo    \ :hi
7997   //             \  /          \          [no multiline comment]
7998   //              ADDC         |  hiAdd
7999   //                 \ :glue  /  /
8000   //                  \      /  /
8001   //                    ADDE
8002   //
8003   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8004   SDValue AddcOp0 = AddcNode->getOperand(0);
8005   SDValue AddcOp1 = AddcNode->getOperand(1);
8006
8007   // Check if the two operands are from the same mul_lohi node.
8008   if (AddcOp0.getNode() == AddcOp1.getNode())
8009     return SDValue();
8010
8011   assert(AddcNode->getNumValues() == 2 &&
8012          AddcNode->getValueType(0) == MVT::i32 &&
8013          "Expect ADDC with two result values. First: i32");
8014
8015   // Check that we have a glued ADDC node.
8016   if (AddcNode->getValueType(1) != MVT::Glue)
8017     return SDValue();
8018
8019   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8020   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8021       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8022       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8023       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8024     return SDValue();
8025
8026   // Look for the glued ADDE.
8027   SDNode* AddeNode = AddcNode->getGluedUser();
8028   if (!AddeNode)
8029     return SDValue();
8030
8031   // Make sure it is really an ADDE.
8032   if (AddeNode->getOpcode() != ISD::ADDE)
8033     return SDValue();
8034
8035   assert(AddeNode->getNumOperands() == 3 &&
8036          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8037          "ADDE node has the wrong inputs");
8038
8039   // Check for the triangle shape.
8040   SDValue AddeOp0 = AddeNode->getOperand(0);
8041   SDValue AddeOp1 = AddeNode->getOperand(1);
8042
8043   // Make sure that the ADDE operands are not coming from the same node.
8044   if (AddeOp0.getNode() == AddeOp1.getNode())
8045     return SDValue();
8046
8047   // Find the MUL_LOHI node walking up ADDE's operands.
8048   bool IsLeftOperandMUL = false;
8049   SDValue MULOp = findMUL_LOHI(AddeOp0);
8050   if (MULOp == SDValue())
8051    MULOp = findMUL_LOHI(AddeOp1);
8052   else
8053     IsLeftOperandMUL = true;
8054   if (MULOp == SDValue())
8055      return SDValue();
8056
8057   // Figure out the right opcode.
8058   unsigned Opc = MULOp->getOpcode();
8059   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8060
8061   // Figure out the high and low input values to the MLAL node.
8062   SDValue* HiMul = &MULOp;
8063   SDValue* HiAdd = nullptr;
8064   SDValue* LoMul = nullptr;
8065   SDValue* LowAdd = nullptr;
8066
8067   if (IsLeftOperandMUL)
8068     HiAdd = &AddeOp1;
8069   else
8070     HiAdd = &AddeOp0;
8071
8072
8073   if (AddcOp0->getOpcode() == Opc) {
8074     LoMul = &AddcOp0;
8075     LowAdd = &AddcOp1;
8076   }
8077   if (AddcOp1->getOpcode() == Opc) {
8078     LoMul = &AddcOp1;
8079     LowAdd = &AddcOp0;
8080   }
8081
8082   if (!LoMul)
8083     return SDValue();
8084
8085   if (LoMul->getNode() != HiMul->getNode())
8086     return SDValue();
8087
8088   // Create the merged node.
8089   SelectionDAG &DAG = DCI.DAG;
8090
8091   // Build operand list.
8092   SmallVector<SDValue, 8> Ops;
8093   Ops.push_back(LoMul->getOperand(0));
8094   Ops.push_back(LoMul->getOperand(1));
8095   Ops.push_back(*LowAdd);
8096   Ops.push_back(*HiAdd);
8097
8098   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8099                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8100
8101   // Replace the ADDs' nodes uses by the MLA node's values.
8102   SDValue HiMLALResult(MLALNode.getNode(), 1);
8103   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8104
8105   SDValue LoMLALResult(MLALNode.getNode(), 0);
8106   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8107
8108   // Return original node to notify the driver to stop replacing.
8109   SDValue resNode(AddcNode, 0);
8110   return resNode;
8111 }
8112
8113 /// PerformADDCCombine - Target-specific dag combine transform from
8114 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8115 static SDValue PerformADDCCombine(SDNode *N,
8116                                  TargetLowering::DAGCombinerInfo &DCI,
8117                                  const ARMSubtarget *Subtarget) {
8118
8119   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8120
8121 }
8122
8123 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8124 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8125 /// called with the default operands, and if that fails, with commuted
8126 /// operands.
8127 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8128                                           TargetLowering::DAGCombinerInfo &DCI,
8129                                           const ARMSubtarget *Subtarget){
8130
8131   // Attempt to create vpaddl for this add.
8132   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8133   if (Result.getNode())
8134     return Result;
8135
8136   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8137   if (N0.getNode()->hasOneUse()) {
8138     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8139     if (Result.getNode()) return Result;
8140   }
8141   return SDValue();
8142 }
8143
8144 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8145 ///
8146 static SDValue PerformADDCombine(SDNode *N,
8147                                  TargetLowering::DAGCombinerInfo &DCI,
8148                                  const ARMSubtarget *Subtarget) {
8149   SDValue N0 = N->getOperand(0);
8150   SDValue N1 = N->getOperand(1);
8151
8152   // First try with the default operand order.
8153   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8154   if (Result.getNode())
8155     return Result;
8156
8157   // If that didn't work, try again with the operands commuted.
8158   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8159 }
8160
8161 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8162 ///
8163 static SDValue PerformSUBCombine(SDNode *N,
8164                                  TargetLowering::DAGCombinerInfo &DCI) {
8165   SDValue N0 = N->getOperand(0);
8166   SDValue N1 = N->getOperand(1);
8167
8168   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8169   if (N1.getNode()->hasOneUse()) {
8170     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8171     if (Result.getNode()) return Result;
8172   }
8173
8174   return SDValue();
8175 }
8176
8177 /// PerformVMULCombine
8178 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8179 /// special multiplier accumulator forwarding.
8180 ///   vmul d3, d0, d2
8181 ///   vmla d3, d1, d2
8182 /// is faster than
8183 ///   vadd d3, d0, d1
8184 ///   vmul d3, d3, d2
8185 //  However, for (A + B) * (A + B),
8186 //    vadd d2, d0, d1
8187 //    vmul d3, d0, d2
8188 //    vmla d3, d1, d2
8189 //  is slower than
8190 //    vadd d2, d0, d1
8191 //    vmul d3, d2, d2
8192 static SDValue PerformVMULCombine(SDNode *N,
8193                                   TargetLowering::DAGCombinerInfo &DCI,
8194                                   const ARMSubtarget *Subtarget) {
8195   if (!Subtarget->hasVMLxForwarding())
8196     return SDValue();
8197
8198   SelectionDAG &DAG = DCI.DAG;
8199   SDValue N0 = N->getOperand(0);
8200   SDValue N1 = N->getOperand(1);
8201   unsigned Opcode = N0.getOpcode();
8202   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8203       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8204     Opcode = N1.getOpcode();
8205     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8206         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8207       return SDValue();
8208     std::swap(N0, N1);
8209   }
8210
8211   if (N0 == N1)
8212     return SDValue();
8213
8214   EVT VT = N->getValueType(0);
8215   SDLoc DL(N);
8216   SDValue N00 = N0->getOperand(0);
8217   SDValue N01 = N0->getOperand(1);
8218   return DAG.getNode(Opcode, DL, VT,
8219                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8220                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8221 }
8222
8223 static SDValue PerformMULCombine(SDNode *N,
8224                                  TargetLowering::DAGCombinerInfo &DCI,
8225                                  const ARMSubtarget *Subtarget) {
8226   SelectionDAG &DAG = DCI.DAG;
8227
8228   if (Subtarget->isThumb1Only())
8229     return SDValue();
8230
8231   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8232     return SDValue();
8233
8234   EVT VT = N->getValueType(0);
8235   if (VT.is64BitVector() || VT.is128BitVector())
8236     return PerformVMULCombine(N, DCI, Subtarget);
8237   if (VT != MVT::i32)
8238     return SDValue();
8239
8240   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8241   if (!C)
8242     return SDValue();
8243
8244   int64_t MulAmt = C->getSExtValue();
8245   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8246
8247   ShiftAmt = ShiftAmt & (32 - 1);
8248   SDValue V = N->getOperand(0);
8249   SDLoc DL(N);
8250
8251   SDValue Res;
8252   MulAmt >>= ShiftAmt;
8253
8254   if (MulAmt >= 0) {
8255     if (isPowerOf2_32(MulAmt - 1)) {
8256       // (mul x, 2^N + 1) => (add (shl x, N), x)
8257       Res = DAG.getNode(ISD::ADD, DL, VT,
8258                         V,
8259                         DAG.getNode(ISD::SHL, DL, VT,
8260                                     V,
8261                                     DAG.getConstant(Log2_32(MulAmt - 1),
8262                                                     MVT::i32)));
8263     } else if (isPowerOf2_32(MulAmt + 1)) {
8264       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8265       Res = DAG.getNode(ISD::SUB, DL, VT,
8266                         DAG.getNode(ISD::SHL, DL, VT,
8267                                     V,
8268                                     DAG.getConstant(Log2_32(MulAmt + 1),
8269                                                     MVT::i32)),
8270                         V);
8271     } else
8272       return SDValue();
8273   } else {
8274     uint64_t MulAmtAbs = -MulAmt;
8275     if (isPowerOf2_32(MulAmtAbs + 1)) {
8276       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8277       Res = DAG.getNode(ISD::SUB, DL, VT,
8278                         V,
8279                         DAG.getNode(ISD::SHL, DL, VT,
8280                                     V,
8281                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8282                                                     MVT::i32)));
8283     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8284       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8285       Res = DAG.getNode(ISD::ADD, DL, VT,
8286                         V,
8287                         DAG.getNode(ISD::SHL, DL, VT,
8288                                     V,
8289                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8290                                                     MVT::i32)));
8291       Res = DAG.getNode(ISD::SUB, DL, VT,
8292                         DAG.getConstant(0, MVT::i32),Res);
8293
8294     } else
8295       return SDValue();
8296   }
8297
8298   if (ShiftAmt != 0)
8299     Res = DAG.getNode(ISD::SHL, DL, VT,
8300                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8301
8302   // Do not add new nodes to DAG combiner worklist.
8303   DCI.CombineTo(N, Res, false);
8304   return SDValue();
8305 }
8306
8307 static SDValue PerformANDCombine(SDNode *N,
8308                                  TargetLowering::DAGCombinerInfo &DCI,
8309                                  const ARMSubtarget *Subtarget) {
8310
8311   // Attempt to use immediate-form VBIC
8312   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8313   SDLoc dl(N);
8314   EVT VT = N->getValueType(0);
8315   SelectionDAG &DAG = DCI.DAG;
8316
8317   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8318     return SDValue();
8319
8320   APInt SplatBits, SplatUndef;
8321   unsigned SplatBitSize;
8322   bool HasAnyUndefs;
8323   if (BVN &&
8324       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8325     if (SplatBitSize <= 64) {
8326       EVT VbicVT;
8327       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8328                                       SplatUndef.getZExtValue(), SplatBitSize,
8329                                       DAG, VbicVT, VT.is128BitVector(),
8330                                       OtherModImm);
8331       if (Val.getNode()) {
8332         SDValue Input =
8333           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8334         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8335         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8336       }
8337     }
8338   }
8339
8340   if (!Subtarget->isThumb1Only()) {
8341     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8342     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8343     if (Result.getNode())
8344       return Result;
8345   }
8346
8347   return SDValue();
8348 }
8349
8350 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8351 static SDValue PerformORCombine(SDNode *N,
8352                                 TargetLowering::DAGCombinerInfo &DCI,
8353                                 const ARMSubtarget *Subtarget) {
8354   // Attempt to use immediate-form VORR
8355   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8356   SDLoc dl(N);
8357   EVT VT = N->getValueType(0);
8358   SelectionDAG &DAG = DCI.DAG;
8359
8360   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8361     return SDValue();
8362
8363   APInt SplatBits, SplatUndef;
8364   unsigned SplatBitSize;
8365   bool HasAnyUndefs;
8366   if (BVN && Subtarget->hasNEON() &&
8367       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8368     if (SplatBitSize <= 64) {
8369       EVT VorrVT;
8370       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8371                                       SplatUndef.getZExtValue(), SplatBitSize,
8372                                       DAG, VorrVT, VT.is128BitVector(),
8373                                       OtherModImm);
8374       if (Val.getNode()) {
8375         SDValue Input =
8376           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8377         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8378         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8379       }
8380     }
8381   }
8382
8383   if (!Subtarget->isThumb1Only()) {
8384     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8385     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8386     if (Result.getNode())
8387       return Result;
8388   }
8389
8390   // The code below optimizes (or (and X, Y), Z).
8391   // The AND operand needs to have a single user to make these optimizations
8392   // profitable.
8393   SDValue N0 = N->getOperand(0);
8394   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8395     return SDValue();
8396   SDValue N1 = N->getOperand(1);
8397
8398   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8399   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8400       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8401     APInt SplatUndef;
8402     unsigned SplatBitSize;
8403     bool HasAnyUndefs;
8404
8405     APInt SplatBits0, SplatBits1;
8406     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8407     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8408     // Ensure that the second operand of both ands are constants
8409     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8410                                       HasAnyUndefs) && !HasAnyUndefs) {
8411         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8412                                           HasAnyUndefs) && !HasAnyUndefs) {
8413             // Ensure that the bit width of the constants are the same and that
8414             // the splat arguments are logical inverses as per the pattern we
8415             // are trying to simplify.
8416             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8417                 SplatBits0 == ~SplatBits1) {
8418                 // Canonicalize the vector type to make instruction selection
8419                 // simpler.
8420                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8421                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8422                                              N0->getOperand(1),
8423                                              N0->getOperand(0),
8424                                              N1->getOperand(0));
8425                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8426             }
8427         }
8428     }
8429   }
8430
8431   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8432   // reasonable.
8433
8434   // BFI is only available on V6T2+
8435   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8436     return SDValue();
8437
8438   SDLoc DL(N);
8439   // 1) or (and A, mask), val => ARMbfi A, val, mask
8440   //      iff (val & mask) == val
8441   //
8442   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8443   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8444   //          && mask == ~mask2
8445   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8446   //          && ~mask == mask2
8447   //  (i.e., copy a bitfield value into another bitfield of the same width)
8448
8449   if (VT != MVT::i32)
8450     return SDValue();
8451
8452   SDValue N00 = N0.getOperand(0);
8453
8454   // The value and the mask need to be constants so we can verify this is
8455   // actually a bitfield set. If the mask is 0xffff, we can do better
8456   // via a movt instruction, so don't use BFI in that case.
8457   SDValue MaskOp = N0.getOperand(1);
8458   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8459   if (!MaskC)
8460     return SDValue();
8461   unsigned Mask = MaskC->getZExtValue();
8462   if (Mask == 0xffff)
8463     return SDValue();
8464   SDValue Res;
8465   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8466   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8467   if (N1C) {
8468     unsigned Val = N1C->getZExtValue();
8469     if ((Val & ~Mask) != Val)
8470       return SDValue();
8471
8472     if (ARM::isBitFieldInvertedMask(Mask)) {
8473       Val >>= countTrailingZeros(~Mask);
8474
8475       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8476                         DAG.getConstant(Val, MVT::i32),
8477                         DAG.getConstant(Mask, MVT::i32));
8478
8479       // Do not add new nodes to DAG combiner worklist.
8480       DCI.CombineTo(N, Res, false);
8481       return SDValue();
8482     }
8483   } else if (N1.getOpcode() == ISD::AND) {
8484     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8485     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8486     if (!N11C)
8487       return SDValue();
8488     unsigned Mask2 = N11C->getZExtValue();
8489
8490     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8491     // as is to match.
8492     if (ARM::isBitFieldInvertedMask(Mask) &&
8493         (Mask == ~Mask2)) {
8494       // The pack halfword instruction works better for masks that fit it,
8495       // so use that when it's available.
8496       if (Subtarget->hasT2ExtractPack() &&
8497           (Mask == 0xffff || Mask == 0xffff0000))
8498         return SDValue();
8499       // 2a
8500       unsigned amt = countTrailingZeros(Mask2);
8501       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8502                         DAG.getConstant(amt, MVT::i32));
8503       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8504                         DAG.getConstant(Mask, MVT::i32));
8505       // Do not add new nodes to DAG combiner worklist.
8506       DCI.CombineTo(N, Res, false);
8507       return SDValue();
8508     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8509                (~Mask == Mask2)) {
8510       // The pack halfword instruction works better for masks that fit it,
8511       // so use that when it's available.
8512       if (Subtarget->hasT2ExtractPack() &&
8513           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8514         return SDValue();
8515       // 2b
8516       unsigned lsb = countTrailingZeros(Mask);
8517       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8518                         DAG.getConstant(lsb, MVT::i32));
8519       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8520                         DAG.getConstant(Mask2, MVT::i32));
8521       // Do not add new nodes to DAG combiner worklist.
8522       DCI.CombineTo(N, Res, false);
8523       return SDValue();
8524     }
8525   }
8526
8527   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8528       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8529       ARM::isBitFieldInvertedMask(~Mask)) {
8530     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8531     // where lsb(mask) == #shamt and masked bits of B are known zero.
8532     SDValue ShAmt = N00.getOperand(1);
8533     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8534     unsigned LSB = countTrailingZeros(Mask);
8535     if (ShAmtC != LSB)
8536       return SDValue();
8537
8538     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8539                       DAG.getConstant(~Mask, MVT::i32));
8540
8541     // Do not add new nodes to DAG combiner worklist.
8542     DCI.CombineTo(N, Res, false);
8543   }
8544
8545   return SDValue();
8546 }
8547
8548 static SDValue PerformXORCombine(SDNode *N,
8549                                  TargetLowering::DAGCombinerInfo &DCI,
8550                                  const ARMSubtarget *Subtarget) {
8551   EVT VT = N->getValueType(0);
8552   SelectionDAG &DAG = DCI.DAG;
8553
8554   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8555     return SDValue();
8556
8557   if (!Subtarget->isThumb1Only()) {
8558     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8559     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8560     if (Result.getNode())
8561       return Result;
8562   }
8563
8564   return SDValue();
8565 }
8566
8567 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8568 /// the bits being cleared by the AND are not demanded by the BFI.
8569 static SDValue PerformBFICombine(SDNode *N,
8570                                  TargetLowering::DAGCombinerInfo &DCI) {
8571   SDValue N1 = N->getOperand(1);
8572   if (N1.getOpcode() == ISD::AND) {
8573     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8574     if (!N11C)
8575       return SDValue();
8576     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8577     unsigned LSB = countTrailingZeros(~InvMask);
8578     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8579     unsigned Mask = (1 << Width)-1;
8580     unsigned Mask2 = N11C->getZExtValue();
8581     if ((Mask & (~Mask2)) == 0)
8582       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8583                              N->getOperand(0), N1.getOperand(0),
8584                              N->getOperand(2));
8585   }
8586   return SDValue();
8587 }
8588
8589 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8590 /// ARMISD::VMOVRRD.
8591 static SDValue PerformVMOVRRDCombine(SDNode *N,
8592                                      TargetLowering::DAGCombinerInfo &DCI,
8593                                      const ARMSubtarget *Subtarget) {
8594   // vmovrrd(vmovdrr x, y) -> x,y
8595   SDValue InDouble = N->getOperand(0);
8596   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8597     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8598
8599   // vmovrrd(load f64) -> (load i32), (load i32)
8600   SDNode *InNode = InDouble.getNode();
8601   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8602       InNode->getValueType(0) == MVT::f64 &&
8603       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8604       !cast<LoadSDNode>(InNode)->isVolatile()) {
8605     // TODO: Should this be done for non-FrameIndex operands?
8606     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8607
8608     SelectionDAG &DAG = DCI.DAG;
8609     SDLoc DL(LD);
8610     SDValue BasePtr = LD->getBasePtr();
8611     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8612                                  LD->getPointerInfo(), LD->isVolatile(),
8613                                  LD->isNonTemporal(), LD->isInvariant(),
8614                                  LD->getAlignment());
8615
8616     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8617                                     DAG.getConstant(4, MVT::i32));
8618     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8619                                  LD->getPointerInfo(), LD->isVolatile(),
8620                                  LD->isNonTemporal(), LD->isInvariant(),
8621                                  std::min(4U, LD->getAlignment() / 2));
8622
8623     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8624     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8625       std::swap (NewLD1, NewLD2);
8626     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8627     return Result;
8628   }
8629
8630   return SDValue();
8631 }
8632
8633 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8634 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8635 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8636   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8637   SDValue Op0 = N->getOperand(0);
8638   SDValue Op1 = N->getOperand(1);
8639   if (Op0.getOpcode() == ISD::BITCAST)
8640     Op0 = Op0.getOperand(0);
8641   if (Op1.getOpcode() == ISD::BITCAST)
8642     Op1 = Op1.getOperand(0);
8643   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8644       Op0.getNode() == Op1.getNode() &&
8645       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8646     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8647                        N->getValueType(0), Op0.getOperand(0));
8648   return SDValue();
8649 }
8650
8651 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8652 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8653 /// i64 vector to have f64 elements, since the value can then be loaded
8654 /// directly into a VFP register.
8655 static bool hasNormalLoadOperand(SDNode *N) {
8656   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8657   for (unsigned i = 0; i < NumElts; ++i) {
8658     SDNode *Elt = N->getOperand(i).getNode();
8659     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8660       return true;
8661   }
8662   return false;
8663 }
8664
8665 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8666 /// ISD::BUILD_VECTOR.
8667 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8668                                           TargetLowering::DAGCombinerInfo &DCI,
8669                                           const ARMSubtarget *Subtarget) {
8670   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8671   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8672   // into a pair of GPRs, which is fine when the value is used as a scalar,
8673   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8674   SelectionDAG &DAG = DCI.DAG;
8675   if (N->getNumOperands() == 2) {
8676     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8677     if (RV.getNode())
8678       return RV;
8679   }
8680
8681   // Load i64 elements as f64 values so that type legalization does not split
8682   // them up into i32 values.
8683   EVT VT = N->getValueType(0);
8684   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8685     return SDValue();
8686   SDLoc dl(N);
8687   SmallVector<SDValue, 8> Ops;
8688   unsigned NumElts = VT.getVectorNumElements();
8689   for (unsigned i = 0; i < NumElts; ++i) {
8690     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8691     Ops.push_back(V);
8692     // Make the DAGCombiner fold the bitcast.
8693     DCI.AddToWorklist(V.getNode());
8694   }
8695   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8696   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8697   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8698 }
8699
8700 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8701 static SDValue
8702 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8703   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8704   // At that time, we may have inserted bitcasts from integer to float.
8705   // If these bitcasts have survived DAGCombine, change the lowering of this
8706   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8707   // force to use floating point types.
8708
8709   // Make sure we can change the type of the vector.
8710   // This is possible iff:
8711   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8712   //    1.1. Vector is used only once.
8713   //    1.2. Use is a bit convert to an integer type.
8714   // 2. The size of its operands are 32-bits (64-bits are not legal).
8715   EVT VT = N->getValueType(0);
8716   EVT EltVT = VT.getVectorElementType();
8717
8718   // Check 1.1. and 2.
8719   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8720     return SDValue();
8721
8722   // By construction, the input type must be float.
8723   assert(EltVT == MVT::f32 && "Unexpected type!");
8724
8725   // Check 1.2.
8726   SDNode *Use = *N->use_begin();
8727   if (Use->getOpcode() != ISD::BITCAST ||
8728       Use->getValueType(0).isFloatingPoint())
8729     return SDValue();
8730
8731   // Check profitability.
8732   // Model is, if more than half of the relevant operands are bitcast from
8733   // i32, turn the build_vector into a sequence of insert_vector_elt.
8734   // Relevant operands are everything that is not statically
8735   // (i.e., at compile time) bitcasted.
8736   unsigned NumOfBitCastedElts = 0;
8737   unsigned NumElts = VT.getVectorNumElements();
8738   unsigned NumOfRelevantElts = NumElts;
8739   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8740     SDValue Elt = N->getOperand(Idx);
8741     if (Elt->getOpcode() == ISD::BITCAST) {
8742       // Assume only bit cast to i32 will go away.
8743       if (Elt->getOperand(0).getValueType() == MVT::i32)
8744         ++NumOfBitCastedElts;
8745     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8746       // Constants are statically casted, thus do not count them as
8747       // relevant operands.
8748       --NumOfRelevantElts;
8749   }
8750
8751   // Check if more than half of the elements require a non-free bitcast.
8752   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8753     return SDValue();
8754
8755   SelectionDAG &DAG = DCI.DAG;
8756   // Create the new vector type.
8757   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8758   // Check if the type is legal.
8759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8760   if (!TLI.isTypeLegal(VecVT))
8761     return SDValue();
8762
8763   // Combine:
8764   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8765   // => BITCAST INSERT_VECTOR_ELT
8766   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8767   //                      (BITCAST EN), N.
8768   SDValue Vec = DAG.getUNDEF(VecVT);
8769   SDLoc dl(N);
8770   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8771     SDValue V = N->getOperand(Idx);
8772     if (V.getOpcode() == ISD::UNDEF)
8773       continue;
8774     if (V.getOpcode() == ISD::BITCAST &&
8775         V->getOperand(0).getValueType() == MVT::i32)
8776       // Fold obvious case.
8777       V = V.getOperand(0);
8778     else {
8779       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8780       // Make the DAGCombiner fold the bitcasts.
8781       DCI.AddToWorklist(V.getNode());
8782     }
8783     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8784     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8785   }
8786   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8787   // Make the DAGCombiner fold the bitcasts.
8788   DCI.AddToWorklist(Vec.getNode());
8789   return Vec;
8790 }
8791
8792 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8793 /// ISD::INSERT_VECTOR_ELT.
8794 static SDValue PerformInsertEltCombine(SDNode *N,
8795                                        TargetLowering::DAGCombinerInfo &DCI) {
8796   // Bitcast an i64 load inserted into a vector to f64.
8797   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8798   EVT VT = N->getValueType(0);
8799   SDNode *Elt = N->getOperand(1).getNode();
8800   if (VT.getVectorElementType() != MVT::i64 ||
8801       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8802     return SDValue();
8803
8804   SelectionDAG &DAG = DCI.DAG;
8805   SDLoc dl(N);
8806   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8807                                  VT.getVectorNumElements());
8808   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8809   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8810   // Make the DAGCombiner fold the bitcasts.
8811   DCI.AddToWorklist(Vec.getNode());
8812   DCI.AddToWorklist(V.getNode());
8813   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8814                                Vec, V, N->getOperand(2));
8815   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8816 }
8817
8818 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8819 /// ISD::VECTOR_SHUFFLE.
8820 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8821   // The LLVM shufflevector instruction does not require the shuffle mask
8822   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8823   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8824   // operands do not match the mask length, they are extended by concatenating
8825   // them with undef vectors.  That is probably the right thing for other
8826   // targets, but for NEON it is better to concatenate two double-register
8827   // size vector operands into a single quad-register size vector.  Do that
8828   // transformation here:
8829   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8830   //   shuffle(concat(v1, v2), undef)
8831   SDValue Op0 = N->getOperand(0);
8832   SDValue Op1 = N->getOperand(1);
8833   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8834       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8835       Op0.getNumOperands() != 2 ||
8836       Op1.getNumOperands() != 2)
8837     return SDValue();
8838   SDValue Concat0Op1 = Op0.getOperand(1);
8839   SDValue Concat1Op1 = Op1.getOperand(1);
8840   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8841       Concat1Op1.getOpcode() != ISD::UNDEF)
8842     return SDValue();
8843   // Skip the transformation if any of the types are illegal.
8844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8845   EVT VT = N->getValueType(0);
8846   if (!TLI.isTypeLegal(VT) ||
8847       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8848       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8849     return SDValue();
8850
8851   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8852                                   Op0.getOperand(0), Op1.getOperand(0));
8853   // Translate the shuffle mask.
8854   SmallVector<int, 16> NewMask;
8855   unsigned NumElts = VT.getVectorNumElements();
8856   unsigned HalfElts = NumElts/2;
8857   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8858   for (unsigned n = 0; n < NumElts; ++n) {
8859     int MaskElt = SVN->getMaskElt(n);
8860     int NewElt = -1;
8861     if (MaskElt < (int)HalfElts)
8862       NewElt = MaskElt;
8863     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8864       NewElt = HalfElts + MaskElt - NumElts;
8865     NewMask.push_back(NewElt);
8866   }
8867   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8868                               DAG.getUNDEF(VT), NewMask.data());
8869 }
8870
8871 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8872 /// NEON load/store intrinsics to merge base address updates.
8873 static SDValue CombineBaseUpdate(SDNode *N,
8874                                  TargetLowering::DAGCombinerInfo &DCI) {
8875   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8876     return SDValue();
8877
8878   SelectionDAG &DAG = DCI.DAG;
8879   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8880                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8881   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8882   SDValue Addr = N->getOperand(AddrOpIdx);
8883
8884   // Search for a use of the address operand that is an increment.
8885   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8886          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8887     SDNode *User = *UI;
8888     if (User->getOpcode() != ISD::ADD ||
8889         UI.getUse().getResNo() != Addr.getResNo())
8890       continue;
8891
8892     // Check that the add is independent of the load/store.  Otherwise, folding
8893     // it would create a cycle.
8894     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8895       continue;
8896
8897     // Find the new opcode for the updating load/store.
8898     bool isLoad = true;
8899     bool isLaneOp = false;
8900     unsigned NewOpc = 0;
8901     unsigned NumVecs = 0;
8902     if (isIntrinsic) {
8903       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8904       switch (IntNo) {
8905       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8906       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8907         NumVecs = 1; break;
8908       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8909         NumVecs = 2; break;
8910       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8911         NumVecs = 3; break;
8912       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8913         NumVecs = 4; break;
8914       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8915         NumVecs = 2; isLaneOp = true; break;
8916       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8917         NumVecs = 3; isLaneOp = true; break;
8918       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8919         NumVecs = 4; isLaneOp = true; break;
8920       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8921         NumVecs = 1; isLoad = false; break;
8922       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8923         NumVecs = 2; isLoad = false; break;
8924       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8925         NumVecs = 3; isLoad = false; break;
8926       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8927         NumVecs = 4; isLoad = false; break;
8928       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8929         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8930       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8931         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8932       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8933         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8934       }
8935     } else {
8936       isLaneOp = true;
8937       switch (N->getOpcode()) {
8938       default: llvm_unreachable("unexpected opcode for Neon base update");
8939       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8940       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8941       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8942       }
8943     }
8944
8945     // Find the size of memory referenced by the load/store.
8946     EVT VecTy;
8947     if (isLoad)
8948       VecTy = N->getValueType(0);
8949     else
8950       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8951     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8952     if (isLaneOp)
8953       NumBytes /= VecTy.getVectorNumElements();
8954
8955     // If the increment is a constant, it must match the memory ref size.
8956     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8957     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8958       uint64_t IncVal = CInc->getZExtValue();
8959       if (IncVal != NumBytes)
8960         continue;
8961     } else if (NumBytes >= 3 * 16) {
8962       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8963       // separate instructions that make it harder to use a non-constant update.
8964       continue;
8965     }
8966
8967     // Create the new updating load/store node.
8968     EVT Tys[6];
8969     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8970     unsigned n;
8971     for (n = 0; n < NumResultVecs; ++n)
8972       Tys[n] = VecTy;
8973     Tys[n++] = MVT::i32;
8974     Tys[n] = MVT::Other;
8975     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8976     SmallVector<SDValue, 8> Ops;
8977     Ops.push_back(N->getOperand(0)); // incoming chain
8978     Ops.push_back(N->getOperand(AddrOpIdx));
8979     Ops.push_back(Inc);
8980     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8981       Ops.push_back(N->getOperand(i));
8982     }
8983     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8984     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8985                                            Ops, MemInt->getMemoryVT(),
8986                                            MemInt->getMemOperand());
8987
8988     // Update the uses.
8989     std::vector<SDValue> NewResults;
8990     for (unsigned i = 0; i < NumResultVecs; ++i) {
8991       NewResults.push_back(SDValue(UpdN.getNode(), i));
8992     }
8993     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8994     DCI.CombineTo(N, NewResults);
8995     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8996
8997     break;
8998   }
8999   return SDValue();
9000 }
9001
9002 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9003 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9004 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9005 /// return true.
9006 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9007   SelectionDAG &DAG = DCI.DAG;
9008   EVT VT = N->getValueType(0);
9009   // vldN-dup instructions only support 64-bit vectors for N > 1.
9010   if (!VT.is64BitVector())
9011     return false;
9012
9013   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9014   SDNode *VLD = N->getOperand(0).getNode();
9015   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9016     return false;
9017   unsigned NumVecs = 0;
9018   unsigned NewOpc = 0;
9019   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9020   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9021     NumVecs = 2;
9022     NewOpc = ARMISD::VLD2DUP;
9023   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9024     NumVecs = 3;
9025     NewOpc = ARMISD::VLD3DUP;
9026   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9027     NumVecs = 4;
9028     NewOpc = ARMISD::VLD4DUP;
9029   } else {
9030     return false;
9031   }
9032
9033   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9034   // numbers match the load.
9035   unsigned VLDLaneNo =
9036     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9037   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9038        UI != UE; ++UI) {
9039     // Ignore uses of the chain result.
9040     if (UI.getUse().getResNo() == NumVecs)
9041       continue;
9042     SDNode *User = *UI;
9043     if (User->getOpcode() != ARMISD::VDUPLANE ||
9044         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9045       return false;
9046   }
9047
9048   // Create the vldN-dup node.
9049   EVT Tys[5];
9050   unsigned n;
9051   for (n = 0; n < NumVecs; ++n)
9052     Tys[n] = VT;
9053   Tys[n] = MVT::Other;
9054   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9055   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9056   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9057   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9058                                            Ops, VLDMemInt->getMemoryVT(),
9059                                            VLDMemInt->getMemOperand());
9060
9061   // Update the uses.
9062   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9063        UI != UE; ++UI) {
9064     unsigned ResNo = UI.getUse().getResNo();
9065     // Ignore uses of the chain result.
9066     if (ResNo == NumVecs)
9067       continue;
9068     SDNode *User = *UI;
9069     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9070   }
9071
9072   // Now the vldN-lane intrinsic is dead except for its chain result.
9073   // Update uses of the chain.
9074   std::vector<SDValue> VLDDupResults;
9075   for (unsigned n = 0; n < NumVecs; ++n)
9076     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9077   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9078   DCI.CombineTo(VLD, VLDDupResults);
9079
9080   return true;
9081 }
9082
9083 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9084 /// ARMISD::VDUPLANE.
9085 static SDValue PerformVDUPLANECombine(SDNode *N,
9086                                       TargetLowering::DAGCombinerInfo &DCI) {
9087   SDValue Op = N->getOperand(0);
9088
9089   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9090   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9091   if (CombineVLDDUP(N, DCI))
9092     return SDValue(N, 0);
9093
9094   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9095   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9096   while (Op.getOpcode() == ISD::BITCAST)
9097     Op = Op.getOperand(0);
9098   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9099     return SDValue();
9100
9101   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9102   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9103   // The canonical VMOV for a zero vector uses a 32-bit element size.
9104   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9105   unsigned EltBits;
9106   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9107     EltSize = 8;
9108   EVT VT = N->getValueType(0);
9109   if (EltSize > VT.getVectorElementType().getSizeInBits())
9110     return SDValue();
9111
9112   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9113 }
9114
9115 /// PerformSTORECombine - Target-specific dag combine xforms for
9116 /// ISD::STORE.
9117 static SDValue PerformSTORECombine(SDNode *N,
9118                                    TargetLowering::DAGCombinerInfo &DCI) {
9119   StoreSDNode *St = cast<StoreSDNode>(N);
9120   if (St->isVolatile())
9121     return SDValue();
9122
9123   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9124   // pack all of the elements in one place.  Next, store to memory in fewer
9125   // chunks.
9126   SDValue StVal = St->getValue();
9127   EVT VT = StVal.getValueType();
9128   if (St->isTruncatingStore() && VT.isVector()) {
9129     SelectionDAG &DAG = DCI.DAG;
9130     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9131     EVT StVT = St->getMemoryVT();
9132     unsigned NumElems = VT.getVectorNumElements();
9133     assert(StVT != VT && "Cannot truncate to the same type");
9134     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9135     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9136
9137     // From, To sizes and ElemCount must be pow of two
9138     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9139
9140     // We are going to use the original vector elt for storing.
9141     // Accumulated smaller vector elements must be a multiple of the store size.
9142     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9143
9144     unsigned SizeRatio  = FromEltSz / ToEltSz;
9145     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9146
9147     // Create a type on which we perform the shuffle.
9148     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9149                                      NumElems*SizeRatio);
9150     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9151
9152     SDLoc DL(St);
9153     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9154     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9155     for (unsigned i = 0; i < NumElems; ++i)
9156       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9157
9158     // Can't shuffle using an illegal type.
9159     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9160
9161     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9162                                 DAG.getUNDEF(WideVec.getValueType()),
9163                                 ShuffleVec.data());
9164     // At this point all of the data is stored at the bottom of the
9165     // register. We now need to save it to mem.
9166
9167     // Find the largest store unit
9168     MVT StoreType = MVT::i8;
9169     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9170          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9171       MVT Tp = (MVT::SimpleValueType)tp;
9172       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9173         StoreType = Tp;
9174     }
9175     // Didn't find a legal store type.
9176     if (!TLI.isTypeLegal(StoreType))
9177       return SDValue();
9178
9179     // Bitcast the original vector into a vector of store-size units
9180     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9181             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9182     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9183     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9184     SmallVector<SDValue, 8> Chains;
9185     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9186                                         TLI.getPointerTy());
9187     SDValue BasePtr = St->getBasePtr();
9188
9189     // Perform one or more big stores into memory.
9190     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9191     for (unsigned I = 0; I < E; I++) {
9192       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9193                                    StoreType, ShuffWide,
9194                                    DAG.getIntPtrConstant(I));
9195       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9196                                 St->getPointerInfo(), St->isVolatile(),
9197                                 St->isNonTemporal(), St->getAlignment());
9198       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9199                             Increment);
9200       Chains.push_back(Ch);
9201     }
9202     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9203   }
9204
9205   if (!ISD::isNormalStore(St))
9206     return SDValue();
9207
9208   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9209   // ARM stores of arguments in the same cache line.
9210   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9211       StVal.getNode()->hasOneUse()) {
9212     SelectionDAG  &DAG = DCI.DAG;
9213     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9214     SDLoc DL(St);
9215     SDValue BasePtr = St->getBasePtr();
9216     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9217                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9218                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9219                                   St->isNonTemporal(), St->getAlignment());
9220
9221     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9222                                     DAG.getConstant(4, MVT::i32));
9223     return DAG.getStore(NewST1.getValue(0), DL,
9224                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9225                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9226                         St->isNonTemporal(),
9227                         std::min(4U, St->getAlignment() / 2));
9228   }
9229
9230   if (StVal.getValueType() == MVT::i64 &&
9231       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9232
9233     // Bitcast an i64 store extracted from a vector to f64.
9234     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9235     SelectionDAG &DAG = DCI.DAG;
9236     SDLoc dl(StVal);
9237     SDValue IntVec = StVal.getOperand(0);
9238     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9239                                    IntVec.getValueType().getVectorNumElements());
9240     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9241     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9242                                  Vec, StVal.getOperand(1));
9243     dl = SDLoc(N);
9244     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9245     // Make the DAGCombiner fold the bitcasts.
9246     DCI.AddToWorklist(Vec.getNode());
9247     DCI.AddToWorklist(ExtElt.getNode());
9248     DCI.AddToWorklist(V.getNode());
9249     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9250                         St->getPointerInfo(), St->isVolatile(),
9251                         St->isNonTemporal(), St->getAlignment(),
9252                         St->getAAInfo());
9253   }
9254
9255   return SDValue();
9256 }
9257
9258 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9259 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9260 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9261 {
9262   integerPart cN;
9263   integerPart c0 = 0;
9264   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9265        I != E; I++) {
9266     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9267     if (!C)
9268       return false;
9269
9270     bool isExact;
9271     APFloat APF = C->getValueAPF();
9272     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9273         != APFloat::opOK || !isExact)
9274       return false;
9275
9276     c0 = (I == 0) ? cN : c0;
9277     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9278       return false;
9279   }
9280   C = c0;
9281   return true;
9282 }
9283
9284 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9285 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9286 /// when the VMUL has a constant operand that is a power of 2.
9287 ///
9288 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9289 ///  vmul.f32        d16, d17, d16
9290 ///  vcvt.s32.f32    d16, d16
9291 /// becomes:
9292 ///  vcvt.s32.f32    d16, d16, #3
9293 static SDValue PerformVCVTCombine(SDNode *N,
9294                                   TargetLowering::DAGCombinerInfo &DCI,
9295                                   const ARMSubtarget *Subtarget) {
9296   SelectionDAG &DAG = DCI.DAG;
9297   SDValue Op = N->getOperand(0);
9298
9299   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9300       Op.getOpcode() != ISD::FMUL)
9301     return SDValue();
9302
9303   uint64_t C;
9304   SDValue N0 = Op->getOperand(0);
9305   SDValue ConstVec = Op->getOperand(1);
9306   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9307
9308   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9309       !isConstVecPow2(ConstVec, isSigned, C))
9310     return SDValue();
9311
9312   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9313   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9314   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9315     // These instructions only exist converting from f32 to i32. We can handle
9316     // smaller integers by generating an extra truncate, but larger ones would
9317     // be lossy.
9318     return SDValue();
9319   }
9320
9321   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9322     Intrinsic::arm_neon_vcvtfp2fxu;
9323   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9324   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9325                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9326                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9327                                  DAG.getConstant(Log2_64(C), MVT::i32));
9328
9329   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9330     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9331
9332   return FixConv;
9333 }
9334
9335 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9336 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9337 /// when the VDIV has a constant operand that is a power of 2.
9338 ///
9339 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9340 ///  vcvt.f32.s32    d16, d16
9341 ///  vdiv.f32        d16, d17, d16
9342 /// becomes:
9343 ///  vcvt.f32.s32    d16, d16, #3
9344 static SDValue PerformVDIVCombine(SDNode *N,
9345                                   TargetLowering::DAGCombinerInfo &DCI,
9346                                   const ARMSubtarget *Subtarget) {
9347   SelectionDAG &DAG = DCI.DAG;
9348   SDValue Op = N->getOperand(0);
9349   unsigned OpOpcode = Op.getNode()->getOpcode();
9350
9351   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9352       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9353     return SDValue();
9354
9355   uint64_t C;
9356   SDValue ConstVec = N->getOperand(1);
9357   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9358
9359   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9360       !isConstVecPow2(ConstVec, isSigned, C))
9361     return SDValue();
9362
9363   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9364   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9365   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9366     // These instructions only exist converting from i32 to f32. We can handle
9367     // smaller integers by generating an extra extend, but larger ones would
9368     // be lossy.
9369     return SDValue();
9370   }
9371
9372   SDValue ConvInput = Op.getOperand(0);
9373   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9374   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9375     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9376                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9377                             ConvInput);
9378
9379   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9380     Intrinsic::arm_neon_vcvtfxu2fp;
9381   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9382                      Op.getValueType(),
9383                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9384                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9385 }
9386
9387 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9388 /// operand of a vector shift operation, where all the elements of the
9389 /// build_vector must have the same constant integer value.
9390 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9391   // Ignore bit_converts.
9392   while (Op.getOpcode() == ISD::BITCAST)
9393     Op = Op.getOperand(0);
9394   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9395   APInt SplatBits, SplatUndef;
9396   unsigned SplatBitSize;
9397   bool HasAnyUndefs;
9398   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9399                                       HasAnyUndefs, ElementBits) ||
9400       SplatBitSize > ElementBits)
9401     return false;
9402   Cnt = SplatBits.getSExtValue();
9403   return true;
9404 }
9405
9406 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9407 /// operand of a vector shift left operation.  That value must be in the range:
9408 ///   0 <= Value < ElementBits for a left shift; or
9409 ///   0 <= Value <= ElementBits for a long left shift.
9410 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9411   assert(VT.isVector() && "vector shift count is not a vector type");
9412   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9413   if (! getVShiftImm(Op, ElementBits, Cnt))
9414     return false;
9415   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9416 }
9417
9418 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9419 /// operand of a vector shift right operation.  For a shift opcode, the value
9420 /// is positive, but for an intrinsic the value count must be negative. The
9421 /// absolute value must be in the range:
9422 ///   1 <= |Value| <= ElementBits for a right shift; or
9423 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9424 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9425                          int64_t &Cnt) {
9426   assert(VT.isVector() && "vector shift count is not a vector type");
9427   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9428   if (! getVShiftImm(Op, ElementBits, Cnt))
9429     return false;
9430   if (isIntrinsic)
9431     Cnt = -Cnt;
9432   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9433 }
9434
9435 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9436 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9437   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9438   switch (IntNo) {
9439   default:
9440     // Don't do anything for most intrinsics.
9441     break;
9442
9443   // Vector shifts: check for immediate versions and lower them.
9444   // Note: This is done during DAG combining instead of DAG legalizing because
9445   // the build_vectors for 64-bit vector element shift counts are generally
9446   // not legal, and it is hard to see their values after they get legalized to
9447   // loads from a constant pool.
9448   case Intrinsic::arm_neon_vshifts:
9449   case Intrinsic::arm_neon_vshiftu:
9450   case Intrinsic::arm_neon_vrshifts:
9451   case Intrinsic::arm_neon_vrshiftu:
9452   case Intrinsic::arm_neon_vrshiftn:
9453   case Intrinsic::arm_neon_vqshifts:
9454   case Intrinsic::arm_neon_vqshiftu:
9455   case Intrinsic::arm_neon_vqshiftsu:
9456   case Intrinsic::arm_neon_vqshiftns:
9457   case Intrinsic::arm_neon_vqshiftnu:
9458   case Intrinsic::arm_neon_vqshiftnsu:
9459   case Intrinsic::arm_neon_vqrshiftns:
9460   case Intrinsic::arm_neon_vqrshiftnu:
9461   case Intrinsic::arm_neon_vqrshiftnsu: {
9462     EVT VT = N->getOperand(1).getValueType();
9463     int64_t Cnt;
9464     unsigned VShiftOpc = 0;
9465
9466     switch (IntNo) {
9467     case Intrinsic::arm_neon_vshifts:
9468     case Intrinsic::arm_neon_vshiftu:
9469       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9470         VShiftOpc = ARMISD::VSHL;
9471         break;
9472       }
9473       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9474         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9475                      ARMISD::VSHRs : ARMISD::VSHRu);
9476         break;
9477       }
9478       return SDValue();
9479
9480     case Intrinsic::arm_neon_vrshifts:
9481     case Intrinsic::arm_neon_vrshiftu:
9482       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9483         break;
9484       return SDValue();
9485
9486     case Intrinsic::arm_neon_vqshifts:
9487     case Intrinsic::arm_neon_vqshiftu:
9488       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9489         break;
9490       return SDValue();
9491
9492     case Intrinsic::arm_neon_vqshiftsu:
9493       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9494         break;
9495       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9496
9497     case Intrinsic::arm_neon_vrshiftn:
9498     case Intrinsic::arm_neon_vqshiftns:
9499     case Intrinsic::arm_neon_vqshiftnu:
9500     case Intrinsic::arm_neon_vqshiftnsu:
9501     case Intrinsic::arm_neon_vqrshiftns:
9502     case Intrinsic::arm_neon_vqrshiftnu:
9503     case Intrinsic::arm_neon_vqrshiftnsu:
9504       // Narrowing shifts require an immediate right shift.
9505       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9506         break;
9507       llvm_unreachable("invalid shift count for narrowing vector shift "
9508                        "intrinsic");
9509
9510     default:
9511       llvm_unreachable("unhandled vector shift");
9512     }
9513
9514     switch (IntNo) {
9515     case Intrinsic::arm_neon_vshifts:
9516     case Intrinsic::arm_neon_vshiftu:
9517       // Opcode already set above.
9518       break;
9519     case Intrinsic::arm_neon_vrshifts:
9520       VShiftOpc = ARMISD::VRSHRs; break;
9521     case Intrinsic::arm_neon_vrshiftu:
9522       VShiftOpc = ARMISD::VRSHRu; break;
9523     case Intrinsic::arm_neon_vrshiftn:
9524       VShiftOpc = ARMISD::VRSHRN; break;
9525     case Intrinsic::arm_neon_vqshifts:
9526       VShiftOpc = ARMISD::VQSHLs; break;
9527     case Intrinsic::arm_neon_vqshiftu:
9528       VShiftOpc = ARMISD::VQSHLu; break;
9529     case Intrinsic::arm_neon_vqshiftsu:
9530       VShiftOpc = ARMISD::VQSHLsu; break;
9531     case Intrinsic::arm_neon_vqshiftns:
9532       VShiftOpc = ARMISD::VQSHRNs; break;
9533     case Intrinsic::arm_neon_vqshiftnu:
9534       VShiftOpc = ARMISD::VQSHRNu; break;
9535     case Intrinsic::arm_neon_vqshiftnsu:
9536       VShiftOpc = ARMISD::VQSHRNsu; break;
9537     case Intrinsic::arm_neon_vqrshiftns:
9538       VShiftOpc = ARMISD::VQRSHRNs; break;
9539     case Intrinsic::arm_neon_vqrshiftnu:
9540       VShiftOpc = ARMISD::VQRSHRNu; break;
9541     case Intrinsic::arm_neon_vqrshiftnsu:
9542       VShiftOpc = ARMISD::VQRSHRNsu; break;
9543     }
9544
9545     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9546                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9547   }
9548
9549   case Intrinsic::arm_neon_vshiftins: {
9550     EVT VT = N->getOperand(1).getValueType();
9551     int64_t Cnt;
9552     unsigned VShiftOpc = 0;
9553
9554     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9555       VShiftOpc = ARMISD::VSLI;
9556     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9557       VShiftOpc = ARMISD::VSRI;
9558     else {
9559       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9560     }
9561
9562     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9563                        N->getOperand(1), N->getOperand(2),
9564                        DAG.getConstant(Cnt, MVT::i32));
9565   }
9566
9567   case Intrinsic::arm_neon_vqrshifts:
9568   case Intrinsic::arm_neon_vqrshiftu:
9569     // No immediate versions of these to check for.
9570     break;
9571   }
9572
9573   return SDValue();
9574 }
9575
9576 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9577 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9578 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9579 /// vector element shift counts are generally not legal, and it is hard to see
9580 /// their values after they get legalized to loads from a constant pool.
9581 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9582                                    const ARMSubtarget *ST) {
9583   EVT VT = N->getValueType(0);
9584   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9585     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9586     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9587     SDValue N1 = N->getOperand(1);
9588     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9589       SDValue N0 = N->getOperand(0);
9590       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9591           DAG.MaskedValueIsZero(N0.getOperand(0),
9592                                 APInt::getHighBitsSet(32, 16)))
9593         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9594     }
9595   }
9596
9597   // Nothing to be done for scalar shifts.
9598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9599   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9600     return SDValue();
9601
9602   assert(ST->hasNEON() && "unexpected vector shift");
9603   int64_t Cnt;
9604
9605   switch (N->getOpcode()) {
9606   default: llvm_unreachable("unexpected shift opcode");
9607
9608   case ISD::SHL:
9609     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9610       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9611                          DAG.getConstant(Cnt, MVT::i32));
9612     break;
9613
9614   case ISD::SRA:
9615   case ISD::SRL:
9616     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9617       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9618                             ARMISD::VSHRs : ARMISD::VSHRu);
9619       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9620                          DAG.getConstant(Cnt, MVT::i32));
9621     }
9622   }
9623   return SDValue();
9624 }
9625
9626 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9627 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9628 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9629                                     const ARMSubtarget *ST) {
9630   SDValue N0 = N->getOperand(0);
9631
9632   // Check for sign- and zero-extensions of vector extract operations of 8-
9633   // and 16-bit vector elements.  NEON supports these directly.  They are
9634   // handled during DAG combining because type legalization will promote them
9635   // to 32-bit types and it is messy to recognize the operations after that.
9636   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9637     SDValue Vec = N0.getOperand(0);
9638     SDValue Lane = N0.getOperand(1);
9639     EVT VT = N->getValueType(0);
9640     EVT EltVT = N0.getValueType();
9641     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9642
9643     if (VT == MVT::i32 &&
9644         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9645         TLI.isTypeLegal(Vec.getValueType()) &&
9646         isa<ConstantSDNode>(Lane)) {
9647
9648       unsigned Opc = 0;
9649       switch (N->getOpcode()) {
9650       default: llvm_unreachable("unexpected opcode");
9651       case ISD::SIGN_EXTEND:
9652         Opc = ARMISD::VGETLANEs;
9653         break;
9654       case ISD::ZERO_EXTEND:
9655       case ISD::ANY_EXTEND:
9656         Opc = ARMISD::VGETLANEu;
9657         break;
9658       }
9659       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9660     }
9661   }
9662
9663   return SDValue();
9664 }
9665
9666 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9667 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9668 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9669                                        const ARMSubtarget *ST) {
9670   // If the target supports NEON, try to use vmax/vmin instructions for f32
9671   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9672   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9673   // a NaN; only do the transformation when it matches that behavior.
9674
9675   // For now only do this when using NEON for FP operations; if using VFP, it
9676   // is not obvious that the benefit outweighs the cost of switching to the
9677   // NEON pipeline.
9678   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9679       N->getValueType(0) != MVT::f32)
9680     return SDValue();
9681
9682   SDValue CondLHS = N->getOperand(0);
9683   SDValue CondRHS = N->getOperand(1);
9684   SDValue LHS = N->getOperand(2);
9685   SDValue RHS = N->getOperand(3);
9686   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9687
9688   unsigned Opcode = 0;
9689   bool IsReversed;
9690   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9691     IsReversed = false; // x CC y ? x : y
9692   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9693     IsReversed = true ; // x CC y ? y : x
9694   } else {
9695     return SDValue();
9696   }
9697
9698   bool IsUnordered;
9699   switch (CC) {
9700   default: break;
9701   case ISD::SETOLT:
9702   case ISD::SETOLE:
9703   case ISD::SETLT:
9704   case ISD::SETLE:
9705   case ISD::SETULT:
9706   case ISD::SETULE:
9707     // If LHS is NaN, an ordered comparison will be false and the result will
9708     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9709     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9710     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9711     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9712       break;
9713     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9714     // will return -0, so vmin can only be used for unsafe math or if one of
9715     // the operands is known to be nonzero.
9716     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9717         !DAG.getTarget().Options.UnsafeFPMath &&
9718         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9719       break;
9720     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9721     break;
9722
9723   case ISD::SETOGT:
9724   case ISD::SETOGE:
9725   case ISD::SETGT:
9726   case ISD::SETGE:
9727   case ISD::SETUGT:
9728   case ISD::SETUGE:
9729     // If LHS is NaN, an ordered comparison will be false and the result will
9730     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9731     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9732     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9733     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9734       break;
9735     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9736     // will return +0, so vmax can only be used for unsafe math or if one of
9737     // the operands is known to be nonzero.
9738     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9739         !DAG.getTarget().Options.UnsafeFPMath &&
9740         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9741       break;
9742     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9743     break;
9744   }
9745
9746   if (!Opcode)
9747     return SDValue();
9748   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9749 }
9750
9751 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9752 SDValue
9753 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9754   SDValue Cmp = N->getOperand(4);
9755   if (Cmp.getOpcode() != ARMISD::CMPZ)
9756     // Only looking at EQ and NE cases.
9757     return SDValue();
9758
9759   EVT VT = N->getValueType(0);
9760   SDLoc dl(N);
9761   SDValue LHS = Cmp.getOperand(0);
9762   SDValue RHS = Cmp.getOperand(1);
9763   SDValue FalseVal = N->getOperand(0);
9764   SDValue TrueVal = N->getOperand(1);
9765   SDValue ARMcc = N->getOperand(2);
9766   ARMCC::CondCodes CC =
9767     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9768
9769   // Simplify
9770   //   mov     r1, r0
9771   //   cmp     r1, x
9772   //   mov     r0, y
9773   //   moveq   r0, x
9774   // to
9775   //   cmp     r0, x
9776   //   movne   r0, y
9777   //
9778   //   mov     r1, r0
9779   //   cmp     r1, x
9780   //   mov     r0, x
9781   //   movne   r0, y
9782   // to
9783   //   cmp     r0, x
9784   //   movne   r0, y
9785   /// FIXME: Turn this into a target neutral optimization?
9786   SDValue Res;
9787   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9788     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9789                       N->getOperand(3), Cmp);
9790   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9791     SDValue ARMcc;
9792     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9793     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9794                       N->getOperand(3), NewCmp);
9795   }
9796
9797   if (Res.getNode()) {
9798     APInt KnownZero, KnownOne;
9799     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9800     // Capture demanded bits information that would be otherwise lost.
9801     if (KnownZero == 0xfffffffe)
9802       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9803                         DAG.getValueType(MVT::i1));
9804     else if (KnownZero == 0xffffff00)
9805       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9806                         DAG.getValueType(MVT::i8));
9807     else if (KnownZero == 0xffff0000)
9808       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9809                         DAG.getValueType(MVT::i16));
9810   }
9811
9812   return Res;
9813 }
9814
9815 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9816                                              DAGCombinerInfo &DCI) const {
9817   switch (N->getOpcode()) {
9818   default: break;
9819   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9820   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9821   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9822   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9823   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9824   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9825   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9826   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9827   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9828   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9829   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9830   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9831   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9832   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9833   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9834   case ISD::FP_TO_SINT:
9835   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9836   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9837   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9838   case ISD::SHL:
9839   case ISD::SRA:
9840   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9841   case ISD::SIGN_EXTEND:
9842   case ISD::ZERO_EXTEND:
9843   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9844   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9845   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9846   case ARMISD::VLD2DUP:
9847   case ARMISD::VLD3DUP:
9848   case ARMISD::VLD4DUP:
9849     return CombineBaseUpdate(N, DCI);
9850   case ARMISD::BUILD_VECTOR:
9851     return PerformARMBUILD_VECTORCombine(N, DCI);
9852   case ISD::INTRINSIC_VOID:
9853   case ISD::INTRINSIC_W_CHAIN:
9854     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9855     case Intrinsic::arm_neon_vld1:
9856     case Intrinsic::arm_neon_vld2:
9857     case Intrinsic::arm_neon_vld3:
9858     case Intrinsic::arm_neon_vld4:
9859     case Intrinsic::arm_neon_vld2lane:
9860     case Intrinsic::arm_neon_vld3lane:
9861     case Intrinsic::arm_neon_vld4lane:
9862     case Intrinsic::arm_neon_vst1:
9863     case Intrinsic::arm_neon_vst2:
9864     case Intrinsic::arm_neon_vst3:
9865     case Intrinsic::arm_neon_vst4:
9866     case Intrinsic::arm_neon_vst2lane:
9867     case Intrinsic::arm_neon_vst3lane:
9868     case Intrinsic::arm_neon_vst4lane:
9869       return CombineBaseUpdate(N, DCI);
9870     default: break;
9871     }
9872     break;
9873   }
9874   return SDValue();
9875 }
9876
9877 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9878                                                           EVT VT) const {
9879   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9880 }
9881
9882 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9883                                                        unsigned,
9884                                                        unsigned,
9885                                                        bool *Fast) const {
9886   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9887   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9888
9889   switch (VT.getSimpleVT().SimpleTy) {
9890   default:
9891     return false;
9892   case MVT::i8:
9893   case MVT::i16:
9894   case MVT::i32: {
9895     // Unaligned access can use (for example) LRDB, LRDH, LDR
9896     if (AllowsUnaligned) {
9897       if (Fast)
9898         *Fast = Subtarget->hasV7Ops();
9899       return true;
9900     }
9901     return false;
9902   }
9903   case MVT::f64:
9904   case MVT::v2f64: {
9905     // For any little-endian targets with neon, we can support unaligned ld/st
9906     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9907     // A big-endian target may also explicitly support unaligned accesses
9908     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9909       if (Fast)
9910         *Fast = true;
9911       return true;
9912     }
9913     return false;
9914   }
9915   }
9916 }
9917
9918 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9919                        unsigned AlignCheck) {
9920   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9921           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9922 }
9923
9924 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9925                                            unsigned DstAlign, unsigned SrcAlign,
9926                                            bool IsMemset, bool ZeroMemset,
9927                                            bool MemcpyStrSrc,
9928                                            MachineFunction &MF) const {
9929   const Function *F = MF.getFunction();
9930
9931   // See if we can use NEON instructions for this...
9932   if ((!IsMemset || ZeroMemset) &&
9933       Subtarget->hasNEON() &&
9934       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9935                                        Attribute::NoImplicitFloat)) {
9936     bool Fast;
9937     if (Size >= 16 &&
9938         (memOpAlign(SrcAlign, DstAlign, 16) ||
9939          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9940       return MVT::v2f64;
9941     } else if (Size >= 8 &&
9942                (memOpAlign(SrcAlign, DstAlign, 8) ||
9943                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9944                  Fast))) {
9945       return MVT::f64;
9946     }
9947   }
9948
9949   // Lowering to i32/i16 if the size permits.
9950   if (Size >= 4)
9951     return MVT::i32;
9952   else if (Size >= 2)
9953     return MVT::i16;
9954
9955   // Let the target-independent logic figure it out.
9956   return MVT::Other;
9957 }
9958
9959 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9960   if (Val.getOpcode() != ISD::LOAD)
9961     return false;
9962
9963   EVT VT1 = Val.getValueType();
9964   if (!VT1.isSimple() || !VT1.isInteger() ||
9965       !VT2.isSimple() || !VT2.isInteger())
9966     return false;
9967
9968   switch (VT1.getSimpleVT().SimpleTy) {
9969   default: break;
9970   case MVT::i1:
9971   case MVT::i8:
9972   case MVT::i16:
9973     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9974     return true;
9975   }
9976
9977   return false;
9978 }
9979
9980 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9981   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9982     return false;
9983
9984   if (!isTypeLegal(EVT::getEVT(Ty1)))
9985     return false;
9986
9987   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9988
9989   // Assuming the caller doesn't have a zeroext or signext return parameter,
9990   // truncation all the way down to i1 is valid.
9991   return true;
9992 }
9993
9994
9995 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9996   if (V < 0)
9997     return false;
9998
9999   unsigned Scale = 1;
10000   switch (VT.getSimpleVT().SimpleTy) {
10001   default: return false;
10002   case MVT::i1:
10003   case MVT::i8:
10004     // Scale == 1;
10005     break;
10006   case MVT::i16:
10007     // Scale == 2;
10008     Scale = 2;
10009     break;
10010   case MVT::i32:
10011     // Scale == 4;
10012     Scale = 4;
10013     break;
10014   }
10015
10016   if ((V & (Scale - 1)) != 0)
10017     return false;
10018   V /= Scale;
10019   return V == (V & ((1LL << 5) - 1));
10020 }
10021
10022 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10023                                       const ARMSubtarget *Subtarget) {
10024   bool isNeg = false;
10025   if (V < 0) {
10026     isNeg = true;
10027     V = - V;
10028   }
10029
10030   switch (VT.getSimpleVT().SimpleTy) {
10031   default: return false;
10032   case MVT::i1:
10033   case MVT::i8:
10034   case MVT::i16:
10035   case MVT::i32:
10036     // + imm12 or - imm8
10037     if (isNeg)
10038       return V == (V & ((1LL << 8) - 1));
10039     return V == (V & ((1LL << 12) - 1));
10040   case MVT::f32:
10041   case MVT::f64:
10042     // Same as ARM mode. FIXME: NEON?
10043     if (!Subtarget->hasVFP2())
10044       return false;
10045     if ((V & 3) != 0)
10046       return false;
10047     V >>= 2;
10048     return V == (V & ((1LL << 8) - 1));
10049   }
10050 }
10051
10052 /// isLegalAddressImmediate - Return true if the integer value can be used
10053 /// as the offset of the target addressing mode for load / store of the
10054 /// given type.
10055 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10056                                     const ARMSubtarget *Subtarget) {
10057   if (V == 0)
10058     return true;
10059
10060   if (!VT.isSimple())
10061     return false;
10062
10063   if (Subtarget->isThumb1Only())
10064     return isLegalT1AddressImmediate(V, VT);
10065   else if (Subtarget->isThumb2())
10066     return isLegalT2AddressImmediate(V, VT, Subtarget);
10067
10068   // ARM mode.
10069   if (V < 0)
10070     V = - V;
10071   switch (VT.getSimpleVT().SimpleTy) {
10072   default: return false;
10073   case MVT::i1:
10074   case MVT::i8:
10075   case MVT::i32:
10076     // +- imm12
10077     return V == (V & ((1LL << 12) - 1));
10078   case MVT::i16:
10079     // +- imm8
10080     return V == (V & ((1LL << 8) - 1));
10081   case MVT::f32:
10082   case MVT::f64:
10083     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10084       return false;
10085     if ((V & 3) != 0)
10086       return false;
10087     V >>= 2;
10088     return V == (V & ((1LL << 8) - 1));
10089   }
10090 }
10091
10092 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10093                                                       EVT VT) const {
10094   int Scale = AM.Scale;
10095   if (Scale < 0)
10096     return false;
10097
10098   switch (VT.getSimpleVT().SimpleTy) {
10099   default: return false;
10100   case MVT::i1:
10101   case MVT::i8:
10102   case MVT::i16:
10103   case MVT::i32:
10104     if (Scale == 1)
10105       return true;
10106     // r + r << imm
10107     Scale = Scale & ~1;
10108     return Scale == 2 || Scale == 4 || Scale == 8;
10109   case MVT::i64:
10110     // r + r
10111     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10112       return true;
10113     return false;
10114   case MVT::isVoid:
10115     // Note, we allow "void" uses (basically, uses that aren't loads or
10116     // stores), because arm allows folding a scale into many arithmetic
10117     // operations.  This should be made more precise and revisited later.
10118
10119     // Allow r << imm, but the imm has to be a multiple of two.
10120     if (Scale & 1) return false;
10121     return isPowerOf2_32(Scale);
10122   }
10123 }
10124
10125 /// isLegalAddressingMode - Return true if the addressing mode represented
10126 /// by AM is legal for this target, for a load/store of the specified type.
10127 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10128                                               Type *Ty) const {
10129   EVT VT = getValueType(Ty, true);
10130   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10131     return false;
10132
10133   // Can never fold addr of global into load/store.
10134   if (AM.BaseGV)
10135     return false;
10136
10137   switch (AM.Scale) {
10138   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10139     break;
10140   case 1:
10141     if (Subtarget->isThumb1Only())
10142       return false;
10143     // FALL THROUGH.
10144   default:
10145     // ARM doesn't support any R+R*scale+imm addr modes.
10146     if (AM.BaseOffs)
10147       return false;
10148
10149     if (!VT.isSimple())
10150       return false;
10151
10152     if (Subtarget->isThumb2())
10153       return isLegalT2ScaledAddressingMode(AM, VT);
10154
10155     int Scale = AM.Scale;
10156     switch (VT.getSimpleVT().SimpleTy) {
10157     default: return false;
10158     case MVT::i1:
10159     case MVT::i8:
10160     case MVT::i32:
10161       if (Scale < 0) Scale = -Scale;
10162       if (Scale == 1)
10163         return true;
10164       // r + r << imm
10165       return isPowerOf2_32(Scale & ~1);
10166     case MVT::i16:
10167     case MVT::i64:
10168       // r + r
10169       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10170         return true;
10171       return false;
10172
10173     case MVT::isVoid:
10174       // Note, we allow "void" uses (basically, uses that aren't loads or
10175       // stores), because arm allows folding a scale into many arithmetic
10176       // operations.  This should be made more precise and revisited later.
10177
10178       // Allow r << imm, but the imm has to be a multiple of two.
10179       if (Scale & 1) return false;
10180       return isPowerOf2_32(Scale);
10181     }
10182   }
10183   return true;
10184 }
10185
10186 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10187 /// icmp immediate, that is the target has icmp instructions which can compare
10188 /// a register against the immediate without having to materialize the
10189 /// immediate into a register.
10190 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10191   // Thumb2 and ARM modes can use cmn for negative immediates.
10192   if (!Subtarget->isThumb())
10193     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10194   if (Subtarget->isThumb2())
10195     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10196   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10197   return Imm >= 0 && Imm <= 255;
10198 }
10199
10200 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10201 /// *or sub* immediate, that is the target has add or sub instructions which can
10202 /// add a register with the immediate without having to materialize the
10203 /// immediate into a register.
10204 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10205   // Same encoding for add/sub, just flip the sign.
10206   int64_t AbsImm = llvm::abs64(Imm);
10207   if (!Subtarget->isThumb())
10208     return ARM_AM::getSOImmVal(AbsImm) != -1;
10209   if (Subtarget->isThumb2())
10210     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10211   // Thumb1 only has 8-bit unsigned immediate.
10212   return AbsImm >= 0 && AbsImm <= 255;
10213 }
10214
10215 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10216                                       bool isSEXTLoad, SDValue &Base,
10217                                       SDValue &Offset, bool &isInc,
10218                                       SelectionDAG &DAG) {
10219   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10220     return false;
10221
10222   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10223     // AddressingMode 3
10224     Base = Ptr->getOperand(0);
10225     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10226       int RHSC = (int)RHS->getZExtValue();
10227       if (RHSC < 0 && RHSC > -256) {
10228         assert(Ptr->getOpcode() == ISD::ADD);
10229         isInc = false;
10230         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10231         return true;
10232       }
10233     }
10234     isInc = (Ptr->getOpcode() == ISD::ADD);
10235     Offset = Ptr->getOperand(1);
10236     return true;
10237   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10238     // AddressingMode 2
10239     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10240       int RHSC = (int)RHS->getZExtValue();
10241       if (RHSC < 0 && RHSC > -0x1000) {
10242         assert(Ptr->getOpcode() == ISD::ADD);
10243         isInc = false;
10244         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10245         Base = Ptr->getOperand(0);
10246         return true;
10247       }
10248     }
10249
10250     if (Ptr->getOpcode() == ISD::ADD) {
10251       isInc = true;
10252       ARM_AM::ShiftOpc ShOpcVal=
10253         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10254       if (ShOpcVal != ARM_AM::no_shift) {
10255         Base = Ptr->getOperand(1);
10256         Offset = Ptr->getOperand(0);
10257       } else {
10258         Base = Ptr->getOperand(0);
10259         Offset = Ptr->getOperand(1);
10260       }
10261       return true;
10262     }
10263
10264     isInc = (Ptr->getOpcode() == ISD::ADD);
10265     Base = Ptr->getOperand(0);
10266     Offset = Ptr->getOperand(1);
10267     return true;
10268   }
10269
10270   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10271   return false;
10272 }
10273
10274 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10275                                      bool isSEXTLoad, SDValue &Base,
10276                                      SDValue &Offset, bool &isInc,
10277                                      SelectionDAG &DAG) {
10278   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10279     return false;
10280
10281   Base = Ptr->getOperand(0);
10282   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10283     int RHSC = (int)RHS->getZExtValue();
10284     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10285       assert(Ptr->getOpcode() == ISD::ADD);
10286       isInc = false;
10287       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10288       return true;
10289     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10290       isInc = Ptr->getOpcode() == ISD::ADD;
10291       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10292       return true;
10293     }
10294   }
10295
10296   return false;
10297 }
10298
10299 /// getPreIndexedAddressParts - returns true by value, base pointer and
10300 /// offset pointer and addressing mode by reference if the node's address
10301 /// can be legally represented as pre-indexed load / store address.
10302 bool
10303 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10304                                              SDValue &Offset,
10305                                              ISD::MemIndexedMode &AM,
10306                                              SelectionDAG &DAG) const {
10307   if (Subtarget->isThumb1Only())
10308     return false;
10309
10310   EVT VT;
10311   SDValue Ptr;
10312   bool isSEXTLoad = false;
10313   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10314     Ptr = LD->getBasePtr();
10315     VT  = LD->getMemoryVT();
10316     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10317   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10318     Ptr = ST->getBasePtr();
10319     VT  = ST->getMemoryVT();
10320   } else
10321     return false;
10322
10323   bool isInc;
10324   bool isLegal = false;
10325   if (Subtarget->isThumb2())
10326     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10327                                        Offset, isInc, DAG);
10328   else
10329     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10330                                         Offset, isInc, DAG);
10331   if (!isLegal)
10332     return false;
10333
10334   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10335   return true;
10336 }
10337
10338 /// getPostIndexedAddressParts - returns true by value, base pointer and
10339 /// offset pointer and addressing mode by reference if this node can be
10340 /// combined with a load / store to form a post-indexed load / store.
10341 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10342                                                    SDValue &Base,
10343                                                    SDValue &Offset,
10344                                                    ISD::MemIndexedMode &AM,
10345                                                    SelectionDAG &DAG) const {
10346   if (Subtarget->isThumb1Only())
10347     return false;
10348
10349   EVT VT;
10350   SDValue Ptr;
10351   bool isSEXTLoad = false;
10352   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10353     VT  = LD->getMemoryVT();
10354     Ptr = LD->getBasePtr();
10355     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10356   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10357     VT  = ST->getMemoryVT();
10358     Ptr = ST->getBasePtr();
10359   } else
10360     return false;
10361
10362   bool isInc;
10363   bool isLegal = false;
10364   if (Subtarget->isThumb2())
10365     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10366                                        isInc, DAG);
10367   else
10368     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10369                                         isInc, DAG);
10370   if (!isLegal)
10371     return false;
10372
10373   if (Ptr != Base) {
10374     // Swap base ptr and offset to catch more post-index load / store when
10375     // it's legal. In Thumb2 mode, offset must be an immediate.
10376     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10377         !Subtarget->isThumb2())
10378       std::swap(Base, Offset);
10379
10380     // Post-indexed load / store update the base pointer.
10381     if (Ptr != Base)
10382       return false;
10383   }
10384
10385   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10386   return true;
10387 }
10388
10389 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10390                                                       APInt &KnownZero,
10391                                                       APInt &KnownOne,
10392                                                       const SelectionDAG &DAG,
10393                                                       unsigned Depth) const {
10394   unsigned BitWidth = KnownOne.getBitWidth();
10395   KnownZero = KnownOne = APInt(BitWidth, 0);
10396   switch (Op.getOpcode()) {
10397   default: break;
10398   case ARMISD::ADDC:
10399   case ARMISD::ADDE:
10400   case ARMISD::SUBC:
10401   case ARMISD::SUBE:
10402     // These nodes' second result is a boolean
10403     if (Op.getResNo() == 0)
10404       break;
10405     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10406     break;
10407   case ARMISD::CMOV: {
10408     // Bits are known zero/one if known on the LHS and RHS.
10409     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10410     if (KnownZero == 0 && KnownOne == 0) return;
10411
10412     APInt KnownZeroRHS, KnownOneRHS;
10413     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10414     KnownZero &= KnownZeroRHS;
10415     KnownOne  &= KnownOneRHS;
10416     return;
10417   }
10418   case ISD::INTRINSIC_W_CHAIN: {
10419     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10420     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10421     switch (IntID) {
10422     default: return;
10423     case Intrinsic::arm_ldaex:
10424     case Intrinsic::arm_ldrex: {
10425       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10426       unsigned MemBits = VT.getScalarType().getSizeInBits();
10427       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10428       return;
10429     }
10430     }
10431   }
10432   }
10433 }
10434
10435 //===----------------------------------------------------------------------===//
10436 //                           ARM Inline Assembly Support
10437 //===----------------------------------------------------------------------===//
10438
10439 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10440   // Looking for "rev" which is V6+.
10441   if (!Subtarget->hasV6Ops())
10442     return false;
10443
10444   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10445   std::string AsmStr = IA->getAsmString();
10446   SmallVector<StringRef, 4> AsmPieces;
10447   SplitString(AsmStr, AsmPieces, ";\n");
10448
10449   switch (AsmPieces.size()) {
10450   default: return false;
10451   case 1:
10452     AsmStr = AsmPieces[0];
10453     AsmPieces.clear();
10454     SplitString(AsmStr, AsmPieces, " \t,");
10455
10456     // rev $0, $1
10457     if (AsmPieces.size() == 3 &&
10458         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10459         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10460       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10461       if (Ty && Ty->getBitWidth() == 32)
10462         return IntrinsicLowering::LowerToByteSwap(CI);
10463     }
10464     break;
10465   }
10466
10467   return false;
10468 }
10469
10470 /// getConstraintType - Given a constraint letter, return the type of
10471 /// constraint it is for this target.
10472 ARMTargetLowering::ConstraintType
10473 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10474   if (Constraint.size() == 1) {
10475     switch (Constraint[0]) {
10476     default:  break;
10477     case 'l': return C_RegisterClass;
10478     case 'w': return C_RegisterClass;
10479     case 'h': return C_RegisterClass;
10480     case 'x': return C_RegisterClass;
10481     case 't': return C_RegisterClass;
10482     case 'j': return C_Other; // Constant for movw.
10483       // An address with a single base register. Due to the way we
10484       // currently handle addresses it is the same as an 'r' memory constraint.
10485     case 'Q': return C_Memory;
10486     }
10487   } else if (Constraint.size() == 2) {
10488     switch (Constraint[0]) {
10489     default: break;
10490     // All 'U+' constraints are addresses.
10491     case 'U': return C_Memory;
10492     }
10493   }
10494   return TargetLowering::getConstraintType(Constraint);
10495 }
10496
10497 /// Examine constraint type and operand type and determine a weight value.
10498 /// This object must already have been set up with the operand type
10499 /// and the current alternative constraint selected.
10500 TargetLowering::ConstraintWeight
10501 ARMTargetLowering::getSingleConstraintMatchWeight(
10502     AsmOperandInfo &info, const char *constraint) const {
10503   ConstraintWeight weight = CW_Invalid;
10504   Value *CallOperandVal = info.CallOperandVal;
10505     // If we don't have a value, we can't do a match,
10506     // but allow it at the lowest weight.
10507   if (!CallOperandVal)
10508     return CW_Default;
10509   Type *type = CallOperandVal->getType();
10510   // Look at the constraint type.
10511   switch (*constraint) {
10512   default:
10513     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10514     break;
10515   case 'l':
10516     if (type->isIntegerTy()) {
10517       if (Subtarget->isThumb())
10518         weight = CW_SpecificReg;
10519       else
10520         weight = CW_Register;
10521     }
10522     break;
10523   case 'w':
10524     if (type->isFloatingPointTy())
10525       weight = CW_Register;
10526     break;
10527   }
10528   return weight;
10529 }
10530
10531 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10532 RCPair
10533 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10534                                                 MVT VT) const {
10535   if (Constraint.size() == 1) {
10536     // GCC ARM Constraint Letters
10537     switch (Constraint[0]) {
10538     case 'l': // Low regs or general regs.
10539       if (Subtarget->isThumb())
10540         return RCPair(0U, &ARM::tGPRRegClass);
10541       return RCPair(0U, &ARM::GPRRegClass);
10542     case 'h': // High regs or no regs.
10543       if (Subtarget->isThumb())
10544         return RCPair(0U, &ARM::hGPRRegClass);
10545       break;
10546     case 'r':
10547       if (Subtarget->isThumb1Only())
10548         return RCPair(0U, &ARM::tGPRRegClass);
10549       return RCPair(0U, &ARM::GPRRegClass);
10550     case 'w':
10551       if (VT == MVT::Other)
10552         break;
10553       if (VT == MVT::f32)
10554         return RCPair(0U, &ARM::SPRRegClass);
10555       if (VT.getSizeInBits() == 64)
10556         return RCPair(0U, &ARM::DPRRegClass);
10557       if (VT.getSizeInBits() == 128)
10558         return RCPair(0U, &ARM::QPRRegClass);
10559       break;
10560     case 'x':
10561       if (VT == MVT::Other)
10562         break;
10563       if (VT == MVT::f32)
10564         return RCPair(0U, &ARM::SPR_8RegClass);
10565       if (VT.getSizeInBits() == 64)
10566         return RCPair(0U, &ARM::DPR_8RegClass);
10567       if (VT.getSizeInBits() == 128)
10568         return RCPair(0U, &ARM::QPR_8RegClass);
10569       break;
10570     case 't':
10571       if (VT == MVT::f32)
10572         return RCPair(0U, &ARM::SPRRegClass);
10573       break;
10574     }
10575   }
10576   if (StringRef("{cc}").equals_lower(Constraint))
10577     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10578
10579   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10580 }
10581
10582 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10583 /// vector.  If it is invalid, don't add anything to Ops.
10584 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10585                                                      std::string &Constraint,
10586                                                      std::vector<SDValue>&Ops,
10587                                                      SelectionDAG &DAG) const {
10588   SDValue Result;
10589
10590   // Currently only support length 1 constraints.
10591   if (Constraint.length() != 1) return;
10592
10593   char ConstraintLetter = Constraint[0];
10594   switch (ConstraintLetter) {
10595   default: break;
10596   case 'j':
10597   case 'I': case 'J': case 'K': case 'L':
10598   case 'M': case 'N': case 'O':
10599     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10600     if (!C)
10601       return;
10602
10603     int64_t CVal64 = C->getSExtValue();
10604     int CVal = (int) CVal64;
10605     // None of these constraints allow values larger than 32 bits.  Check
10606     // that the value fits in an int.
10607     if (CVal != CVal64)
10608       return;
10609
10610     switch (ConstraintLetter) {
10611       case 'j':
10612         // Constant suitable for movw, must be between 0 and
10613         // 65535.
10614         if (Subtarget->hasV6T2Ops())
10615           if (CVal >= 0 && CVal <= 65535)
10616             break;
10617         return;
10618       case 'I':
10619         if (Subtarget->isThumb1Only()) {
10620           // This must be a constant between 0 and 255, for ADD
10621           // immediates.
10622           if (CVal >= 0 && CVal <= 255)
10623             break;
10624         } else if (Subtarget->isThumb2()) {
10625           // A constant that can be used as an immediate value in a
10626           // data-processing instruction.
10627           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10628             break;
10629         } else {
10630           // A constant that can be used as an immediate value in a
10631           // data-processing instruction.
10632           if (ARM_AM::getSOImmVal(CVal) != -1)
10633             break;
10634         }
10635         return;
10636
10637       case 'J':
10638         if (Subtarget->isThumb()) {  // FIXME thumb2
10639           // This must be a constant between -255 and -1, for negated ADD
10640           // immediates. This can be used in GCC with an "n" modifier that
10641           // prints the negated value, for use with SUB instructions. It is
10642           // not useful otherwise but is implemented for compatibility.
10643           if (CVal >= -255 && CVal <= -1)
10644             break;
10645         } else {
10646           // This must be a constant between -4095 and 4095. It is not clear
10647           // what this constraint is intended for. Implemented for
10648           // compatibility with GCC.
10649           if (CVal >= -4095 && CVal <= 4095)
10650             break;
10651         }
10652         return;
10653
10654       case 'K':
10655         if (Subtarget->isThumb1Only()) {
10656           // A 32-bit value where only one byte has a nonzero value. Exclude
10657           // zero to match GCC. This constraint is used by GCC internally for
10658           // constants that can be loaded with a move/shift combination.
10659           // It is not useful otherwise but is implemented for compatibility.
10660           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10661             break;
10662         } else if (Subtarget->isThumb2()) {
10663           // A constant whose bitwise inverse can be used as an immediate
10664           // value in a data-processing instruction. This can be used in GCC
10665           // with a "B" modifier that prints the inverted value, for use with
10666           // BIC and MVN instructions. It is not useful otherwise but is
10667           // implemented for compatibility.
10668           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10669             break;
10670         } else {
10671           // A constant whose bitwise inverse can be used as an immediate
10672           // value in a data-processing instruction. This can be used in GCC
10673           // with a "B" modifier that prints the inverted value, for use with
10674           // BIC and MVN instructions. It is not useful otherwise but is
10675           // implemented for compatibility.
10676           if (ARM_AM::getSOImmVal(~CVal) != -1)
10677             break;
10678         }
10679         return;
10680
10681       case 'L':
10682         if (Subtarget->isThumb1Only()) {
10683           // This must be a constant between -7 and 7,
10684           // for 3-operand ADD/SUB immediate instructions.
10685           if (CVal >= -7 && CVal < 7)
10686             break;
10687         } else if (Subtarget->isThumb2()) {
10688           // A constant whose negation can be used as an immediate value in a
10689           // data-processing instruction. This can be used in GCC with an "n"
10690           // modifier that prints the negated value, for use with SUB
10691           // instructions. It is not useful otherwise but is implemented for
10692           // compatibility.
10693           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10694             break;
10695         } else {
10696           // A constant whose negation can be used as an immediate value in a
10697           // data-processing instruction. This can be used in GCC with an "n"
10698           // modifier that prints the negated value, for use with SUB
10699           // instructions. It is not useful otherwise but is implemented for
10700           // compatibility.
10701           if (ARM_AM::getSOImmVal(-CVal) != -1)
10702             break;
10703         }
10704         return;
10705
10706       case 'M':
10707         if (Subtarget->isThumb()) { // FIXME thumb2
10708           // This must be a multiple of 4 between 0 and 1020, for
10709           // ADD sp + immediate.
10710           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10711             break;
10712         } else {
10713           // A power of two or a constant between 0 and 32.  This is used in
10714           // GCC for the shift amount on shifted register operands, but it is
10715           // useful in general for any shift amounts.
10716           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10717             break;
10718         }
10719         return;
10720
10721       case 'N':
10722         if (Subtarget->isThumb()) {  // FIXME thumb2
10723           // This must be a constant between 0 and 31, for shift amounts.
10724           if (CVal >= 0 && CVal <= 31)
10725             break;
10726         }
10727         return;
10728
10729       case 'O':
10730         if (Subtarget->isThumb()) {  // FIXME thumb2
10731           // This must be a multiple of 4 between -508 and 508, for
10732           // ADD/SUB sp = sp + immediate.
10733           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10734             break;
10735         }
10736         return;
10737     }
10738     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10739     break;
10740   }
10741
10742   if (Result.getNode()) {
10743     Ops.push_back(Result);
10744     return;
10745   }
10746   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10747 }
10748
10749 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10750   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10751   unsigned Opcode = Op->getOpcode();
10752   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10753          "Invalid opcode for Div/Rem lowering");
10754   bool isSigned = (Opcode == ISD::SDIVREM);
10755   EVT VT = Op->getValueType(0);
10756   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10757
10758   RTLIB::Libcall LC;
10759   switch (VT.getSimpleVT().SimpleTy) {
10760   default: llvm_unreachable("Unexpected request for libcall!");
10761   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10762   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10763   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10764   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10765   }
10766
10767   SDValue InChain = DAG.getEntryNode();
10768
10769   TargetLowering::ArgListTy Args;
10770   TargetLowering::ArgListEntry Entry;
10771   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10772     EVT ArgVT = Op->getOperand(i).getValueType();
10773     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10774     Entry.Node = Op->getOperand(i);
10775     Entry.Ty = ArgTy;
10776     Entry.isSExt = isSigned;
10777     Entry.isZExt = !isSigned;
10778     Args.push_back(Entry);
10779   }
10780
10781   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10782                                          getPointerTy());
10783
10784   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10785
10786   SDLoc dl(Op);
10787   TargetLowering::CallLoweringInfo CLI(DAG);
10788   CLI.setDebugLoc(dl).setChain(InChain)
10789     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10790     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10791
10792   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10793   return CallInfo.first;
10794 }
10795
10796 SDValue
10797 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10798   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10799   SDLoc DL(Op);
10800
10801   // Get the inputs.
10802   SDValue Chain = Op.getOperand(0);
10803   SDValue Size  = Op.getOperand(1);
10804
10805   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10806                               DAG.getConstant(2, MVT::i32));
10807
10808   SDValue Flag;
10809   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10810   Flag = Chain.getValue(1);
10811
10812   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10813   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10814
10815   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10816   Chain = NewSP.getValue(1);
10817
10818   SDValue Ops[2] = { NewSP, Chain };
10819   return DAG.getMergeValues(Ops, DL);
10820 }
10821
10822 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10823   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10824          "Unexpected type for custom-lowering FP_EXTEND");
10825
10826   RTLIB::Libcall LC;
10827   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10828
10829   SDValue SrcVal = Op.getOperand(0);
10830   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10831                      /*isSigned*/ false, SDLoc(Op)).first;
10832 }
10833
10834 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10835   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10836          Subtarget->isFPOnlySP() &&
10837          "Unexpected type for custom-lowering FP_ROUND");
10838
10839   RTLIB::Libcall LC;
10840   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10841
10842   SDValue SrcVal = Op.getOperand(0);
10843   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10844                      /*isSigned*/ false, SDLoc(Op)).first;
10845 }
10846
10847 bool
10848 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10849   // The ARM target isn't yet aware of offsets.
10850   return false;
10851 }
10852
10853 bool ARM::isBitFieldInvertedMask(unsigned v) {
10854   if (v == 0xffffffff)
10855     return false;
10856
10857   // there can be 1's on either or both "outsides", all the "inside"
10858   // bits must be 0's
10859   unsigned TO = CountTrailingOnes_32(v);
10860   unsigned LO = CountLeadingOnes_32(v);
10861   v = (v >> TO) << TO;
10862   v = (v << LO) >> LO;
10863   return v == 0;
10864 }
10865
10866 /// isFPImmLegal - Returns true if the target can instruction select the
10867 /// specified FP immediate natively. If false, the legalizer will
10868 /// materialize the FP immediate as a load from a constant pool.
10869 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10870   if (!Subtarget->hasVFP3())
10871     return false;
10872   if (VT == MVT::f32)
10873     return ARM_AM::getFP32Imm(Imm) != -1;
10874   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10875     return ARM_AM::getFP64Imm(Imm) != -1;
10876   return false;
10877 }
10878
10879 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10880 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10881 /// specified in the intrinsic calls.
10882 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10883                                            const CallInst &I,
10884                                            unsigned Intrinsic) const {
10885   switch (Intrinsic) {
10886   case Intrinsic::arm_neon_vld1:
10887   case Intrinsic::arm_neon_vld2:
10888   case Intrinsic::arm_neon_vld3:
10889   case Intrinsic::arm_neon_vld4:
10890   case Intrinsic::arm_neon_vld2lane:
10891   case Intrinsic::arm_neon_vld3lane:
10892   case Intrinsic::arm_neon_vld4lane: {
10893     Info.opc = ISD::INTRINSIC_W_CHAIN;
10894     // Conservatively set memVT to the entire set of vectors loaded.
10895     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10896     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10897     Info.ptrVal = I.getArgOperand(0);
10898     Info.offset = 0;
10899     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10900     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10901     Info.vol = false; // volatile loads with NEON intrinsics not supported
10902     Info.readMem = true;
10903     Info.writeMem = false;
10904     return true;
10905   }
10906   case Intrinsic::arm_neon_vst1:
10907   case Intrinsic::arm_neon_vst2:
10908   case Intrinsic::arm_neon_vst3:
10909   case Intrinsic::arm_neon_vst4:
10910   case Intrinsic::arm_neon_vst2lane:
10911   case Intrinsic::arm_neon_vst3lane:
10912   case Intrinsic::arm_neon_vst4lane: {
10913     Info.opc = ISD::INTRINSIC_VOID;
10914     // Conservatively set memVT to the entire set of vectors stored.
10915     unsigned NumElts = 0;
10916     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10917       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10918       if (!ArgTy->isVectorTy())
10919         break;
10920       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10921     }
10922     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10923     Info.ptrVal = I.getArgOperand(0);
10924     Info.offset = 0;
10925     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10926     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10927     Info.vol = false; // volatile stores with NEON intrinsics not supported
10928     Info.readMem = false;
10929     Info.writeMem = true;
10930     return true;
10931   }
10932   case Intrinsic::arm_ldaex:
10933   case Intrinsic::arm_ldrex: {
10934     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10935     Info.opc = ISD::INTRINSIC_W_CHAIN;
10936     Info.memVT = MVT::getVT(PtrTy->getElementType());
10937     Info.ptrVal = I.getArgOperand(0);
10938     Info.offset = 0;
10939     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10940     Info.vol = true;
10941     Info.readMem = true;
10942     Info.writeMem = false;
10943     return true;
10944   }
10945   case Intrinsic::arm_stlex:
10946   case Intrinsic::arm_strex: {
10947     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10948     Info.opc = ISD::INTRINSIC_W_CHAIN;
10949     Info.memVT = MVT::getVT(PtrTy->getElementType());
10950     Info.ptrVal = I.getArgOperand(1);
10951     Info.offset = 0;
10952     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10953     Info.vol = true;
10954     Info.readMem = false;
10955     Info.writeMem = true;
10956     return true;
10957   }
10958   case Intrinsic::arm_stlexd:
10959   case Intrinsic::arm_strexd: {
10960     Info.opc = ISD::INTRINSIC_W_CHAIN;
10961     Info.memVT = MVT::i64;
10962     Info.ptrVal = I.getArgOperand(2);
10963     Info.offset = 0;
10964     Info.align = 8;
10965     Info.vol = true;
10966     Info.readMem = false;
10967     Info.writeMem = true;
10968     return true;
10969   }
10970   case Intrinsic::arm_ldaexd:
10971   case Intrinsic::arm_ldrexd: {
10972     Info.opc = ISD::INTRINSIC_W_CHAIN;
10973     Info.memVT = MVT::i64;
10974     Info.ptrVal = I.getArgOperand(0);
10975     Info.offset = 0;
10976     Info.align = 8;
10977     Info.vol = true;
10978     Info.readMem = true;
10979     Info.writeMem = false;
10980     return true;
10981   }
10982   default:
10983     break;
10984   }
10985
10986   return false;
10987 }
10988
10989 /// \brief Returns true if it is beneficial to convert a load of a constant
10990 /// to just the constant itself.
10991 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10992                                                           Type *Ty) const {
10993   assert(Ty->isIntegerTy());
10994
10995   unsigned Bits = Ty->getPrimitiveSizeInBits();
10996   if (Bits == 0 || Bits > 32)
10997     return false;
10998   return true;
10999 }
11000
11001 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11002
11003 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11004                                         ARM_MB::MemBOpt Domain) const {
11005   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11006
11007   // First, if the target has no DMB, see what fallback we can use.
11008   if (!Subtarget->hasDataBarrier()) {
11009     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11010     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11011     // here.
11012     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11013       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11014       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11015                         Builder.getInt32(0), Builder.getInt32(7),
11016                         Builder.getInt32(10), Builder.getInt32(5)};
11017       return Builder.CreateCall(MCR, args);
11018     } else {
11019       // Instead of using barriers, atomic accesses on these subtargets use
11020       // libcalls.
11021       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11022     }
11023   } else {
11024     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11025     // Only a full system barrier exists in the M-class architectures.
11026     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11027     Constant *CDomain = Builder.getInt32(Domain);
11028     return Builder.CreateCall(DMB, CDomain);
11029   }
11030 }
11031
11032 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11033 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11034                                          AtomicOrdering Ord, bool IsStore,
11035                                          bool IsLoad) const {
11036   if (!getInsertFencesForAtomic())
11037     return nullptr;
11038
11039   switch (Ord) {
11040   case NotAtomic:
11041   case Unordered:
11042     llvm_unreachable("Invalid fence: unordered/non-atomic");
11043   case Monotonic:
11044   case Acquire:
11045     return nullptr; // Nothing to do
11046   case SequentiallyConsistent:
11047     if (!IsStore)
11048       return nullptr; // Nothing to do
11049     /*FALLTHROUGH*/
11050   case Release:
11051   case AcquireRelease:
11052     if (Subtarget->isSwift())
11053       return makeDMB(Builder, ARM_MB::ISHST);
11054     // FIXME: add a comment with a link to documentation justifying this.
11055     else
11056       return makeDMB(Builder, ARM_MB::ISH);
11057   }
11058   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11059 }
11060
11061 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11062                                           AtomicOrdering Ord, bool IsStore,
11063                                           bool IsLoad) const {
11064   if (!getInsertFencesForAtomic())
11065     return nullptr;
11066
11067   switch (Ord) {
11068   case NotAtomic:
11069   case Unordered:
11070     llvm_unreachable("Invalid fence: unordered/not-atomic");
11071   case Monotonic:
11072   case Release:
11073     return nullptr; // Nothing to do
11074   case Acquire:
11075   case AcquireRelease:
11076   case SequentiallyConsistent:
11077     return makeDMB(Builder, ARM_MB::ISH);
11078   }
11079   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11080 }
11081
11082 // Loads and stores less than 64-bits are already atomic; ones above that
11083 // are doomed anyway, so defer to the default libcall and blame the OS when
11084 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11085 // anything for those.
11086 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11087   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11088   return (Size == 64) && !Subtarget->isMClass();
11089 }
11090
11091 // Loads and stores less than 64-bits are already atomic; ones above that
11092 // are doomed anyway, so defer to the default libcall and blame the OS when
11093 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11094 // anything for those.
11095 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11096 // guarantee, see DDI0406C ARM architecture reference manual,
11097 // sections A8.8.72-74 LDRD)
11098 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11099   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11100   return (Size == 64) && !Subtarget->isMClass();
11101 }
11102
11103 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11104 // and up to 64 bits on the non-M profiles
11105 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11106   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11107   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11108 }
11109
11110 // This has so far only been implemented for MachO.
11111 bool ARMTargetLowering::useLoadStackGuardNode() const {
11112   return Subtarget->isTargetMachO();
11113 }
11114
11115 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11116                                                   unsigned &Cost) const {
11117   // If we do not have NEON, vector types are not natively supported.
11118   if (!Subtarget->hasNEON())
11119     return false;
11120
11121   // Floating point values and vector values map to the same register file.
11122   // Therefore, althought we could do a store extract of a vector type, this is
11123   // better to leave at float as we have more freedom in the addressing mode for
11124   // those.
11125   if (VectorTy->isFPOrFPVectorTy())
11126     return false;
11127
11128   // If the index is unknown at compile time, this is very expensive to lower
11129   // and it is not possible to combine the store with the extract.
11130   if (!isa<ConstantInt>(Idx))
11131     return false;
11132
11133   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11134   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11135   // We can do a store + vector extract on any vector that fits perfectly in a D
11136   // or Q register.
11137   if (BitWidth == 64 || BitWidth == 128) {
11138     Cost = 0;
11139     return true;
11140   }
11141   return false;
11142 }
11143
11144 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11145                                          AtomicOrdering Ord) const {
11146   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11147   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11148   bool IsAcquire = isAtLeastAcquire(Ord);
11149
11150   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11151   // intrinsic must return {i32, i32} and we have to recombine them into a
11152   // single i64 here.
11153   if (ValTy->getPrimitiveSizeInBits() == 64) {
11154     Intrinsic::ID Int =
11155         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11156     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11157
11158     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11159     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11160
11161     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11162     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11163     if (!Subtarget->isLittle())
11164       std::swap (Lo, Hi);
11165     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11166     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11167     return Builder.CreateOr(
11168         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11169   }
11170
11171   Type *Tys[] = { Addr->getType() };
11172   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11173   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11174
11175   return Builder.CreateTruncOrBitCast(
11176       Builder.CreateCall(Ldrex, Addr),
11177       cast<PointerType>(Addr->getType())->getElementType());
11178 }
11179
11180 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11181                                                Value *Addr,
11182                                                AtomicOrdering Ord) const {
11183   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11184   bool IsRelease = isAtLeastRelease(Ord);
11185
11186   // Since the intrinsics must have legal type, the i64 intrinsics take two
11187   // parameters: "i32, i32". We must marshal Val into the appropriate form
11188   // before the call.
11189   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11190     Intrinsic::ID Int =
11191         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11192     Function *Strex = Intrinsic::getDeclaration(M, Int);
11193     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11194
11195     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11196     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11197     if (!Subtarget->isLittle())
11198       std::swap (Lo, Hi);
11199     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11200     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11201   }
11202
11203   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11204   Type *Tys[] = { Addr->getType() };
11205   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11206
11207   return Builder.CreateCall2(
11208       Strex, Builder.CreateZExtOrBitCast(
11209                  Val, Strex->getFunctionType()->getParamType(0)),
11210       Addr);
11211 }
11212
11213 enum HABaseType {
11214   HA_UNKNOWN = 0,
11215   HA_FLOAT,
11216   HA_DOUBLE,
11217   HA_VECT64,
11218   HA_VECT128
11219 };
11220
11221 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11222                                    uint64_t &Members) {
11223   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11224     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11225       uint64_t SubMembers = 0;
11226       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11227         return false;
11228       Members += SubMembers;
11229     }
11230   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11231     uint64_t SubMembers = 0;
11232     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11233       return false;
11234     Members += SubMembers * AT->getNumElements();
11235   } else if (Ty->isFloatTy()) {
11236     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11237       return false;
11238     Members = 1;
11239     Base = HA_FLOAT;
11240   } else if (Ty->isDoubleTy()) {
11241     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11242       return false;
11243     Members = 1;
11244     Base = HA_DOUBLE;
11245   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11246     Members = 1;
11247     switch (Base) {
11248     case HA_FLOAT:
11249     case HA_DOUBLE:
11250       return false;
11251     case HA_VECT64:
11252       return VT->getBitWidth() == 64;
11253     case HA_VECT128:
11254       return VT->getBitWidth() == 128;
11255     case HA_UNKNOWN:
11256       switch (VT->getBitWidth()) {
11257       case 64:
11258         Base = HA_VECT64;
11259         return true;
11260       case 128:
11261         Base = HA_VECT128;
11262         return true;
11263       default:
11264         return false;
11265       }
11266     }
11267   }
11268
11269   return (Members > 0 && Members <= 4);
11270 }
11271
11272 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11273 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11274     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11275   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11276       CallingConv::ARM_AAPCS_VFP)
11277     return false;
11278
11279   HABaseType Base = HA_UNKNOWN;
11280   uint64_t Members = 0;
11281   bool result = isHomogeneousAggregate(Ty, Base, Members);
11282   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11283   return result;
11284 }