[CodeGen] Use ArrayRef instead of std::vector&. 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                                      const ARMSubtarget &STI)
161     : TargetLowering(TM), Subtarget(&STI) {
162   RegInfo = Subtarget->getRegisterInfo();
163   Itins = Subtarget->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 (MVT VT : MVT::vector_valuetypes()) {
408     for (MVT InnerVT : MVT::vector_valuetypes()) {
409       setTruncStoreAction(VT, InnerVT, Expand);
410       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
411       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
412       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
413     }
414
415     setOperationAction(ISD::MULHS, VT, Expand);
416     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
417     setOperationAction(ISD::MULHU, VT, Expand);
418     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
419
420     setOperationAction(ISD::BSWAP, VT, Expand);
421   }
422
423   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
424   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
425
426   if (Subtarget->hasNEON()) {
427     addDRTypeForNEON(MVT::v2f32);
428     addDRTypeForNEON(MVT::v8i8);
429     addDRTypeForNEON(MVT::v4i16);
430     addDRTypeForNEON(MVT::v2i32);
431     addDRTypeForNEON(MVT::v1i64);
432
433     addQRTypeForNEON(MVT::v4f32);
434     addQRTypeForNEON(MVT::v2f64);
435     addQRTypeForNEON(MVT::v16i8);
436     addQRTypeForNEON(MVT::v8i16);
437     addQRTypeForNEON(MVT::v4i32);
438     addQRTypeForNEON(MVT::v2i64);
439
440     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
441     // neither Neon nor VFP support any arithmetic operations on it.
442     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
443     // supported for v4f32.
444     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
445     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
446     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
447     // FIXME: Code duplication: FDIV and FREM are expanded always, see
448     // ARMTargetLowering::addTypeForNEON method for details.
449     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
450     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
451     // FIXME: Create unittest.
452     // In another words, find a way when "copysign" appears in DAG with vector
453     // operands.
454     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
455     // FIXME: Code duplication: SETCC has custom operation action, see
456     // ARMTargetLowering::addTypeForNEON method for details.
457     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
458     // FIXME: Create unittest for FNEG and for FABS.
459     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
472     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
473     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
474     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
475     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
476     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
477     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
478
479     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
480     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
481     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
482     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
483     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
485     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
486     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
487     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
488     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
489     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
490     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
491     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
492     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
494
495     // Mark v2f32 intrinsics.
496     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
497     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
498     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
499     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
500     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
502     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
503     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
504     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
505     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
506     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
507     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
508     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
509     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
511
512     // Neon does not support some operations on v1i64 and v2i64 types.
513     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
514     // Custom handling for some quad-vector types to detect VMULL.
515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
518     // Custom handling for some vector types to avoid expensive expansions
519     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
522     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
523     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
524     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
525     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
526     // a destination type that is wider than the source, and nor does
527     // it have a FP_TO_[SU]INT instruction with a narrower destination than
528     // source.
529     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
530     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
531     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
532     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
533
534     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
535     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
536
537     // NEON does not have single instruction CTPOP for vectors with element
538     // types wider than 8-bits.  However, custom lowering can leverage the
539     // v8i8/v16i8 vcnt instruction.
540     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
542     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
543     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
544
545     // NEON only has FMA instructions as of VFP4.
546     if (!Subtarget->hasVFP4()) {
547       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
548       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
549     }
550
551     setTargetDAGCombine(ISD::INTRINSIC_VOID);
552     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
554     setTargetDAGCombine(ISD::SHL);
555     setTargetDAGCombine(ISD::SRL);
556     setTargetDAGCombine(ISD::SRA);
557     setTargetDAGCombine(ISD::SIGN_EXTEND);
558     setTargetDAGCombine(ISD::ZERO_EXTEND);
559     setTargetDAGCombine(ISD::ANY_EXTEND);
560     setTargetDAGCombine(ISD::SELECT_CC);
561     setTargetDAGCombine(ISD::BUILD_VECTOR);
562     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
563     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
564     setTargetDAGCombine(ISD::STORE);
565     setTargetDAGCombine(ISD::FP_TO_SINT);
566     setTargetDAGCombine(ISD::FP_TO_UINT);
567     setTargetDAGCombine(ISD::FDIV);
568
569     // It is legal to extload from v4i8 to v4i16 or v4i32.
570     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
571                   MVT::v4i16, MVT::v2i16,
572                   MVT::v2i32};
573     for (unsigned i = 0; i < 6; ++i) {
574       for (MVT VT : MVT::integer_vector_valuetypes()) {
575         setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
576         setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
577         setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
578       }
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   for (MVT VT : MVT::fp_valuetypes()) {
624     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
626   }
627
628   // ... or truncating stores
629   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
630   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
631   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
632
633   // ARM does not have i1 sign extending load.
634   for (MVT VT : MVT::integer_valuetypes())
635     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
636
637   // ARM supports all 4 flavors of integer indexed load / store.
638   if (!Subtarget->isThumb1Only()) {
639     for (unsigned im = (unsigned)ISD::PRE_INC;
640          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
641       setIndexedLoadAction(im,  MVT::i1,  Legal);
642       setIndexedLoadAction(im,  MVT::i8,  Legal);
643       setIndexedLoadAction(im,  MVT::i16, Legal);
644       setIndexedLoadAction(im,  MVT::i32, Legal);
645       setIndexedStoreAction(im, MVT::i1,  Legal);
646       setIndexedStoreAction(im, MVT::i8,  Legal);
647       setIndexedStoreAction(im, MVT::i16, Legal);
648       setIndexedStoreAction(im, MVT::i32, Legal);
649     }
650   }
651
652   setOperationAction(ISD::SADDO, MVT::i32, Custom);
653   setOperationAction(ISD::UADDO, MVT::i32, Custom);
654   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
655   setOperationAction(ISD::USUBO, MVT::i32, Custom);
656
657   // i64 operation support.
658   setOperationAction(ISD::MUL,     MVT::i64, Expand);
659   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
660   if (Subtarget->isThumb1Only()) {
661     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
662     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
663   }
664   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
665       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
666     setOperationAction(ISD::MULHS, MVT::i32, Expand);
667
668   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
669   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
670   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRL,       MVT::i64, Custom);
672   setOperationAction(ISD::SRA,       MVT::i64, Custom);
673
674   if (!Subtarget->isThumb1Only()) {
675     // FIXME: We should do this for Thumb1 as well.
676     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
677     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
678     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
679     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
680   }
681
682   // ARM does not have ROTL.
683   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
684   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
685   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
686   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
687     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
688
689   // These just redirect to CTTZ and CTLZ on ARM.
690   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
691   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
692
693   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
694
695   // Only ARMv6 has BSWAP.
696   if (!Subtarget->hasV6Ops())
697     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
698
699   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
700       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
701     // These are expanded into libcalls if the cpu doesn't have HW divider.
702     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
703     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
704   }
705
706   // FIXME: Also set divmod for SREM on EABI
707   setOperationAction(ISD::SREM,  MVT::i32, Expand);
708   setOperationAction(ISD::UREM,  MVT::i32, Expand);
709   // Register based DivRem for AEABI (RTABI 4.2)
710   if (Subtarget->isTargetAEABI()) {
711     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
712     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
713     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
715     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
716     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
717     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
719
720     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
721     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
728
729     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
730     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
731   } else {
732     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
733     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
734   }
735
736   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
737   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
738   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
739   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
740   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
741
742   setOperationAction(ISD::TRAP, MVT::Other, Legal);
743
744   // Use the default implementation.
745   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
746   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
747   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
748   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
749   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
750   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
751
752   if (!Subtarget->isTargetMachO()) {
753     // Non-MachO platforms may return values in these registers via the
754     // personality function.
755     setExceptionPointerRegister(ARM::R0);
756     setExceptionSelectorRegister(ARM::R1);
757   }
758
759   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
760     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
761   else
762     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
763
764   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
765   // the default expansion. If we are targeting a single threaded system,
766   // then set them all for expand so we can lower them later into their
767   // non-atomic form.
768   if (TM.Options.ThreadModel == ThreadModel::Single)
769     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
770   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
771     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
772     // to ldrex/strex loops already.
773     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
774
775     // On v8, we have particularly efficient implementations of atomic fences
776     // if they can be combined with nearby atomic loads and stores.
777     if (!Subtarget->hasV8Ops()) {
778       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
779       setInsertFencesForAtomic(true);
780     }
781   } else {
782     // If there's anything we can use as a barrier, go through custom lowering
783     // for ATOMIC_FENCE.
784     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
785                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
786
787     // Set them all for expansion, which will force libcalls.
788     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
789     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
800     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
801     // Unordered/Monotonic case.
802     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
803     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
804   }
805
806   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
807
808   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
809   if (!Subtarget->hasV6Ops()) {
810     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
812   }
813   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
814
815   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
816       !Subtarget->isThumb1Only()) {
817     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
818     // iff target supports vfp2.
819     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
820     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
821   }
822
823   // We want to custom lower some of our intrinsics.
824   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
825   if (Subtarget->isTargetDarwin()) {
826     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
827     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
828     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
829   }
830
831   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
832   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
833   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
834   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
835   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
836   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
837   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
838   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
840
841   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
842   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
843   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
844   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
845   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
846
847   // We don't support sin/cos/fmod/copysign/pow
848   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
849   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
850   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
851   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
852   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
853   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
854   setOperationAction(ISD::FREM,      MVT::f64, Expand);
855   setOperationAction(ISD::FREM,      MVT::f32, Expand);
856   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
857       !Subtarget->isThumb1Only()) {
858     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
859     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
860   }
861   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
862   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
863
864   if (!Subtarget->hasVFP4()) {
865     setOperationAction(ISD::FMA, MVT::f64, Expand);
866     setOperationAction(ISD::FMA, MVT::f32, Expand);
867   }
868
869   // Various VFP goodness
870   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
871     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
872     if (Subtarget->hasVFP2()) {
873       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
874       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
875       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
876       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
877     }
878
879     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
883     }
884
885     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886     if (!Subtarget->hasFP16()) {
887       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
889     }
890   }
891
892   // Combine sin / cos into one node or libcall if possible.
893   if (Subtarget->hasSinCos()) {
894     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895     setLibcallName(RTLIB::SINCOS_F64, "sincos");
896     if (Subtarget->getTargetTriple().isiOS()) {
897       // For iOS, we don't want to the normal expansion of a libcall to
898       // sincos. We want to issue a libcall to __sincos_stret.
899       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
901     }
902   }
903
904   // FP-ARMv8 implements a lot of rounding-like FP operations.
905   if (Subtarget->hasFPARMv8()) {
906     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908     setOperationAction(ISD::FROUND, MVT::f32, Legal);
909     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911     setOperationAction(ISD::FRINT, MVT::f32, Legal);
912     if (!Subtarget->isFPOnlySP()) {
913       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918       setOperationAction(ISD::FRINT, MVT::f64, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass*, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
971   const TargetRegisterClass *RRC = nullptr;
972   uint8_t Cost = 1;
973   switch (VT.SimpleTy) {
974   default:
975     return TargetLowering::findRepresentativeClass(VT);
976   // Use DPR as representative register class for all floating point
977   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978   // the cost is 1 for both f32 and f64.
979   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981     RRC = &ARM::DPRRegClass;
982     // When NEON is used for SP, only half of the register file is available
983     // because operations that define both SP and DP results will be constrained
984     // to the VFP2 class (D0-D15). We currently model this constraint prior to
985     // coalescing by double-counting the SP regs. See the FIXME above.
986     if (Subtarget->useNEONForSinglePrecisionFP())
987       Cost = 2;
988     break;
989   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990   case MVT::v4f32: case MVT::v2f64:
991     RRC = &ARM::DPRRegClass;
992     Cost = 2;
993     break;
994   case MVT::v4i64:
995     RRC = &ARM::DPRRegClass;
996     Cost = 4;
997     break;
998   case MVT::v8i64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 8;
1001     break;
1002   }
1003   return std::make_pair(RRC, Cost);
1004 }
1005
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007   switch (Opcode) {
1008   default: return nullptr;
1009   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1010   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1011   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1012   case ARMISD::CALL:          return "ARMISD::CALL";
1013   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1014   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1015   case ARMISD::tCALL:         return "ARMISD::tCALL";
1016   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1017   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1018   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1019   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1020   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1021   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1022   case ARMISD::CMP:           return "ARMISD::CMP";
1023   case ARMISD::CMN:           return "ARMISD::CMN";
1024   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1025   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1026   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1027   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1028   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1029
1030   case ARMISD::CMOV:          return "ARMISD::CMOV";
1031
1032   case ARMISD::RBIT:          return "ARMISD::RBIT";
1033
1034   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1035   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1036   case ARMISD::SITOF:         return "ARMISD::SITOF";
1037   case ARMISD::UITOF:         return "ARMISD::UITOF";
1038
1039   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1040   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1041   case ARMISD::RRX:           return "ARMISD::RRX";
1042
1043   case ARMISD::ADDC:          return "ARMISD::ADDC";
1044   case ARMISD::ADDE:          return "ARMISD::ADDE";
1045   case ARMISD::SUBC:          return "ARMISD::SUBC";
1046   case ARMISD::SUBE:          return "ARMISD::SUBE";
1047
1048   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1049   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1050
1051   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1053
1054   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1055
1056   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1057
1058   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1059
1060   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1061
1062   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1063
1064   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1197   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1198
1199   if (MCID.getNumDefs() == 0)
1200     return Sched::RegPressure;
1201   if (!Itins->isEmpty() &&
1202       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1203     return Sched::ILP;
1204
1205   return Sched::RegPressure;
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Lowering Code
1210 //===----------------------------------------------------------------------===//
1211
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1214   switch (CC) {
1215   default: llvm_unreachable("Unknown condition code!");
1216   case ISD::SETNE:  return ARMCC::NE;
1217   case ISD::SETEQ:  return ARMCC::EQ;
1218   case ISD::SETGT:  return ARMCC::GT;
1219   case ISD::SETGE:  return ARMCC::GE;
1220   case ISD::SETLT:  return ARMCC::LT;
1221   case ISD::SETLE:  return ARMCC::LE;
1222   case ISD::SETUGT: return ARMCC::HI;
1223   case ISD::SETUGE: return ARMCC::HS;
1224   case ISD::SETULT: return ARMCC::LO;
1225   case ISD::SETULE: return ARMCC::LS;
1226   }
1227 }
1228
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231                         ARMCC::CondCodes &CondCode2) {
1232   CondCode2 = ARMCC::AL;
1233   switch (CC) {
1234   default: llvm_unreachable("Unknown FP condition!");
1235   case ISD::SETEQ:
1236   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1237   case ISD::SETGT:
1238   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1239   case ISD::SETGE:
1240   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244   case ISD::SETO:   CondCode = ARMCC::VC; break;
1245   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1246   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1249   case ISD::SETLT:
1250   case ISD::SETULT: CondCode = ARMCC::LT; break;
1251   case ISD::SETLE:
1252   case ISD::SETULE: CondCode = ARMCC::LE; break;
1253   case ISD::SETNE:
1254   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1255   }
1256 }
1257
1258 //===----------------------------------------------------------------------===//
1259 //                      Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1261
1262 #include "ARMGenCallingConv.inc"
1263
1264 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1265 /// account presence of floating point hardware and calling convention
1266 /// limitations, such as support for variadic functions.
1267 CallingConv::ID
1268 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1269                                            bool isVarArg) const {
1270   switch (CC) {
1271   default:
1272     llvm_unreachable("Unsupported calling convention");
1273   case CallingConv::ARM_AAPCS:
1274   case CallingConv::ARM_APCS:
1275   case CallingConv::GHC:
1276     return CC;
1277   case CallingConv::ARM_AAPCS_VFP:
1278     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1279   case CallingConv::C:
1280     if (!Subtarget->isAAPCS_ABI())
1281       return CallingConv::ARM_APCS;
1282     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1283              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1284              !isVarArg)
1285       return CallingConv::ARM_AAPCS_VFP;
1286     else
1287       return CallingConv::ARM_AAPCS;
1288   case CallingConv::Fast:
1289     if (!Subtarget->isAAPCS_ABI()) {
1290       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1291         return CallingConv::Fast;
1292       return CallingConv::ARM_APCS;
1293     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1294       return CallingConv::ARM_AAPCS_VFP;
1295     else
1296       return CallingConv::ARM_AAPCS;
1297   }
1298 }
1299
1300 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1301 /// CallingConvention.
1302 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1303                                                  bool Return,
1304                                                  bool isVarArg) const {
1305   switch (getEffectiveCallingConv(CC, isVarArg)) {
1306   default:
1307     llvm_unreachable("Unsupported calling convention");
1308   case CallingConv::ARM_APCS:
1309     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1310   case CallingConv::ARM_AAPCS:
1311     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1312   case CallingConv::ARM_AAPCS_VFP:
1313     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1314   case CallingConv::Fast:
1315     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1316   case CallingConv::GHC:
1317     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1318   }
1319 }
1320
1321 /// LowerCallResult - Lower the result values of a call into the
1322 /// appropriate copies out of appropriate physical registers.
1323 SDValue
1324 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1325                                    CallingConv::ID CallConv, bool isVarArg,
1326                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1327                                    SDLoc dl, SelectionDAG &DAG,
1328                                    SmallVectorImpl<SDValue> &InVals,
1329                                    bool isThisReturn, SDValue ThisVal) const {
1330
1331   // Assign locations to each value returned by this call.
1332   SmallVector<CCValAssign, 16> RVLocs;
1333   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1334                     *DAG.getContext(), Call);
1335   CCInfo.AnalyzeCallResult(Ins,
1336                            CCAssignFnForNode(CallConv, /* Return*/ true,
1337                                              isVarArg));
1338
1339   // Copy all of the result registers out of their specified physreg.
1340   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341     CCValAssign VA = RVLocs[i];
1342
1343     // Pass 'this' value directly from the argument to return value, to avoid
1344     // reg unit interference
1345     if (i == 0 && isThisReturn) {
1346       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1347              "unexpected return calling convention register assignment");
1348       InVals.push_back(ThisVal);
1349       continue;
1350     }
1351
1352     SDValue Val;
1353     if (VA.needsCustom()) {
1354       // Handle f64 or half of a v2f64.
1355       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1356                                       InFlag);
1357       Chain = Lo.getValue(1);
1358       InFlag = Lo.getValue(2);
1359       VA = RVLocs[++i]; // skip ahead to next loc
1360       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1361                                       InFlag);
1362       Chain = Hi.getValue(1);
1363       InFlag = Hi.getValue(2);
1364       if (!Subtarget->isLittle())
1365         std::swap (Lo, Hi);
1366       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1367
1368       if (VA.getLocVT() == MVT::v2f64) {
1369         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1370         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1371                           DAG.getConstant(0, MVT::i32));
1372
1373         VA = RVLocs[++i]; // skip ahead to next loc
1374         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1375         Chain = Lo.getValue(1);
1376         InFlag = Lo.getValue(2);
1377         VA = RVLocs[++i]; // skip ahead to next loc
1378         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379         Chain = Hi.getValue(1);
1380         InFlag = Hi.getValue(2);
1381         if (!Subtarget->isLittle())
1382           std::swap (Lo, Hi);
1383         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1384         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1385                           DAG.getConstant(1, MVT::i32));
1386       }
1387     } else {
1388       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1389                                InFlag);
1390       Chain = Val.getValue(1);
1391       InFlag = Val.getValue(2);
1392     }
1393
1394     switch (VA.getLocInfo()) {
1395     default: llvm_unreachable("Unknown loc info!");
1396     case CCValAssign::Full: break;
1397     case CCValAssign::BCvt:
1398       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1399       break;
1400     }
1401
1402     InVals.push_back(Val);
1403   }
1404
1405   return Chain;
1406 }
1407
1408 /// LowerMemOpCallTo - Store the argument to the stack.
1409 SDValue
1410 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1411                                     SDValue StackPtr, SDValue Arg,
1412                                     SDLoc dl, SelectionDAG &DAG,
1413                                     const CCValAssign &VA,
1414                                     ISD::ArgFlagsTy Flags) const {
1415   unsigned LocMemOffset = VA.getLocMemOffset();
1416   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1417   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1418   return DAG.getStore(Chain, dl, Arg, PtrOff,
1419                       MachinePointerInfo::getStack(LocMemOffset),
1420                       false, false, 0);
1421 }
1422
1423 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1424                                          SDValue Chain, SDValue &Arg,
1425                                          RegsToPassVector &RegsToPass,
1426                                          CCValAssign &VA, CCValAssign &NextVA,
1427                                          SDValue &StackPtr,
1428                                          SmallVectorImpl<SDValue> &MemOpChains,
1429                                          ISD::ArgFlagsTy Flags) const {
1430
1431   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1432                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1433   unsigned id = Subtarget->isLittle() ? 0 : 1;
1434   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1435
1436   if (NextVA.isRegLoc())
1437     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1438   else {
1439     assert(NextVA.isMemLoc());
1440     if (!StackPtr.getNode())
1441       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1442
1443     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1444                                            dl, DAG, NextVA,
1445                                            Flags));
1446   }
1447 }
1448
1449 /// LowerCall - Lowering a call into a callseq_start <-
1450 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1451 /// nodes.
1452 SDValue
1453 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1454                              SmallVectorImpl<SDValue> &InVals) const {
1455   SelectionDAG &DAG                     = CLI.DAG;
1456   SDLoc &dl                          = CLI.DL;
1457   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1458   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1459   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1460   SDValue Chain                         = CLI.Chain;
1461   SDValue Callee                        = CLI.Callee;
1462   bool &isTailCall                      = CLI.IsTailCall;
1463   CallingConv::ID CallConv              = CLI.CallConv;
1464   bool doesNotRet                       = CLI.DoesNotReturn;
1465   bool isVarArg                         = CLI.IsVarArg;
1466
1467   MachineFunction &MF = DAG.getMachineFunction();
1468   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1469   bool isThisReturn   = false;
1470   bool isSibCall      = false;
1471
1472   // Disable tail calls if they're not supported.
1473   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1474     isTailCall = false;
1475
1476   if (isTailCall) {
1477     // Check if it's really possible to do a tail call.
1478     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1479                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1480                                                    Outs, OutVals, Ins, DAG);
1481     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1482       report_fatal_error("failed to perform tail call elimination on a call "
1483                          "site marked musttail");
1484     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1485     // detected sibcalls.
1486     if (isTailCall) {
1487       ++NumTailCalls;
1488       isSibCall = true;
1489     }
1490   }
1491
1492   // Analyze operands of the call, assigning locations to each operand.
1493   SmallVector<CCValAssign, 16> ArgLocs;
1494   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1495                     *DAG.getContext(), Call);
1496   CCInfo.AnalyzeCallOperands(Outs,
1497                              CCAssignFnForNode(CallConv, /* Return*/ false,
1498                                                isVarArg));
1499
1500   // Get a count of how many bytes are to be pushed on the stack.
1501   unsigned NumBytes = CCInfo.getNextStackOffset();
1502
1503   // For tail calls, memory operands are available in our caller's stack.
1504   if (isSibCall)
1505     NumBytes = 0;
1506
1507   // Adjust the stack pointer for the new arguments...
1508   // These operations are automatically eliminated by the prolog/epilog pass
1509   if (!isSibCall)
1510     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1511                                  dl);
1512
1513   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1514
1515   RegsToPassVector RegsToPass;
1516   SmallVector<SDValue, 8> MemOpChains;
1517
1518   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1519   // of tail call optimization, arguments are handled later.
1520   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1521        i != e;
1522        ++i, ++realArgIdx) {
1523     CCValAssign &VA = ArgLocs[i];
1524     SDValue Arg = OutVals[realArgIdx];
1525     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1526     bool isByVal = Flags.isByVal();
1527
1528     // Promote the value if needed.
1529     switch (VA.getLocInfo()) {
1530     default: llvm_unreachable("Unknown loc info!");
1531     case CCValAssign::Full: break;
1532     case CCValAssign::SExt:
1533       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1534       break;
1535     case CCValAssign::ZExt:
1536       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1537       break;
1538     case CCValAssign::AExt:
1539       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1540       break;
1541     case CCValAssign::BCvt:
1542       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1543       break;
1544     }
1545
1546     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1547     if (VA.needsCustom()) {
1548       if (VA.getLocVT() == MVT::v2f64) {
1549         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1550                                   DAG.getConstant(0, MVT::i32));
1551         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1552                                   DAG.getConstant(1, MVT::i32));
1553
1554         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1555                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1556
1557         VA = ArgLocs[++i]; // skip ahead to next loc
1558         if (VA.isRegLoc()) {
1559           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1560                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1561         } else {
1562           assert(VA.isMemLoc());
1563
1564           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1565                                                  dl, DAG, VA, Flags));
1566         }
1567       } else {
1568         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1569                          StackPtr, MemOpChains, Flags);
1570       }
1571     } else if (VA.isRegLoc()) {
1572       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1573         assert(VA.getLocVT() == MVT::i32 &&
1574                "unexpected calling convention register assignment");
1575         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1576                "unexpected use of 'returned'");
1577         isThisReturn = true;
1578       }
1579       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1580     } else if (isByVal) {
1581       assert(VA.isMemLoc());
1582       unsigned offset = 0;
1583
1584       // True if this byval aggregate will be split between registers
1585       // and memory.
1586       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1587       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1588
1589       if (CurByValIdx < ByValArgsCount) {
1590
1591         unsigned RegBegin, RegEnd;
1592         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1593
1594         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1595         unsigned int i, j;
1596         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1597           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1598           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1599           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1600                                      MachinePointerInfo(),
1601                                      false, false, false,
1602                                      DAG.InferPtrAlignment(AddArg));
1603           MemOpChains.push_back(Load.getValue(1));
1604           RegsToPass.push_back(std::make_pair(j, Load));
1605         }
1606
1607         // If parameter size outsides register area, "offset" value
1608         // helps us to calculate stack slot for remained part properly.
1609         offset = RegEnd - RegBegin;
1610
1611         CCInfo.nextInRegsParam();
1612       }
1613
1614       if (Flags.getByValSize() > 4*offset) {
1615         unsigned LocMemOffset = VA.getLocMemOffset();
1616         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1617         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1618                                   StkPtrOff);
1619         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1620         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1621         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1622                                            MVT::i32);
1623         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1624
1625         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1626         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1627         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1628                                           Ops));
1629       }
1630     } else if (!isSibCall) {
1631       assert(VA.isMemLoc());
1632
1633       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1634                                              dl, DAG, VA, Flags));
1635     }
1636   }
1637
1638   if (!MemOpChains.empty())
1639     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1640
1641   // Build a sequence of copy-to-reg nodes chained together with token chain
1642   // and flag operands which copy the outgoing args into the appropriate regs.
1643   SDValue InFlag;
1644   // Tail call byval lowering might overwrite argument registers so in case of
1645   // tail call optimization the copies to registers are lowered later.
1646   if (!isTailCall)
1647     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1648       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1649                                RegsToPass[i].second, InFlag);
1650       InFlag = Chain.getValue(1);
1651     }
1652
1653   // For tail calls lower the arguments to the 'real' stack slot.
1654   if (isTailCall) {
1655     // Force all the incoming stack arguments to be loaded from the stack
1656     // before any new outgoing arguments are stored to the stack, because the
1657     // outgoing stack slots may alias the incoming argument stack slots, and
1658     // the alias isn't otherwise explicit. This is slightly more conservative
1659     // than necessary, because it means that each store effectively depends
1660     // on every argument instead of just those arguments it would clobber.
1661
1662     // Do not flag preceding copytoreg stuff together with the following stuff.
1663     InFlag = SDValue();
1664     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666                                RegsToPass[i].second, InFlag);
1667       InFlag = Chain.getValue(1);
1668     }
1669     InFlag = SDValue();
1670   }
1671
1672   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1673   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1674   // node so that legalize doesn't hack it.
1675   bool isDirect = false;
1676   bool isARMFunc = false;
1677   bool isLocalARMFunc = false;
1678   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1679
1680   if (EnableARMLongCalls) {
1681     assert((Subtarget->isTargetWindows() ||
1682             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1683            "long-calls with non-static relocation model!");
1684     // Handle a global address or an external symbol. If it's not one of
1685     // those, the target's already in a register, so we don't need to do
1686     // anything extra.
1687     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1688       const GlobalValue *GV = G->getGlobal();
1689       // Create a constant pool entry for the callee address
1690       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1691       ARMConstantPoolValue *CPV =
1692         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1693
1694       // Get the address of the callee into a register
1695       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1696       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1697       Callee = DAG.getLoad(getPointerTy(), dl,
1698                            DAG.getEntryNode(), CPAddr,
1699                            MachinePointerInfo::getConstantPool(),
1700                            false, false, false, 0);
1701     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1702       const char *Sym = S->getSymbol();
1703
1704       // Create a constant pool entry for the callee address
1705       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706       ARMConstantPoolValue *CPV =
1707         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1708                                       ARMPCLabelIndex, 0);
1709       // Get the address of the callee into a register
1710       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1711       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1712       Callee = DAG.getLoad(getPointerTy(), dl,
1713                            DAG.getEntryNode(), CPAddr,
1714                            MachinePointerInfo::getConstantPool(),
1715                            false, false, false, 0);
1716     }
1717   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1718     const GlobalValue *GV = G->getGlobal();
1719     isDirect = true;
1720     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1721     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1722                    getTargetMachine().getRelocationModel() != Reloc::Static;
1723     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1724     // ARM call to a local ARM function is predicable.
1725     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1726     // tBX takes a register source operand.
1727     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1728       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1729       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1730                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1731                                                       0, ARMII::MO_NONLAZY));
1732       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1733                            MachinePointerInfo::getGOT(), false, false, true, 0);
1734     } else if (Subtarget->isTargetCOFF()) {
1735       assert(Subtarget->isTargetWindows() &&
1736              "Windows is the only supported COFF target");
1737       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1738                                  ? ARMII::MO_DLLIMPORT
1739                                  : ARMII::MO_NO_FLAG;
1740       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1741                                           TargetFlags);
1742       if (GV->hasDLLImportStorageClass())
1743         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1744                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1745                                          Callee), MachinePointerInfo::getGOT(),
1746                              false, false, false, 0);
1747     } else {
1748       // On ELF targets for PIC code, direct calls should go through the PLT
1749       unsigned OpFlags = 0;
1750       if (Subtarget->isTargetELF() &&
1751           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1752         OpFlags = ARMII::MO_PLT;
1753       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1754     }
1755   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1756     isDirect = true;
1757     bool isStub = Subtarget->isTargetMachO() &&
1758                   getTargetMachine().getRelocationModel() != Reloc::Static;
1759     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1760     // tBX takes a register source operand.
1761     const char *Sym = S->getSymbol();
1762     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1763       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1764       ARMConstantPoolValue *CPV =
1765         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1766                                       ARMPCLabelIndex, 4);
1767       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1768       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1769       Callee = DAG.getLoad(getPointerTy(), dl,
1770                            DAG.getEntryNode(), CPAddr,
1771                            MachinePointerInfo::getConstantPool(),
1772                            false, false, false, 0);
1773       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1774       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1775                            getPointerTy(), Callee, PICLabel);
1776     } else {
1777       unsigned OpFlags = 0;
1778       // On ELF targets for PIC code, direct calls should go through the PLT
1779       if (Subtarget->isTargetELF() &&
1780                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1781         OpFlags = ARMII::MO_PLT;
1782       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1783     }
1784   }
1785
1786   // FIXME: handle tail calls differently.
1787   unsigned CallOpc;
1788   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1789   if (Subtarget->isThumb()) {
1790     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1791       CallOpc = ARMISD::CALL_NOLINK;
1792     else
1793       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1794   } else {
1795     if (!isDirect && !Subtarget->hasV5TOps())
1796       CallOpc = ARMISD::CALL_NOLINK;
1797     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1798                // Emit regular call when code size is the priority
1799                !HasMinSizeAttr)
1800       // "mov lr, pc; b _foo" to avoid confusing the RSP
1801       CallOpc = ARMISD::CALL_NOLINK;
1802     else
1803       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1804   }
1805
1806   std::vector<SDValue> Ops;
1807   Ops.push_back(Chain);
1808   Ops.push_back(Callee);
1809
1810   // Add argument registers to the end of the list so that they are known live
1811   // into the call.
1812   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1813     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1814                                   RegsToPass[i].second.getValueType()));
1815
1816   // Add a register mask operand representing the call-preserved registers.
1817   if (!isTailCall) {
1818     const uint32_t *Mask;
1819     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1820     if (isThisReturn) {
1821       // For 'this' returns, use the R0-preserving mask if applicable
1822       Mask = ARI->getThisReturnPreservedMask(CallConv);
1823       if (!Mask) {
1824         // Set isThisReturn to false if the calling convention is not one that
1825         // allows 'returned' to be modeled in this way, so LowerCallResult does
1826         // not try to pass 'this' straight through
1827         isThisReturn = false;
1828         Mask = ARI->getCallPreservedMask(CallConv);
1829       }
1830     } else
1831       Mask = ARI->getCallPreservedMask(CallConv);
1832
1833     assert(Mask && "Missing call preserved mask for calling convention");
1834     Ops.push_back(DAG.getRegisterMask(Mask));
1835   }
1836
1837   if (InFlag.getNode())
1838     Ops.push_back(InFlag);
1839
1840   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1841   if (isTailCall)
1842     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1843
1844   // Returns a chain and a flag for retval copy to use.
1845   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1846   InFlag = Chain.getValue(1);
1847
1848   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1849                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1850   if (!Ins.empty())
1851     InFlag = Chain.getValue(1);
1852
1853   // Handle result values, copying them out of physregs into vregs that we
1854   // return.
1855   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1856                          InVals, isThisReturn,
1857                          isThisReturn ? OutVals[0] : SDValue());
1858 }
1859
1860 /// HandleByVal - Every parameter *after* a byval parameter is passed
1861 /// on the stack.  Remember the next parameter register to allocate,
1862 /// and then confiscate the rest of the parameter registers to insure
1863 /// this.
1864 void
1865 ARMTargetLowering::HandleByVal(
1866     CCState *State, unsigned &size, unsigned Align) const {
1867   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1868   assert((State->getCallOrPrologue() == Prologue ||
1869           State->getCallOrPrologue() == Call) &&
1870          "unhandled ParmContext");
1871
1872   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1873     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1874       unsigned AlignInRegs = Align / 4;
1875       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1876       for (unsigned i = 0; i < Waste; ++i)
1877         reg = State->AllocateReg(GPRArgRegs, 4);
1878     }
1879     if (reg != 0) {
1880       unsigned excess = 4 * (ARM::R4 - reg);
1881
1882       // Special case when NSAA != SP and parameter size greater than size of
1883       // all remained GPR regs. In that case we can't split parameter, we must
1884       // send it to stack. We also must set NCRN to R4, so waste all
1885       // remained registers.
1886       const unsigned NSAAOffset = State->getNextStackOffset();
1887       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1888         while (State->AllocateReg(GPRArgRegs, 4))
1889           ;
1890         return;
1891       }
1892
1893       // First register for byval parameter is the first register that wasn't
1894       // allocated before this method call, so it would be "reg".
1895       // If parameter is small enough to be saved in range [reg, r4), then
1896       // the end (first after last) register would be reg + param-size-in-regs,
1897       // else parameter would be splitted between registers and stack,
1898       // end register would be r4 in this case.
1899       unsigned ByValRegBegin = reg;
1900       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1901       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1902       // Note, first register is allocated in the beginning of function already,
1903       // allocate remained amount of registers we need.
1904       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1905         State->AllocateReg(GPRArgRegs, 4);
1906       // A byval parameter that is split between registers and memory needs its
1907       // size truncated here.
1908       // In the case where the entire structure fits in registers, we set the
1909       // size in memory to zero.
1910       if (size < excess)
1911         size = 0;
1912       else
1913         size -= excess;
1914     }
1915   }
1916 }
1917
1918 /// MatchingStackOffset - Return true if the given stack call argument is
1919 /// already available in the same position (relatively) of the caller's
1920 /// incoming argument stack.
1921 static
1922 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1923                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1924                          const TargetInstrInfo *TII) {
1925   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1926   int FI = INT_MAX;
1927   if (Arg.getOpcode() == ISD::CopyFromReg) {
1928     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1929     if (!TargetRegisterInfo::isVirtualRegister(VR))
1930       return false;
1931     MachineInstr *Def = MRI->getVRegDef(VR);
1932     if (!Def)
1933       return false;
1934     if (!Flags.isByVal()) {
1935       if (!TII->isLoadFromStackSlot(Def, FI))
1936         return false;
1937     } else {
1938       return false;
1939     }
1940   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1941     if (Flags.isByVal())
1942       // ByVal argument is passed in as a pointer but it's now being
1943       // dereferenced. e.g.
1944       // define @foo(%struct.X* %A) {
1945       //   tail call @bar(%struct.X* byval %A)
1946       // }
1947       return false;
1948     SDValue Ptr = Ld->getBasePtr();
1949     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1950     if (!FINode)
1951       return false;
1952     FI = FINode->getIndex();
1953   } else
1954     return false;
1955
1956   assert(FI != INT_MAX);
1957   if (!MFI->isFixedObjectIndex(FI))
1958     return false;
1959   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1960 }
1961
1962 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1963 /// for tail call optimization. Targets which want to do tail call
1964 /// optimization should implement this function.
1965 bool
1966 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1967                                                      CallingConv::ID CalleeCC,
1968                                                      bool isVarArg,
1969                                                      bool isCalleeStructRet,
1970                                                      bool isCallerStructRet,
1971                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1972                                     const SmallVectorImpl<SDValue> &OutVals,
1973                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1974                                                      SelectionDAG& DAG) const {
1975   const Function *CallerF = DAG.getMachineFunction().getFunction();
1976   CallingConv::ID CallerCC = CallerF->getCallingConv();
1977   bool CCMatch = CallerCC == CalleeCC;
1978
1979   // Look for obvious safe cases to perform tail call optimization that do not
1980   // require ABI changes. This is what gcc calls sibcall.
1981
1982   // Do not sibcall optimize vararg calls unless the call site is not passing
1983   // any arguments.
1984   if (isVarArg && !Outs.empty())
1985     return false;
1986
1987   // Exception-handling functions need a special set of instructions to indicate
1988   // a return to the hardware. Tail-calling another function would probably
1989   // break this.
1990   if (CallerF->hasFnAttribute("interrupt"))
1991     return false;
1992
1993   // Also avoid sibcall optimization if either caller or callee uses struct
1994   // return semantics.
1995   if (isCalleeStructRet || isCallerStructRet)
1996     return false;
1997
1998   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1999   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2000   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2001   // support in the assembler and linker to be used. This would need to be
2002   // fixed to fully support tail calls in Thumb1.
2003   //
2004   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2005   // LR.  This means if we need to reload LR, it takes an extra instructions,
2006   // which outweighs the value of the tail call; but here we don't know yet
2007   // whether LR is going to be used.  Probably the right approach is to
2008   // generate the tail call here and turn it back into CALL/RET in
2009   // emitEpilogue if LR is used.
2010
2011   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2012   // but we need to make sure there are enough registers; the only valid
2013   // registers are the 4 used for parameters.  We don't currently do this
2014   // case.
2015   if (Subtarget->isThumb1Only())
2016     return false;
2017
2018   // Externally-defined functions with weak linkage should not be
2019   // tail-called on ARM when the OS does not support dynamic
2020   // pre-emption of symbols, as the AAELF spec requires normal calls
2021   // to undefined weak functions to be replaced with a NOP or jump to the
2022   // next instruction. The behaviour of branch instructions in this
2023   // situation (as used for tail calls) is implementation-defined, so we
2024   // cannot rely on the linker replacing the tail call with a return.
2025   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2026     const GlobalValue *GV = G->getGlobal();
2027     const Triple TT(getTargetMachine().getTargetTriple());
2028     if (GV->hasExternalWeakLinkage() &&
2029         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2030       return false;
2031   }
2032
2033   // If the calling conventions do not match, then we'd better make sure the
2034   // results are returned in the same way as what the caller expects.
2035   if (!CCMatch) {
2036     SmallVector<CCValAssign, 16> RVLocs1;
2037     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2038                        *DAG.getContext(), Call);
2039     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2040
2041     SmallVector<CCValAssign, 16> RVLocs2;
2042     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2043                        *DAG.getContext(), Call);
2044     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2045
2046     if (RVLocs1.size() != RVLocs2.size())
2047       return false;
2048     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2049       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2050         return false;
2051       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2052         return false;
2053       if (RVLocs1[i].isRegLoc()) {
2054         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2055           return false;
2056       } else {
2057         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2058           return false;
2059       }
2060     }
2061   }
2062
2063   // If Caller's vararg or byval argument has been split between registers and
2064   // stack, do not perform tail call, since part of the argument is in caller's
2065   // local frame.
2066   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2067                                       getInfo<ARMFunctionInfo>();
2068   if (AFI_Caller->getArgRegsSaveSize())
2069     return false;
2070
2071   // If the callee takes no arguments then go on to check the results of the
2072   // call.
2073   if (!Outs.empty()) {
2074     // Check if stack adjustment is needed. For now, do not do this if any
2075     // argument is passed on the stack.
2076     SmallVector<CCValAssign, 16> ArgLocs;
2077     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2078                       *DAG.getContext(), Call);
2079     CCInfo.AnalyzeCallOperands(Outs,
2080                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2081     if (CCInfo.getNextStackOffset()) {
2082       MachineFunction &MF = DAG.getMachineFunction();
2083
2084       // Check if the arguments are already laid out in the right way as
2085       // the caller's fixed stack objects.
2086       MachineFrameInfo *MFI = MF.getFrameInfo();
2087       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2088       const TargetInstrInfo *TII = Subtarget->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 = Subtarget->getFrameLowering()->getStackAlignment();
2847   ArgRegsSize = NumGPRs * 4;
2848
2849   // If parameter is split between stack and GPRs...
2850   if (NumGPRs && Align > 4 &&
2851       (ArgRegsSize < ArgSize ||
2852         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2853     // Add padding for part of param recovered from GPRs.  For example,
2854     // if Align == 8, its last byte must be at address K*8 - 1.
2855     // We need to do it, since remained (stack) part of parameter has
2856     // stack alignment, and we need to "attach" "GPRs head" without gaps
2857     // to it:
2858     // Stack:
2859     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2860     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2861     //
2862     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2863     unsigned Padding =
2864         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2865     ArgRegsSaveSize = ArgRegsSize + Padding;
2866   } else
2867     // We don't need to extend regs save size for byval parameters if they
2868     // are passed via GPRs only.
2869     ArgRegsSaveSize = ArgRegsSize;
2870 }
2871
2872 // The remaining GPRs hold either the beginning of variable-argument
2873 // data, or the beginning of an aggregate passed by value (usually
2874 // byval).  Either way, we allocate stack slots adjacent to the data
2875 // provided by our caller, and store the unallocated registers there.
2876 // If this is a variadic function, the va_list pointer will begin with
2877 // these values; otherwise, this reassembles a (byval) structure that
2878 // was split between registers and memory.
2879 // Return: The frame index registers were stored into.
2880 int
2881 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2882                                   SDLoc dl, SDValue &Chain,
2883                                   const Value *OrigArg,
2884                                   unsigned InRegsParamRecordIdx,
2885                                   unsigned OffsetFromOrigArg,
2886                                   unsigned ArgOffset,
2887                                   unsigned ArgSize,
2888                                   bool ForceMutable,
2889                                   unsigned ByValStoreOffset,
2890                                   unsigned TotalArgRegsSaveSize) const {
2891
2892   // Currently, two use-cases possible:
2893   // Case #1. Non-var-args function, and we meet first byval parameter.
2894   //          Setup first unallocated register as first byval register;
2895   //          eat all remained registers
2896   //          (these two actions are performed by HandleByVal method).
2897   //          Then, here, we initialize stack frame with
2898   //          "store-reg" instructions.
2899   // Case #2. Var-args function, that doesn't contain byval parameters.
2900   //          The same: eat all remained unallocated registers,
2901   //          initialize stack frame.
2902
2903   MachineFunction &MF = DAG.getMachineFunction();
2904   MachineFrameInfo *MFI = MF.getFrameInfo();
2905   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2906   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2907   unsigned RBegin, REnd;
2908   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2909     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2910     firstRegToSaveIndex = RBegin - ARM::R0;
2911     lastRegToSaveIndex = REnd - ARM::R0;
2912   } else {
2913     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2914       (GPRArgRegs, array_lengthof(GPRArgRegs));
2915     lastRegToSaveIndex = 4;
2916   }
2917
2918   unsigned ArgRegsSize, ArgRegsSaveSize;
2919   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2920                  ArgRegsSize, ArgRegsSaveSize);
2921
2922   // Store any by-val regs to their spots on the stack so that they may be
2923   // loaded by deferencing the result of formal parameter pointer or va_next.
2924   // Note: once stack area for byval/varargs registers
2925   // was initialized, it can't be initialized again.
2926   if (ArgRegsSaveSize) {
2927     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2928
2929     if (Padding) {
2930       assert(AFI->getStoredByValParamsPadding() == 0 &&
2931              "The only parameter may be padded.");
2932       AFI->setStoredByValParamsPadding(Padding);
2933     }
2934
2935     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2936                                             Padding +
2937                                               ByValStoreOffset -
2938                                               (int64_t)TotalArgRegsSaveSize,
2939                                             false);
2940     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2941     if (Padding) {
2942        MFI->CreateFixedObject(Padding,
2943                               ArgOffset + ByValStoreOffset -
2944                                 (int64_t)ArgRegsSaveSize,
2945                               false);
2946     }
2947
2948     SmallVector<SDValue, 4> MemOps;
2949     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2950          ++firstRegToSaveIndex, ++i) {
2951       const TargetRegisterClass *RC;
2952       if (AFI->isThumb1OnlyFunction())
2953         RC = &ARM::tGPRRegClass;
2954       else
2955         RC = &ARM::GPRRegClass;
2956
2957       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2958       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2959       SDValue Store =
2960         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2961                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2962                      false, false, 0);
2963       MemOps.push_back(Store);
2964       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2965                         DAG.getConstant(4, getPointerTy()));
2966     }
2967
2968     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2969
2970     if (!MemOps.empty())
2971       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2972     return FrameIndex;
2973   } else {
2974     if (ArgSize == 0) {
2975       // We cannot allocate a zero-byte object for the first variadic argument,
2976       // so just make up a size.
2977       ArgSize = 4;
2978     }
2979     // This will point to the next argument passed via stack.
2980     return MFI->CreateFixedObject(
2981       ArgSize, ArgOffset, !ForceMutable);
2982   }
2983 }
2984
2985 // Setup stack frame, the va_list pointer will start from.
2986 void
2987 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2988                                         SDLoc dl, SDValue &Chain,
2989                                         unsigned ArgOffset,
2990                                         unsigned TotalArgRegsSaveSize,
2991                                         bool ForceMutable) const {
2992   MachineFunction &MF = DAG.getMachineFunction();
2993   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2994
2995   // Try to store any remaining integer argument regs
2996   // to their spots on the stack so that they may be loaded by deferencing
2997   // the result of va_next.
2998   // If there is no regs to be stored, just point address after last
2999   // argument passed via stack.
3000   int FrameIndex =
3001     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3002                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3003                    0, TotalArgRegsSaveSize);
3004
3005   AFI->setVarArgsFrameIndex(FrameIndex);
3006 }
3007
3008 SDValue
3009 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3010                                         CallingConv::ID CallConv, bool isVarArg,
3011                                         const SmallVectorImpl<ISD::InputArg>
3012                                           &Ins,
3013                                         SDLoc dl, SelectionDAG &DAG,
3014                                         SmallVectorImpl<SDValue> &InVals)
3015                                           const {
3016   MachineFunction &MF = DAG.getMachineFunction();
3017   MachineFrameInfo *MFI = MF.getFrameInfo();
3018
3019   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3020
3021   // Assign locations to all of the incoming arguments.
3022   SmallVector<CCValAssign, 16> ArgLocs;
3023   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3024                     *DAG.getContext(), Prologue);
3025   CCInfo.AnalyzeFormalArguments(Ins,
3026                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3027                                                   isVarArg));
3028
3029   SmallVector<SDValue, 16> ArgValues;
3030   int lastInsIndex = -1;
3031   SDValue ArgValue;
3032   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3033   unsigned CurArgIdx = 0;
3034
3035   // Initially ArgRegsSaveSize is zero.
3036   // Then we increase this value each time we meet byval parameter.
3037   // We also increase this value in case of varargs function.
3038   AFI->setArgRegsSaveSize(0);
3039
3040   unsigned ByValStoreOffset = 0;
3041   unsigned TotalArgRegsSaveSize = 0;
3042   unsigned ArgRegsSaveSizeMaxAlign = 4;
3043
3044   // Calculate the amount of stack space that we need to allocate to store
3045   // byval and variadic arguments that are passed in registers.
3046   // We need to know this before we allocate the first byval or variadic
3047   // argument, as they will be allocated a stack slot below the CFA (Canonical
3048   // Frame Address, the stack pointer at entry to the function).
3049   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3050     CCValAssign &VA = ArgLocs[i];
3051     if (VA.isMemLoc()) {
3052       int index = VA.getValNo();
3053       if (index != lastInsIndex) {
3054         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3055         if (Flags.isByVal()) {
3056           unsigned ExtraArgRegsSize;
3057           unsigned ExtraArgRegsSaveSize;
3058           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3059                          Flags.getByValSize(),
3060                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3061
3062           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3063           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3064               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3065           CCInfo.nextInRegsParam();
3066         }
3067         lastInsIndex = index;
3068       }
3069     }
3070   }
3071   CCInfo.rewindByValRegsInfo();
3072   lastInsIndex = -1;
3073   if (isVarArg && MFI->hasVAStart()) {
3074     unsigned ExtraArgRegsSize;
3075     unsigned ExtraArgRegsSaveSize;
3076     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3077                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3078     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3079   }
3080   // If the arg regs save area contains N-byte aligned values, the
3081   // bottom of it must be at least N-byte aligned.
3082   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3083   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3084
3085   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3086     CCValAssign &VA = ArgLocs[i];
3087     if (Ins[VA.getValNo()].isOrigArg()) {
3088       std::advance(CurOrigArg,
3089                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3090       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3091     }
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 = VA.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             assert(Ins[index].isOrigArg() &&
3185                    "Byval arguments cannot be implicit");
3186             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3187
3188             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3189             int FrameIndex = StoreByValRegs(
3190                 CCInfo, DAG, dl, Chain, CurOrigArg,
3191                 CurByValIndex,
3192                 Ins[VA.getValNo()].PartOffset,
3193                 VA.getLocMemOffset(),
3194                 Flags.getByValSize(),
3195                 true /*force mutable frames*/,
3196                 ByValStoreOffset,
3197                 TotalArgRegsSaveSize);
3198             ByValStoreOffset += Flags.getByValSize();
3199             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3200             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3201             CCInfo.nextInRegsParam();
3202           } else {
3203             unsigned FIOffset = VA.getLocMemOffset();
3204             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3205                                             FIOffset, true);
3206
3207             // Create load nodes to retrieve arguments from the stack.
3208             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3209             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3210                                          MachinePointerInfo::getFixedStack(FI),
3211                                          false, false, false, 0));
3212           }
3213           lastInsIndex = index;
3214         }
3215     }
3216   }
3217
3218   // varargs
3219   if (isVarArg && MFI->hasVAStart())
3220     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3221                          CCInfo.getNextStackOffset(),
3222                          TotalArgRegsSaveSize);
3223
3224   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3225
3226   return Chain;
3227 }
3228
3229 /// isFloatingPointZero - Return true if this is +0.0.
3230 static bool isFloatingPointZero(SDValue Op) {
3231   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3232     return CFP->getValueAPF().isPosZero();
3233   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3234     // Maybe this has already been legalized into the constant pool?
3235     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3236       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3237       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3238         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3239           return CFP->getValueAPF().isPosZero();
3240     }
3241   } else if (Op->getOpcode() == ISD::BITCAST &&
3242              Op->getValueType(0) == MVT::f64) {
3243     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3244     // created by LowerConstantFP().
3245     SDValue BitcastOp = Op->getOperand(0);
3246     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3247       SDValue MoveOp = BitcastOp->getOperand(0);
3248       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3249           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3250         return true;
3251       }
3252     }
3253   }
3254   return false;
3255 }
3256
3257 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3258 /// the given operands.
3259 SDValue
3260 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3261                              SDValue &ARMcc, SelectionDAG &DAG,
3262                              SDLoc dl) const {
3263   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3264     unsigned C = RHSC->getZExtValue();
3265     if (!isLegalICmpImmediate(C)) {
3266       // Constant does not fit, try adjusting it by one?
3267       switch (CC) {
3268       default: break;
3269       case ISD::SETLT:
3270       case ISD::SETGE:
3271         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3272           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3273           RHS = DAG.getConstant(C-1, MVT::i32);
3274         }
3275         break;
3276       case ISD::SETULT:
3277       case ISD::SETUGE:
3278         if (C != 0 && isLegalICmpImmediate(C-1)) {
3279           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3280           RHS = DAG.getConstant(C-1, MVT::i32);
3281         }
3282         break;
3283       case ISD::SETLE:
3284       case ISD::SETGT:
3285         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3286           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3287           RHS = DAG.getConstant(C+1, MVT::i32);
3288         }
3289         break;
3290       case ISD::SETULE:
3291       case ISD::SETUGT:
3292         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3293           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3294           RHS = DAG.getConstant(C+1, MVT::i32);
3295         }
3296         break;
3297       }
3298     }
3299   }
3300
3301   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3302   ARMISD::NodeType CompareType;
3303   switch (CondCode) {
3304   default:
3305     CompareType = ARMISD::CMP;
3306     break;
3307   case ARMCC::EQ:
3308   case ARMCC::NE:
3309     // Uses only Z Flag
3310     CompareType = ARMISD::CMPZ;
3311     break;
3312   }
3313   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3314   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3315 }
3316
3317 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3318 SDValue
3319 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3320                              SDLoc dl) const {
3321   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3322   SDValue Cmp;
3323   if (!isFloatingPointZero(RHS))
3324     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3325   else
3326     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3327   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3328 }
3329
3330 /// duplicateCmp - Glue values can have only one use, so this function
3331 /// duplicates a comparison node.
3332 SDValue
3333 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3334   unsigned Opc = Cmp.getOpcode();
3335   SDLoc DL(Cmp);
3336   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3337     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3338
3339   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3340   Cmp = Cmp.getOperand(0);
3341   Opc = Cmp.getOpcode();
3342   if (Opc == ARMISD::CMPFP)
3343     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3344   else {
3345     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3346     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3347   }
3348   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3349 }
3350
3351 std::pair<SDValue, SDValue>
3352 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3353                                  SDValue &ARMcc) const {
3354   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3355
3356   SDValue Value, OverflowCmp;
3357   SDValue LHS = Op.getOperand(0);
3358   SDValue RHS = Op.getOperand(1);
3359
3360
3361   // FIXME: We are currently always generating CMPs because we don't support
3362   // generating CMN through the backend. This is not as good as the natural
3363   // CMP case because it causes a register dependency and cannot be folded
3364   // later.
3365
3366   switch (Op.getOpcode()) {
3367   default:
3368     llvm_unreachable("Unknown overflow instruction!");
3369   case ISD::SADDO:
3370     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3371     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3372     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3373     break;
3374   case ISD::UADDO:
3375     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3376     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3377     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3378     break;
3379   case ISD::SSUBO:
3380     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3381     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3382     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3383     break;
3384   case ISD::USUBO:
3385     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3386     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3387     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3388     break;
3389   } // switch (...)
3390
3391   return std::make_pair(Value, OverflowCmp);
3392 }
3393
3394
3395 SDValue
3396 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3397   // Let legalize expand this if it isn't a legal type yet.
3398   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3399     return SDValue();
3400
3401   SDValue Value, OverflowCmp;
3402   SDValue ARMcc;
3403   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3404   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3405   // We use 0 and 1 as false and true values.
3406   SDValue TVal = DAG.getConstant(1, MVT::i32);
3407   SDValue FVal = DAG.getConstant(0, MVT::i32);
3408   EVT VT = Op.getValueType();
3409
3410   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3411                                  ARMcc, CCR, OverflowCmp);
3412
3413   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3414   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3415 }
3416
3417
3418 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3419   SDValue Cond = Op.getOperand(0);
3420   SDValue SelectTrue = Op.getOperand(1);
3421   SDValue SelectFalse = Op.getOperand(2);
3422   SDLoc dl(Op);
3423   unsigned Opc = Cond.getOpcode();
3424
3425   if (Cond.getResNo() == 1 &&
3426       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3427        Opc == ISD::USUBO)) {
3428     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3429       return SDValue();
3430
3431     SDValue Value, OverflowCmp;
3432     SDValue ARMcc;
3433     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3434     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3435     EVT VT = Op.getValueType();
3436
3437     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3438                    OverflowCmp, DAG);
3439   }
3440
3441   // Convert:
3442   //
3443   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3444   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3445   //
3446   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3447     const ConstantSDNode *CMOVTrue =
3448       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3449     const ConstantSDNode *CMOVFalse =
3450       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3451
3452     if (CMOVTrue && CMOVFalse) {
3453       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3454       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3455
3456       SDValue True;
3457       SDValue False;
3458       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3459         True = SelectTrue;
3460         False = SelectFalse;
3461       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3462         True = SelectFalse;
3463         False = SelectTrue;
3464       }
3465
3466       if (True.getNode() && False.getNode()) {
3467         EVT VT = Op.getValueType();
3468         SDValue ARMcc = Cond.getOperand(2);
3469         SDValue CCR = Cond.getOperand(3);
3470         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3471         assert(True.getValueType() == VT);
3472         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3473       }
3474     }
3475   }
3476
3477   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3478   // undefined bits before doing a full-word comparison with zero.
3479   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3480                      DAG.getConstant(1, Cond.getValueType()));
3481
3482   return DAG.getSelectCC(dl, Cond,
3483                          DAG.getConstant(0, Cond.getValueType()),
3484                          SelectTrue, SelectFalse, ISD::SETNE);
3485 }
3486
3487 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3488   if (CC == ISD::SETNE)
3489     return ISD::SETEQ;
3490   return ISD::getSetCCInverse(CC, true);
3491 }
3492
3493 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3494                                  bool &swpCmpOps, bool &swpVselOps) {
3495   // Start by selecting the GE condition code for opcodes that return true for
3496   // 'equality'
3497   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3498       CC == ISD::SETULE)
3499     CondCode = ARMCC::GE;
3500
3501   // and GT for opcodes that return false for 'equality'.
3502   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3503            CC == ISD::SETULT)
3504     CondCode = ARMCC::GT;
3505
3506   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3507   // to swap the compare operands.
3508   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3509       CC == ISD::SETULT)
3510     swpCmpOps = true;
3511
3512   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3513   // If we have an unordered opcode, we need to swap the operands to the VSEL
3514   // instruction (effectively negating the condition).
3515   //
3516   // This also has the effect of swapping which one of 'less' or 'greater'
3517   // returns true, so we also swap the compare operands. It also switches
3518   // whether we return true for 'equality', so we compensate by picking the
3519   // opposite condition code to our original choice.
3520   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3521       CC == ISD::SETUGT) {
3522     swpCmpOps = !swpCmpOps;
3523     swpVselOps = !swpVselOps;
3524     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3525   }
3526
3527   // 'ordered' is 'anything but unordered', so use the VS condition code and
3528   // swap the VSEL operands.
3529   if (CC == ISD::SETO) {
3530     CondCode = ARMCC::VS;
3531     swpVselOps = true;
3532   }
3533
3534   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3535   // code and swap the VSEL operands.
3536   if (CC == ISD::SETUNE) {
3537     CondCode = ARMCC::EQ;
3538     swpVselOps = true;
3539   }
3540 }
3541
3542 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3543                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3544                                    SDValue Cmp, SelectionDAG &DAG) const {
3545   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3546     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3547                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3548     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3549                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3550
3551     SDValue TrueLow = TrueVal.getValue(0);
3552     SDValue TrueHigh = TrueVal.getValue(1);
3553     SDValue FalseLow = FalseVal.getValue(0);
3554     SDValue FalseHigh = FalseVal.getValue(1);
3555
3556     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3557                               ARMcc, CCR, Cmp);
3558     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3559                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3560
3561     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3562   } else {
3563     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3564                        Cmp);
3565   }
3566 }
3567
3568 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3569   EVT VT = Op.getValueType();
3570   SDValue LHS = Op.getOperand(0);
3571   SDValue RHS = Op.getOperand(1);
3572   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3573   SDValue TrueVal = Op.getOperand(2);
3574   SDValue FalseVal = Op.getOperand(3);
3575   SDLoc dl(Op);
3576
3577   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3578     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3579                                                     dl);
3580
3581     // If softenSetCCOperands only returned one value, we should compare it to
3582     // zero.
3583     if (!RHS.getNode()) {
3584       RHS = DAG.getConstant(0, LHS.getValueType());
3585       CC = ISD::SETNE;
3586     }
3587   }
3588
3589   if (LHS.getValueType() == MVT::i32) {
3590     // Try to generate VSEL on ARMv8.
3591     // The VSEL instruction can't use all the usual ARM condition
3592     // codes: it only has two bits to select the condition code, so it's
3593     // constrained to use only GE, GT, VS and EQ.
3594     //
3595     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3596     // swap the operands of the previous compare instruction (effectively
3597     // inverting the compare condition, swapping 'less' and 'greater') and
3598     // sometimes need to swap the operands to the VSEL (which inverts the
3599     // condition in the sense of firing whenever the previous condition didn't)
3600     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3601                                     TrueVal.getValueType() == MVT::f64)) {
3602       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3603       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3604           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3605         CC = getInverseCCForVSEL(CC);
3606         std::swap(TrueVal, FalseVal);
3607       }
3608     }
3609
3610     SDValue ARMcc;
3611     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3612     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3613     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3614   }
3615
3616   ARMCC::CondCodes CondCode, CondCode2;
3617   FPCCToARMCC(CC, CondCode, CondCode2);
3618
3619   // Try to generate VSEL on ARMv8.
3620   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3621                                   TrueVal.getValueType() == MVT::f64)) {
3622     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3623     // same operands, as follows:
3624     //   c = fcmp [ogt, olt, ugt, ult] a, b
3625     //   select c, a, b
3626     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3627     // handled differently than the original code sequence.
3628     if (getTargetMachine().Options.UnsafeFPMath) {
3629       if (LHS == TrueVal && RHS == FalseVal) {
3630         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3631           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3632         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3633           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3634       } else if (LHS == FalseVal && RHS == TrueVal) {
3635         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3636           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3637         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3638           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3639       }
3640     }
3641
3642     bool swpCmpOps = false;
3643     bool swpVselOps = false;
3644     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3645
3646     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3647         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3648       if (swpCmpOps)
3649         std::swap(LHS, RHS);
3650       if (swpVselOps)
3651         std::swap(TrueVal, FalseVal);
3652     }
3653   }
3654
3655   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3656   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3657   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3658   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3659   if (CondCode2 != ARMCC::AL) {
3660     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3661     // FIXME: Needs another CMP because flag can have but one use.
3662     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3663     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3664   }
3665   return Result;
3666 }
3667
3668 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3669 /// to morph to an integer compare sequence.
3670 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3671                            const ARMSubtarget *Subtarget) {
3672   SDNode *N = Op.getNode();
3673   if (!N->hasOneUse())
3674     // Otherwise it requires moving the value from fp to integer registers.
3675     return false;
3676   if (!N->getNumValues())
3677     return false;
3678   EVT VT = Op.getValueType();
3679   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3680     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3681     // vmrs are very slow, e.g. cortex-a8.
3682     return false;
3683
3684   if (isFloatingPointZero(Op)) {
3685     SeenZero = true;
3686     return true;
3687   }
3688   return ISD::isNormalLoad(N);
3689 }
3690
3691 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3692   if (isFloatingPointZero(Op))
3693     return DAG.getConstant(0, MVT::i32);
3694
3695   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3696     return DAG.getLoad(MVT::i32, SDLoc(Op),
3697                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3698                        Ld->isVolatile(), Ld->isNonTemporal(),
3699                        Ld->isInvariant(), Ld->getAlignment());
3700
3701   llvm_unreachable("Unknown VFP cmp argument!");
3702 }
3703
3704 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3705                            SDValue &RetVal1, SDValue &RetVal2) {
3706   if (isFloatingPointZero(Op)) {
3707     RetVal1 = DAG.getConstant(0, MVT::i32);
3708     RetVal2 = DAG.getConstant(0, MVT::i32);
3709     return;
3710   }
3711
3712   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3713     SDValue Ptr = Ld->getBasePtr();
3714     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3715                           Ld->getChain(), Ptr,
3716                           Ld->getPointerInfo(),
3717                           Ld->isVolatile(), Ld->isNonTemporal(),
3718                           Ld->isInvariant(), Ld->getAlignment());
3719
3720     EVT PtrType = Ptr.getValueType();
3721     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3722     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3723                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3724     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3725                           Ld->getChain(), NewPtr,
3726                           Ld->getPointerInfo().getWithOffset(4),
3727                           Ld->isVolatile(), Ld->isNonTemporal(),
3728                           Ld->isInvariant(), NewAlign);
3729     return;
3730   }
3731
3732   llvm_unreachable("Unknown VFP cmp argument!");
3733 }
3734
3735 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3736 /// f32 and even f64 comparisons to integer ones.
3737 SDValue
3738 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3739   SDValue Chain = Op.getOperand(0);
3740   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3741   SDValue LHS = Op.getOperand(2);
3742   SDValue RHS = Op.getOperand(3);
3743   SDValue Dest = Op.getOperand(4);
3744   SDLoc dl(Op);
3745
3746   bool LHSSeenZero = false;
3747   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3748   bool RHSSeenZero = false;
3749   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3750   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3751     // If unsafe fp math optimization is enabled and there are no other uses of
3752     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3753     // to an integer comparison.
3754     if (CC == ISD::SETOEQ)
3755       CC = ISD::SETEQ;
3756     else if (CC == ISD::SETUNE)
3757       CC = ISD::SETNE;
3758
3759     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3760     SDValue ARMcc;
3761     if (LHS.getValueType() == MVT::f32) {
3762       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3763                         bitcastf32Toi32(LHS, DAG), Mask);
3764       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3765                         bitcastf32Toi32(RHS, DAG), Mask);
3766       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3767       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3768       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3769                          Chain, Dest, ARMcc, CCR, Cmp);
3770     }
3771
3772     SDValue LHS1, LHS2;
3773     SDValue RHS1, RHS2;
3774     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3775     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3776     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3777     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3778     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3779     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3780     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3781     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3782     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3783   }
3784
3785   return SDValue();
3786 }
3787
3788 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3789   SDValue Chain = Op.getOperand(0);
3790   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3791   SDValue LHS = Op.getOperand(2);
3792   SDValue RHS = Op.getOperand(3);
3793   SDValue Dest = Op.getOperand(4);
3794   SDLoc dl(Op);
3795
3796   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3797     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3798                                                     dl);
3799
3800     // If softenSetCCOperands only returned one value, we should compare it to
3801     // zero.
3802     if (!RHS.getNode()) {
3803       RHS = DAG.getConstant(0, LHS.getValueType());
3804       CC = ISD::SETNE;
3805     }
3806   }
3807
3808   if (LHS.getValueType() == MVT::i32) {
3809     SDValue ARMcc;
3810     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3811     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3812     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3813                        Chain, Dest, ARMcc, CCR, Cmp);
3814   }
3815
3816   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3817
3818   if (getTargetMachine().Options.UnsafeFPMath &&
3819       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3820        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3821     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3822     if (Result.getNode())
3823       return Result;
3824   }
3825
3826   ARMCC::CondCodes CondCode, CondCode2;
3827   FPCCToARMCC(CC, CondCode, CondCode2);
3828
3829   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3830   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3831   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3832   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3833   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3834   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3835   if (CondCode2 != ARMCC::AL) {
3836     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3837     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3838     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3839   }
3840   return Res;
3841 }
3842
3843 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3844   SDValue Chain = Op.getOperand(0);
3845   SDValue Table = Op.getOperand(1);
3846   SDValue Index = Op.getOperand(2);
3847   SDLoc dl(Op);
3848
3849   EVT PTy = getPointerTy();
3850   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3851   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3852   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3853   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3854   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3855   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3856   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3857   if (Subtarget->isThumb2()) {
3858     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3859     // which does another jump to the destination. This also makes it easier
3860     // to translate it to TBB / TBH later.
3861     // FIXME: This might not work if the function is extremely large.
3862     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3863                        Addr, Op.getOperand(2), JTI, UId);
3864   }
3865   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3866     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3867                        MachinePointerInfo::getJumpTable(),
3868                        false, false, false, 0);
3869     Chain = Addr.getValue(1);
3870     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3871     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3872   } else {
3873     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3874                        MachinePointerInfo::getJumpTable(),
3875                        false, false, false, 0);
3876     Chain = Addr.getValue(1);
3877     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3878   }
3879 }
3880
3881 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3882   EVT VT = Op.getValueType();
3883   SDLoc dl(Op);
3884
3885   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3886     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3887       return Op;
3888     return DAG.UnrollVectorOp(Op.getNode());
3889   }
3890
3891   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3892          "Invalid type for custom lowering!");
3893   if (VT != MVT::v4i16)
3894     return DAG.UnrollVectorOp(Op.getNode());
3895
3896   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3897   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3898 }
3899
3900 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3901   EVT VT = Op.getValueType();
3902   if (VT.isVector())
3903     return LowerVectorFP_TO_INT(Op, DAG);
3904
3905   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3906     RTLIB::Libcall LC;
3907     if (Op.getOpcode() == ISD::FP_TO_SINT)
3908       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3909                               Op.getValueType());
3910     else
3911       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3912                               Op.getValueType());
3913     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3914                        /*isSigned*/ false, SDLoc(Op)).first;
3915   }
3916
3917   SDLoc dl(Op);
3918   unsigned Opc;
3919
3920   switch (Op.getOpcode()) {
3921   default: llvm_unreachable("Invalid opcode!");
3922   case ISD::FP_TO_SINT:
3923     Opc = ARMISD::FTOSI;
3924     break;
3925   case ISD::FP_TO_UINT:
3926     Opc = ARMISD::FTOUI;
3927     break;
3928   }
3929   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3930   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3931 }
3932
3933 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3934   EVT VT = Op.getValueType();
3935   SDLoc dl(Op);
3936
3937   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3938     if (VT.getVectorElementType() == MVT::f32)
3939       return Op;
3940     return DAG.UnrollVectorOp(Op.getNode());
3941   }
3942
3943   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3944          "Invalid type for custom lowering!");
3945   if (VT != MVT::v4f32)
3946     return DAG.UnrollVectorOp(Op.getNode());
3947
3948   unsigned CastOpc;
3949   unsigned Opc;
3950   switch (Op.getOpcode()) {
3951   default: llvm_unreachable("Invalid opcode!");
3952   case ISD::SINT_TO_FP:
3953     CastOpc = ISD::SIGN_EXTEND;
3954     Opc = ISD::SINT_TO_FP;
3955     break;
3956   case ISD::UINT_TO_FP:
3957     CastOpc = ISD::ZERO_EXTEND;
3958     Opc = ISD::UINT_TO_FP;
3959     break;
3960   }
3961
3962   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3963   return DAG.getNode(Opc, dl, VT, Op);
3964 }
3965
3966 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3967   EVT VT = Op.getValueType();
3968   if (VT.isVector())
3969     return LowerVectorINT_TO_FP(Op, DAG);
3970
3971   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3972     RTLIB::Libcall LC;
3973     if (Op.getOpcode() == ISD::SINT_TO_FP)
3974       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3975                               Op.getValueType());
3976     else
3977       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3978                               Op.getValueType());
3979     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3980                        /*isSigned*/ false, SDLoc(Op)).first;
3981   }
3982
3983   SDLoc dl(Op);
3984   unsigned Opc;
3985
3986   switch (Op.getOpcode()) {
3987   default: llvm_unreachable("Invalid opcode!");
3988   case ISD::SINT_TO_FP:
3989     Opc = ARMISD::SITOF;
3990     break;
3991   case ISD::UINT_TO_FP:
3992     Opc = ARMISD::UITOF;
3993     break;
3994   }
3995
3996   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3997   return DAG.getNode(Opc, dl, VT, Op);
3998 }
3999
4000 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4001   // Implement fcopysign with a fabs and a conditional fneg.
4002   SDValue Tmp0 = Op.getOperand(0);
4003   SDValue Tmp1 = Op.getOperand(1);
4004   SDLoc dl(Op);
4005   EVT VT = Op.getValueType();
4006   EVT SrcVT = Tmp1.getValueType();
4007   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4008     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4009   bool UseNEON = !InGPR && Subtarget->hasNEON();
4010
4011   if (UseNEON) {
4012     // Use VBSL to copy the sign bit.
4013     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4014     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4015                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4016     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4017     if (VT == MVT::f64)
4018       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4019                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4020                          DAG.getConstant(32, MVT::i32));
4021     else /*if (VT == MVT::f32)*/
4022       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4023     if (SrcVT == MVT::f32) {
4024       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4025       if (VT == MVT::f64)
4026         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4027                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4028                            DAG.getConstant(32, MVT::i32));
4029     } else if (VT == MVT::f32)
4030       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4031                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4032                          DAG.getConstant(32, MVT::i32));
4033     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4034     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4035
4036     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4037                                             MVT::i32);
4038     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4039     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4040                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4041
4042     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4043                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4044                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4045     if (VT == MVT::f32) {
4046       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4047       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4048                         DAG.getConstant(0, MVT::i32));
4049     } else {
4050       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4051     }
4052
4053     return Res;
4054   }
4055
4056   // Bitcast operand 1 to i32.
4057   if (SrcVT == MVT::f64)
4058     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4059                        Tmp1).getValue(1);
4060   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4061
4062   // Or in the signbit with integer operations.
4063   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4064   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4065   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4066   if (VT == MVT::f32) {
4067     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4068                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4069     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4070                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4071   }
4072
4073   // f64: Or the high part with signbit and then combine two parts.
4074   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4075                      Tmp0);
4076   SDValue Lo = Tmp0.getValue(0);
4077   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4078   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4079   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4080 }
4081
4082 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4083   MachineFunction &MF = DAG.getMachineFunction();
4084   MachineFrameInfo *MFI = MF.getFrameInfo();
4085   MFI->setReturnAddressIsTaken(true);
4086
4087   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4088     return SDValue();
4089
4090   EVT VT = Op.getValueType();
4091   SDLoc dl(Op);
4092   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4093   if (Depth) {
4094     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4095     SDValue Offset = DAG.getConstant(4, MVT::i32);
4096     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4097                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4098                        MachinePointerInfo(), false, false, false, 0);
4099   }
4100
4101   // Return LR, which contains the return address. Mark it an implicit live-in.
4102   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4103   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4104 }
4105
4106 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4107   const ARMBaseRegisterInfo &ARI =
4108     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4109   MachineFunction &MF = DAG.getMachineFunction();
4110   MachineFrameInfo *MFI = MF.getFrameInfo();
4111   MFI->setFrameAddressIsTaken(true);
4112
4113   EVT VT = Op.getValueType();
4114   SDLoc dl(Op);  // FIXME probably not meaningful
4115   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4116   unsigned FrameReg = ARI.getFrameRegister(MF);
4117   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4118   while (Depth--)
4119     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4120                             MachinePointerInfo(),
4121                             false, false, false, 0);
4122   return FrameAddr;
4123 }
4124
4125 // FIXME? Maybe this could be a TableGen attribute on some registers and
4126 // this table could be generated automatically from RegInfo.
4127 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4128                                               EVT VT) const {
4129   unsigned Reg = StringSwitch<unsigned>(RegName)
4130                        .Case("sp", ARM::SP)
4131                        .Default(0);
4132   if (Reg)
4133     return Reg;
4134   report_fatal_error("Invalid register name global variable");
4135 }
4136
4137 /// ExpandBITCAST - If the target supports VFP, this function is called to
4138 /// expand a bit convert where either the source or destination type is i64 to
4139 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4140 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4141 /// vectors), since the legalizer won't know what to do with that.
4142 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4144   SDLoc dl(N);
4145   SDValue Op = N->getOperand(0);
4146
4147   // This function is only supposed to be called for i64 types, either as the
4148   // source or destination of the bit convert.
4149   EVT SrcVT = Op.getValueType();
4150   EVT DstVT = N->getValueType(0);
4151   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4152          "ExpandBITCAST called for non-i64 type");
4153
4154   // Turn i64->f64 into VMOVDRR.
4155   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4156     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4157                              DAG.getConstant(0, MVT::i32));
4158     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4159                              DAG.getConstant(1, MVT::i32));
4160     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4161                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4162   }
4163
4164   // Turn f64->i64 into VMOVRRD.
4165   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4166     SDValue Cvt;
4167     if (TLI.isBigEndian() && SrcVT.isVector() &&
4168         SrcVT.getVectorNumElements() > 1)
4169       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4170                         DAG.getVTList(MVT::i32, MVT::i32),
4171                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4172     else
4173       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4174                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4175     // Merge the pieces into a single i64 value.
4176     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4177   }
4178
4179   return SDValue();
4180 }
4181
4182 /// getZeroVector - Returns a vector of specified type with all zero elements.
4183 /// Zero vectors are used to represent vector negation and in those cases
4184 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4185 /// not support i64 elements, so sometimes the zero vectors will need to be
4186 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4187 /// zero vector.
4188 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4189   assert(VT.isVector() && "Expected a vector type");
4190   // The canonical modified immediate encoding of a zero vector is....0!
4191   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4192   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4193   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4194   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4195 }
4196
4197 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4198 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4199 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4200                                                 SelectionDAG &DAG) const {
4201   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4202   EVT VT = Op.getValueType();
4203   unsigned VTBits = VT.getSizeInBits();
4204   SDLoc dl(Op);
4205   SDValue ShOpLo = Op.getOperand(0);
4206   SDValue ShOpHi = Op.getOperand(1);
4207   SDValue ShAmt  = Op.getOperand(2);
4208   SDValue ARMcc;
4209   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4210
4211   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4212
4213   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4214                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4215   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4216   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4217                                    DAG.getConstant(VTBits, MVT::i32));
4218   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4219   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4220   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4221
4222   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4223   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4224                           ARMcc, DAG, dl);
4225   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4226   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4227                            CCR, Cmp);
4228
4229   SDValue Ops[2] = { Lo, Hi };
4230   return DAG.getMergeValues(Ops, dl);
4231 }
4232
4233 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4234 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4235 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4236                                                SelectionDAG &DAG) const {
4237   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4238   EVT VT = Op.getValueType();
4239   unsigned VTBits = VT.getSizeInBits();
4240   SDLoc dl(Op);
4241   SDValue ShOpLo = Op.getOperand(0);
4242   SDValue ShOpHi = Op.getOperand(1);
4243   SDValue ShAmt  = Op.getOperand(2);
4244   SDValue ARMcc;
4245
4246   assert(Op.getOpcode() == ISD::SHL_PARTS);
4247   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4248                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4249   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4250   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4251                                    DAG.getConstant(VTBits, MVT::i32));
4252   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4253   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4254
4255   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4256   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4257   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4258                           ARMcc, DAG, dl);
4259   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4260   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4261                            CCR, Cmp);
4262
4263   SDValue Ops[2] = { Lo, Hi };
4264   return DAG.getMergeValues(Ops, dl);
4265 }
4266
4267 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4268                                             SelectionDAG &DAG) const {
4269   // The rounding mode is in bits 23:22 of the FPSCR.
4270   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4271   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4272   // so that the shift + and get folded into a bitfield extract.
4273   SDLoc dl(Op);
4274   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4275                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4276                                               MVT::i32));
4277   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4278                                   DAG.getConstant(1U << 22, MVT::i32));
4279   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4280                               DAG.getConstant(22, MVT::i32));
4281   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4282                      DAG.getConstant(3, MVT::i32));
4283 }
4284
4285 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4286                          const ARMSubtarget *ST) {
4287   EVT VT = N->getValueType(0);
4288   SDLoc dl(N);
4289
4290   if (!ST->hasV6T2Ops())
4291     return SDValue();
4292
4293   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4294   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4295 }
4296
4297 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4298 /// for each 16-bit element from operand, repeated.  The basic idea is to
4299 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4300 ///
4301 /// Trace for v4i16:
4302 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4303 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4304 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4305 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4306 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4307 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4308 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4309 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4310 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4311   EVT VT = N->getValueType(0);
4312   SDLoc DL(N);
4313
4314   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4315   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4316   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4317   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4318   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4319   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4320 }
4321
4322 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4323 /// bit-count for each 16-bit element from the operand.  We need slightly
4324 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4325 /// 64/128-bit registers.
4326 ///
4327 /// Trace for v4i16:
4328 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4329 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4330 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4331 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4332 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4333   EVT VT = N->getValueType(0);
4334   SDLoc DL(N);
4335
4336   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4337   if (VT.is64BitVector()) {
4338     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4339     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4340                        DAG.getIntPtrConstant(0));
4341   } else {
4342     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4343                                     BitCounts, DAG.getIntPtrConstant(0));
4344     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4345   }
4346 }
4347
4348 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4349 /// bit-count for each 32-bit element from the operand.  The idea here is
4350 /// to split the vector into 16-bit elements, leverage the 16-bit count
4351 /// routine, and then combine the results.
4352 ///
4353 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4354 /// input    = [v0    v1    ] (vi: 32-bit elements)
4355 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4356 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4357 /// vrev: N0 = [k1 k0 k3 k2 ]
4358 ///            [k0 k1 k2 k3 ]
4359 ///       N1 =+[k1 k0 k3 k2 ]
4360 ///            [k0 k2 k1 k3 ]
4361 ///       N2 =+[k1 k3 k0 k2 ]
4362 ///            [k0    k2    k1    k3    ]
4363 /// Extended =+[k1    k3    k0    k2    ]
4364 ///            [k0    k2    ]
4365 /// Extracted=+[k1    k3    ]
4366 ///
4367 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4368   EVT VT = N->getValueType(0);
4369   SDLoc DL(N);
4370
4371   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4372
4373   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4374   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4375   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4376   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4377   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4378
4379   if (VT.is64BitVector()) {
4380     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4381     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4382                        DAG.getIntPtrConstant(0));
4383   } else {
4384     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4385                                     DAG.getIntPtrConstant(0));
4386     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4387   }
4388 }
4389
4390 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4391                           const ARMSubtarget *ST) {
4392   EVT VT = N->getValueType(0);
4393
4394   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4395   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4396           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4397          "Unexpected type for custom ctpop lowering");
4398
4399   if (VT.getVectorElementType() == MVT::i32)
4400     return lowerCTPOP32BitElements(N, DAG);
4401   else
4402     return lowerCTPOP16BitElements(N, DAG);
4403 }
4404
4405 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4406                           const ARMSubtarget *ST) {
4407   EVT VT = N->getValueType(0);
4408   SDLoc dl(N);
4409
4410   if (!VT.isVector())
4411     return SDValue();
4412
4413   // Lower vector shifts on NEON to use VSHL.
4414   assert(ST->hasNEON() && "unexpected vector shift");
4415
4416   // Left shifts translate directly to the vshiftu intrinsic.
4417   if (N->getOpcode() == ISD::SHL)
4418     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4419                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4420                        N->getOperand(0), N->getOperand(1));
4421
4422   assert((N->getOpcode() == ISD::SRA ||
4423           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4424
4425   // NEON uses the same intrinsics for both left and right shifts.  For
4426   // right shifts, the shift amounts are negative, so negate the vector of
4427   // shift amounts.
4428   EVT ShiftVT = N->getOperand(1).getValueType();
4429   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4430                                      getZeroVector(ShiftVT, DAG, dl),
4431                                      N->getOperand(1));
4432   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4433                              Intrinsic::arm_neon_vshifts :
4434                              Intrinsic::arm_neon_vshiftu);
4435   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4436                      DAG.getConstant(vshiftInt, MVT::i32),
4437                      N->getOperand(0), NegatedCount);
4438 }
4439
4440 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4441                                 const ARMSubtarget *ST) {
4442   EVT VT = N->getValueType(0);
4443   SDLoc dl(N);
4444
4445   // We can get here for a node like i32 = ISD::SHL i32, i64
4446   if (VT != MVT::i64)
4447     return SDValue();
4448
4449   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4450          "Unknown shift to lower!");
4451
4452   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4453   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4454       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4455     return SDValue();
4456
4457   // If we are in thumb mode, we don't have RRX.
4458   if (ST->isThumb1Only()) return SDValue();
4459
4460   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4461   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4462                            DAG.getConstant(0, MVT::i32));
4463   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4464                            DAG.getConstant(1, MVT::i32));
4465
4466   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4467   // captures the result into a carry flag.
4468   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4469   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4470
4471   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4472   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4473
4474   // Merge the pieces into a single i64 value.
4475  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4476 }
4477
4478 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4479   SDValue TmpOp0, TmpOp1;
4480   bool Invert = false;
4481   bool Swap = false;
4482   unsigned Opc = 0;
4483
4484   SDValue Op0 = Op.getOperand(0);
4485   SDValue Op1 = Op.getOperand(1);
4486   SDValue CC = Op.getOperand(2);
4487   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4488   EVT VT = Op.getValueType();
4489   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4490   SDLoc dl(Op);
4491
4492   if (Op1.getValueType().isFloatingPoint()) {
4493     switch (SetCCOpcode) {
4494     default: llvm_unreachable("Illegal FP comparison");
4495     case ISD::SETUNE:
4496     case ISD::SETNE:  Invert = true; // Fallthrough
4497     case ISD::SETOEQ:
4498     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4499     case ISD::SETOLT:
4500     case ISD::SETLT: Swap = true; // Fallthrough
4501     case ISD::SETOGT:
4502     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4503     case ISD::SETOLE:
4504     case ISD::SETLE:  Swap = true; // Fallthrough
4505     case ISD::SETOGE:
4506     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4507     case ISD::SETUGE: Swap = true; // Fallthrough
4508     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4509     case ISD::SETUGT: Swap = true; // Fallthrough
4510     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4511     case ISD::SETUEQ: Invert = true; // Fallthrough
4512     case ISD::SETONE:
4513       // Expand this to (OLT | OGT).
4514       TmpOp0 = Op0;
4515       TmpOp1 = Op1;
4516       Opc = ISD::OR;
4517       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4518       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4519       break;
4520     case ISD::SETUO: Invert = true; // Fallthrough
4521     case ISD::SETO:
4522       // Expand this to (OLT | OGE).
4523       TmpOp0 = Op0;
4524       TmpOp1 = Op1;
4525       Opc = ISD::OR;
4526       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4527       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4528       break;
4529     }
4530   } else {
4531     // Integer comparisons.
4532     switch (SetCCOpcode) {
4533     default: llvm_unreachable("Illegal integer comparison");
4534     case ISD::SETNE:  Invert = true;
4535     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4536     case ISD::SETLT:  Swap = true;
4537     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4538     case ISD::SETLE:  Swap = true;
4539     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4540     case ISD::SETULT: Swap = true;
4541     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4542     case ISD::SETULE: Swap = true;
4543     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4544     }
4545
4546     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4547     if (Opc == ARMISD::VCEQ) {
4548
4549       SDValue AndOp;
4550       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4551         AndOp = Op0;
4552       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4553         AndOp = Op1;
4554
4555       // Ignore bitconvert.
4556       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4557         AndOp = AndOp.getOperand(0);
4558
4559       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4560         Opc = ARMISD::VTST;
4561         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4562         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4563         Invert = !Invert;
4564       }
4565     }
4566   }
4567
4568   if (Swap)
4569     std::swap(Op0, Op1);
4570
4571   // If one of the operands is a constant vector zero, attempt to fold the
4572   // comparison to a specialized compare-against-zero form.
4573   SDValue SingleOp;
4574   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4575     SingleOp = Op0;
4576   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4577     if (Opc == ARMISD::VCGE)
4578       Opc = ARMISD::VCLEZ;
4579     else if (Opc == ARMISD::VCGT)
4580       Opc = ARMISD::VCLTZ;
4581     SingleOp = Op1;
4582   }
4583
4584   SDValue Result;
4585   if (SingleOp.getNode()) {
4586     switch (Opc) {
4587     case ARMISD::VCEQ:
4588       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4589     case ARMISD::VCGE:
4590       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4591     case ARMISD::VCLEZ:
4592       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4593     case ARMISD::VCGT:
4594       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4595     case ARMISD::VCLTZ:
4596       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4597     default:
4598       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4599     }
4600   } else {
4601      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4602   }
4603
4604   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4605
4606   if (Invert)
4607     Result = DAG.getNOT(dl, Result, VT);
4608
4609   return Result;
4610 }
4611
4612 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4613 /// valid vector constant for a NEON instruction with a "modified immediate"
4614 /// operand (e.g., VMOV).  If so, return the encoded value.
4615 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4616                                  unsigned SplatBitSize, SelectionDAG &DAG,
4617                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4618   unsigned OpCmode, Imm;
4619
4620   // SplatBitSize is set to the smallest size that splats the vector, so a
4621   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4622   // immediate instructions others than VMOV do not support the 8-bit encoding
4623   // of a zero vector, and the default encoding of zero is supposed to be the
4624   // 32-bit version.
4625   if (SplatBits == 0)
4626     SplatBitSize = 32;
4627
4628   switch (SplatBitSize) {
4629   case 8:
4630     if (type != VMOVModImm)
4631       return SDValue();
4632     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4633     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4634     OpCmode = 0xe;
4635     Imm = SplatBits;
4636     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4637     break;
4638
4639   case 16:
4640     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4641     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4642     if ((SplatBits & ~0xff) == 0) {
4643       // Value = 0x00nn: Op=x, Cmode=100x.
4644       OpCmode = 0x8;
4645       Imm = SplatBits;
4646       break;
4647     }
4648     if ((SplatBits & ~0xff00) == 0) {
4649       // Value = 0xnn00: Op=x, Cmode=101x.
4650       OpCmode = 0xa;
4651       Imm = SplatBits >> 8;
4652       break;
4653     }
4654     return SDValue();
4655
4656   case 32:
4657     // NEON's 32-bit VMOV supports splat values where:
4658     // * only one byte is nonzero, or
4659     // * the least significant byte is 0xff and the second byte is nonzero, or
4660     // * the least significant 2 bytes are 0xff and the third is nonzero.
4661     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4662     if ((SplatBits & ~0xff) == 0) {
4663       // Value = 0x000000nn: Op=x, Cmode=000x.
4664       OpCmode = 0;
4665       Imm = SplatBits;
4666       break;
4667     }
4668     if ((SplatBits & ~0xff00) == 0) {
4669       // Value = 0x0000nn00: Op=x, Cmode=001x.
4670       OpCmode = 0x2;
4671       Imm = SplatBits >> 8;
4672       break;
4673     }
4674     if ((SplatBits & ~0xff0000) == 0) {
4675       // Value = 0x00nn0000: Op=x, Cmode=010x.
4676       OpCmode = 0x4;
4677       Imm = SplatBits >> 16;
4678       break;
4679     }
4680     if ((SplatBits & ~0xff000000) == 0) {
4681       // Value = 0xnn000000: Op=x, Cmode=011x.
4682       OpCmode = 0x6;
4683       Imm = SplatBits >> 24;
4684       break;
4685     }
4686
4687     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4688     if (type == OtherModImm) return SDValue();
4689
4690     if ((SplatBits & ~0xffff) == 0 &&
4691         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4692       // Value = 0x0000nnff: Op=x, Cmode=1100.
4693       OpCmode = 0xc;
4694       Imm = SplatBits >> 8;
4695       break;
4696     }
4697
4698     if ((SplatBits & ~0xffffff) == 0 &&
4699         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4700       // Value = 0x00nnffff: Op=x, Cmode=1101.
4701       OpCmode = 0xd;
4702       Imm = SplatBits >> 16;
4703       break;
4704     }
4705
4706     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4707     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4708     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4709     // and fall through here to test for a valid 64-bit splat.  But, then the
4710     // caller would also need to check and handle the change in size.
4711     return SDValue();
4712
4713   case 64: {
4714     if (type != VMOVModImm)
4715       return SDValue();
4716     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4717     uint64_t BitMask = 0xff;
4718     uint64_t Val = 0;
4719     unsigned ImmMask = 1;
4720     Imm = 0;
4721     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4722       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4723         Val |= BitMask;
4724         Imm |= ImmMask;
4725       } else if ((SplatBits & BitMask) != 0) {
4726         return SDValue();
4727       }
4728       BitMask <<= 8;
4729       ImmMask <<= 1;
4730     }
4731
4732     if (DAG.getTargetLoweringInfo().isBigEndian())
4733       // swap higher and lower 32 bit word
4734       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4735
4736     // Op=1, Cmode=1110.
4737     OpCmode = 0x1e;
4738     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4739     break;
4740   }
4741
4742   default:
4743     llvm_unreachable("unexpected size for isNEONModifiedImm");
4744   }
4745
4746   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4747   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4748 }
4749
4750 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4751                                            const ARMSubtarget *ST) const {
4752   if (!ST->hasVFP3())
4753     return SDValue();
4754
4755   bool IsDouble = Op.getValueType() == MVT::f64;
4756   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4757
4758   // Use the default (constant pool) lowering for double constants when we have
4759   // an SP-only FPU
4760   if (IsDouble && Subtarget->isFPOnlySP())
4761     return SDValue();
4762
4763   // Try splatting with a VMOV.f32...
4764   APFloat FPVal = CFP->getValueAPF();
4765   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4766
4767   if (ImmVal != -1) {
4768     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4769       // We have code in place to select a valid ConstantFP already, no need to
4770       // do any mangling.
4771       return Op;
4772     }
4773
4774     // It's a float and we are trying to use NEON operations where
4775     // possible. Lower it to a splat followed by an extract.
4776     SDLoc DL(Op);
4777     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4778     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4779                                       NewVal);
4780     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4781                        DAG.getConstant(0, MVT::i32));
4782   }
4783
4784   // The rest of our options are NEON only, make sure that's allowed before
4785   // proceeding..
4786   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4787     return SDValue();
4788
4789   EVT VMovVT;
4790   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4791
4792   // It wouldn't really be worth bothering for doubles except for one very
4793   // important value, which does happen to match: 0.0. So make sure we don't do
4794   // anything stupid.
4795   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4796     return SDValue();
4797
4798   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4799   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4800                                      false, VMOVModImm);
4801   if (NewVal != SDValue()) {
4802     SDLoc DL(Op);
4803     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4804                                       NewVal);
4805     if (IsDouble)
4806       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4807
4808     // It's a float: cast and extract a vector element.
4809     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4810                                        VecConstant);
4811     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4812                        DAG.getConstant(0, MVT::i32));
4813   }
4814
4815   // Finally, try a VMVN.i32
4816   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4817                              false, VMVNModImm);
4818   if (NewVal != SDValue()) {
4819     SDLoc DL(Op);
4820     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4821
4822     if (IsDouble)
4823       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4824
4825     // It's a float: cast and extract a vector element.
4826     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4827                                        VecConstant);
4828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4829                        DAG.getConstant(0, MVT::i32));
4830   }
4831
4832   return SDValue();
4833 }
4834
4835 // check if an VEXT instruction can handle the shuffle mask when the
4836 // vector sources of the shuffle are the same.
4837 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4838   unsigned NumElts = VT.getVectorNumElements();
4839
4840   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4841   if (M[0] < 0)
4842     return false;
4843
4844   Imm = M[0];
4845
4846   // If this is a VEXT shuffle, the immediate value is the index of the first
4847   // element.  The other shuffle indices must be the successive elements after
4848   // the first one.
4849   unsigned ExpectedElt = Imm;
4850   for (unsigned i = 1; i < NumElts; ++i) {
4851     // Increment the expected index.  If it wraps around, just follow it
4852     // back to index zero and keep going.
4853     ++ExpectedElt;
4854     if (ExpectedElt == NumElts)
4855       ExpectedElt = 0;
4856
4857     if (M[i] < 0) continue; // ignore UNDEF indices
4858     if (ExpectedElt != static_cast<unsigned>(M[i]))
4859       return false;
4860   }
4861
4862   return true;
4863 }
4864
4865
4866 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4867                        bool &ReverseVEXT, unsigned &Imm) {
4868   unsigned NumElts = VT.getVectorNumElements();
4869   ReverseVEXT = false;
4870
4871   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4872   if (M[0] < 0)
4873     return false;
4874
4875   Imm = M[0];
4876
4877   // If this is a VEXT shuffle, the immediate value is the index of the first
4878   // element.  The other shuffle indices must be the successive elements after
4879   // the first one.
4880   unsigned ExpectedElt = Imm;
4881   for (unsigned i = 1; i < NumElts; ++i) {
4882     // Increment the expected index.  If it wraps around, it may still be
4883     // a VEXT but the source vectors must be swapped.
4884     ExpectedElt += 1;
4885     if (ExpectedElt == NumElts * 2) {
4886       ExpectedElt = 0;
4887       ReverseVEXT = true;
4888     }
4889
4890     if (M[i] < 0) continue; // ignore UNDEF indices
4891     if (ExpectedElt != static_cast<unsigned>(M[i]))
4892       return false;
4893   }
4894
4895   // Adjust the index value if the source operands will be swapped.
4896   if (ReverseVEXT)
4897     Imm -= NumElts;
4898
4899   return true;
4900 }
4901
4902 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4903 /// instruction with the specified blocksize.  (The order of the elements
4904 /// within each block of the vector is reversed.)
4905 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4906   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4907          "Only possible block sizes for VREV are: 16, 32, 64");
4908
4909   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4910   if (EltSz == 64)
4911     return false;
4912
4913   unsigned NumElts = VT.getVectorNumElements();
4914   unsigned BlockElts = M[0] + 1;
4915   // If the first shuffle index is UNDEF, be optimistic.
4916   if (M[0] < 0)
4917     BlockElts = BlockSize / EltSz;
4918
4919   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4920     return false;
4921
4922   for (unsigned i = 0; i < NumElts; ++i) {
4923     if (M[i] < 0) continue; // ignore UNDEF indices
4924     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4925       return false;
4926   }
4927
4928   return true;
4929 }
4930
4931 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4932   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4933   // range, then 0 is placed into the resulting vector. So pretty much any mask
4934   // of 8 elements can work here.
4935   return VT == MVT::v8i8 && M.size() == 8;
4936 }
4937
4938 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4939   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4940   if (EltSz == 64)
4941     return false;
4942
4943   unsigned NumElts = VT.getVectorNumElements();
4944   WhichResult = (M[0] == 0 ? 0 : 1);
4945   for (unsigned i = 0; i < NumElts; i += 2) {
4946     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4947         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4948       return false;
4949   }
4950   return true;
4951 }
4952
4953 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4954 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4955 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4956 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4957   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4958   if (EltSz == 64)
4959     return false;
4960
4961   unsigned NumElts = VT.getVectorNumElements();
4962   WhichResult = (M[0] == 0 ? 0 : 1);
4963   for (unsigned i = 0; i < NumElts; i += 2) {
4964     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4965         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4966       return false;
4967   }
4968   return true;
4969 }
4970
4971 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4972   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4973   if (EltSz == 64)
4974     return false;
4975
4976   unsigned NumElts = VT.getVectorNumElements();
4977   WhichResult = (M[0] == 0 ? 0 : 1);
4978   for (unsigned i = 0; i != NumElts; ++i) {
4979     if (M[i] < 0) continue; // ignore UNDEF indices
4980     if ((unsigned) M[i] != 2 * i + WhichResult)
4981       return false;
4982   }
4983
4984   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4985   if (VT.is64BitVector() && EltSz == 32)
4986     return false;
4987
4988   return true;
4989 }
4990
4991 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4992 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4993 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4994 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4995   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4996   if (EltSz == 64)
4997     return false;
4998
4999   unsigned Half = VT.getVectorNumElements() / 2;
5000   WhichResult = (M[0] == 0 ? 0 : 1);
5001   for (unsigned j = 0; j != 2; ++j) {
5002     unsigned Idx = WhichResult;
5003     for (unsigned i = 0; i != Half; ++i) {
5004       int MIdx = M[i + j * Half];
5005       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5006         return false;
5007       Idx += 2;
5008     }
5009   }
5010
5011   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5012   if (VT.is64BitVector() && EltSz == 32)
5013     return false;
5014
5015   return true;
5016 }
5017
5018 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5019   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5020   if (EltSz == 64)
5021     return false;
5022
5023   unsigned NumElts = VT.getVectorNumElements();
5024   WhichResult = (M[0] == 0 ? 0 : 1);
5025   unsigned Idx = WhichResult * NumElts / 2;
5026   for (unsigned i = 0; i != NumElts; i += 2) {
5027     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5028         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5029       return false;
5030     Idx += 1;
5031   }
5032
5033   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5034   if (VT.is64BitVector() && EltSz == 32)
5035     return false;
5036
5037   return true;
5038 }
5039
5040 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5041 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5042 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5043 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5044   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5045   if (EltSz == 64)
5046     return false;
5047
5048   unsigned NumElts = VT.getVectorNumElements();
5049   WhichResult = (M[0] == 0 ? 0 : 1);
5050   unsigned Idx = WhichResult * NumElts / 2;
5051   for (unsigned i = 0; i != NumElts; i += 2) {
5052     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5053         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5054       return false;
5055     Idx += 1;
5056   }
5057
5058   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5059   if (VT.is64BitVector() && EltSz == 32)
5060     return false;
5061
5062   return true;
5063 }
5064
5065 /// \return true if this is a reverse operation on an vector.
5066 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5067   unsigned NumElts = VT.getVectorNumElements();
5068   // Make sure the mask has the right size.
5069   if (NumElts != M.size())
5070       return false;
5071
5072   // Look for <15, ..., 3, -1, 1, 0>.
5073   for (unsigned i = 0; i != NumElts; ++i)
5074     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5075       return false;
5076
5077   return true;
5078 }
5079
5080 // If N is an integer constant that can be moved into a register in one
5081 // instruction, return an SDValue of such a constant (will become a MOV
5082 // instruction).  Otherwise return null.
5083 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5084                                      const ARMSubtarget *ST, SDLoc dl) {
5085   uint64_t Val;
5086   if (!isa<ConstantSDNode>(N))
5087     return SDValue();
5088   Val = cast<ConstantSDNode>(N)->getZExtValue();
5089
5090   if (ST->isThumb1Only()) {
5091     if (Val <= 255 || ~Val <= 255)
5092       return DAG.getConstant(Val, MVT::i32);
5093   } else {
5094     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5095       return DAG.getConstant(Val, MVT::i32);
5096   }
5097   return SDValue();
5098 }
5099
5100 // If this is a case we can't handle, return null and let the default
5101 // expansion code take care of it.
5102 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5103                                              const ARMSubtarget *ST) const {
5104   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5105   SDLoc dl(Op);
5106   EVT VT = Op.getValueType();
5107
5108   APInt SplatBits, SplatUndef;
5109   unsigned SplatBitSize;
5110   bool HasAnyUndefs;
5111   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5112     if (SplatBitSize <= 64) {
5113       // Check if an immediate VMOV works.
5114       EVT VmovVT;
5115       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5116                                       SplatUndef.getZExtValue(), SplatBitSize,
5117                                       DAG, VmovVT, VT.is128BitVector(),
5118                                       VMOVModImm);
5119       if (Val.getNode()) {
5120         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5121         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5122       }
5123
5124       // Try an immediate VMVN.
5125       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5126       Val = isNEONModifiedImm(NegatedImm,
5127                                       SplatUndef.getZExtValue(), SplatBitSize,
5128                                       DAG, VmovVT, VT.is128BitVector(),
5129                                       VMVNModImm);
5130       if (Val.getNode()) {
5131         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5132         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5133       }
5134
5135       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5136       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5137         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5138         if (ImmVal != -1) {
5139           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5140           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5141         }
5142       }
5143     }
5144   }
5145
5146   // Scan through the operands to see if only one value is used.
5147   //
5148   // As an optimisation, even if more than one value is used it may be more
5149   // profitable to splat with one value then change some lanes.
5150   //
5151   // Heuristically we decide to do this if the vector has a "dominant" value,
5152   // defined as splatted to more than half of the lanes.
5153   unsigned NumElts = VT.getVectorNumElements();
5154   bool isOnlyLowElement = true;
5155   bool usesOnlyOneValue = true;
5156   bool hasDominantValue = false;
5157   bool isConstant = true;
5158
5159   // Map of the number of times a particular SDValue appears in the
5160   // element list.
5161   DenseMap<SDValue, unsigned> ValueCounts;
5162   SDValue Value;
5163   for (unsigned i = 0; i < NumElts; ++i) {
5164     SDValue V = Op.getOperand(i);
5165     if (V.getOpcode() == ISD::UNDEF)
5166       continue;
5167     if (i > 0)
5168       isOnlyLowElement = false;
5169     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5170       isConstant = false;
5171
5172     ValueCounts.insert(std::make_pair(V, 0));
5173     unsigned &Count = ValueCounts[V];
5174
5175     // Is this value dominant? (takes up more than half of the lanes)
5176     if (++Count > (NumElts / 2)) {
5177       hasDominantValue = true;
5178       Value = V;
5179     }
5180   }
5181   if (ValueCounts.size() != 1)
5182     usesOnlyOneValue = false;
5183   if (!Value.getNode() && ValueCounts.size() > 0)
5184     Value = ValueCounts.begin()->first;
5185
5186   if (ValueCounts.size() == 0)
5187     return DAG.getUNDEF(VT);
5188
5189   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5190   // Keep going if we are hitting this case.
5191   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5192     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5193
5194   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5195
5196   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5197   // i32 and try again.
5198   if (hasDominantValue && EltSize <= 32) {
5199     if (!isConstant) {
5200       SDValue N;
5201
5202       // If we are VDUPing a value that comes directly from a vector, that will
5203       // cause an unnecessary move to and from a GPR, where instead we could
5204       // just use VDUPLANE. We can only do this if the lane being extracted
5205       // is at a constant index, as the VDUP from lane instructions only have
5206       // constant-index forms.
5207       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5208           isa<ConstantSDNode>(Value->getOperand(1))) {
5209         // We need to create a new undef vector to use for the VDUPLANE if the
5210         // size of the vector from which we get the value is different than the
5211         // size of the vector that we need to create. We will insert the element
5212         // such that the register coalescer will remove unnecessary copies.
5213         if (VT != Value->getOperand(0).getValueType()) {
5214           ConstantSDNode *constIndex;
5215           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5216           assert(constIndex && "The index is not a constant!");
5217           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5218                              VT.getVectorNumElements();
5219           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5220                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5221                         Value, DAG.getConstant(index, MVT::i32)),
5222                            DAG.getConstant(index, MVT::i32));
5223         } else
5224           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5225                         Value->getOperand(0), Value->getOperand(1));
5226       } else
5227         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5228
5229       if (!usesOnlyOneValue) {
5230         // The dominant value was splatted as 'N', but we now have to insert
5231         // all differing elements.
5232         for (unsigned I = 0; I < NumElts; ++I) {
5233           if (Op.getOperand(I) == Value)
5234             continue;
5235           SmallVector<SDValue, 3> Ops;
5236           Ops.push_back(N);
5237           Ops.push_back(Op.getOperand(I));
5238           Ops.push_back(DAG.getConstant(I, MVT::i32));
5239           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5240         }
5241       }
5242       return N;
5243     }
5244     if (VT.getVectorElementType().isFloatingPoint()) {
5245       SmallVector<SDValue, 8> Ops;
5246       for (unsigned i = 0; i < NumElts; ++i)
5247         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5248                                   Op.getOperand(i)));
5249       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5250       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5251       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5252       if (Val.getNode())
5253         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5254     }
5255     if (usesOnlyOneValue) {
5256       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5257       if (isConstant && Val.getNode())
5258         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5259     }
5260   }
5261
5262   // If all elements are constants and the case above didn't get hit, fall back
5263   // to the default expansion, which will generate a load from the constant
5264   // pool.
5265   if (isConstant)
5266     return SDValue();
5267
5268   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5269   if (NumElts >= 4) {
5270     SDValue shuffle = ReconstructShuffle(Op, DAG);
5271     if (shuffle != SDValue())
5272       return shuffle;
5273   }
5274
5275   // Vectors with 32- or 64-bit elements can be built by directly assigning
5276   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5277   // will be legalized.
5278   if (EltSize >= 32) {
5279     // Do the expansion with floating-point types, since that is what the VFP
5280     // registers are defined to use, and since i64 is not legal.
5281     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5282     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5283     SmallVector<SDValue, 8> Ops;
5284     for (unsigned i = 0; i < NumElts; ++i)
5285       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5286     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5287     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5288   }
5289
5290   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5291   // know the default expansion would otherwise fall back on something even
5292   // worse. For a vector with one or two non-undef values, that's
5293   // scalar_to_vector for the elements followed by a shuffle (provided the
5294   // shuffle is valid for the target) and materialization element by element
5295   // on the stack followed by a load for everything else.
5296   if (!isConstant && !usesOnlyOneValue) {
5297     SDValue Vec = DAG.getUNDEF(VT);
5298     for (unsigned i = 0 ; i < NumElts; ++i) {
5299       SDValue V = Op.getOperand(i);
5300       if (V.getOpcode() == ISD::UNDEF)
5301         continue;
5302       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5303       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5304     }
5305     return Vec;
5306   }
5307
5308   return SDValue();
5309 }
5310
5311 // Gather data to see if the operation can be modelled as a
5312 // shuffle in combination with VEXTs.
5313 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5314                                               SelectionDAG &DAG) const {
5315   SDLoc dl(Op);
5316   EVT VT = Op.getValueType();
5317   unsigned NumElts = VT.getVectorNumElements();
5318
5319   SmallVector<SDValue, 2> SourceVecs;
5320   SmallVector<unsigned, 2> MinElts;
5321   SmallVector<unsigned, 2> MaxElts;
5322
5323   for (unsigned i = 0; i < NumElts; ++i) {
5324     SDValue V = Op.getOperand(i);
5325     if (V.getOpcode() == ISD::UNDEF)
5326       continue;
5327     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5328       // A shuffle can only come from building a vector from various
5329       // elements of other vectors.
5330       return SDValue();
5331     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5332                VT.getVectorElementType()) {
5333       // This code doesn't know how to handle shuffles where the vector
5334       // element types do not match (this happens because type legalization
5335       // promotes the return type of EXTRACT_VECTOR_ELT).
5336       // FIXME: It might be appropriate to extend this code to handle
5337       // mismatched types.
5338       return SDValue();
5339     }
5340
5341     // Record this extraction against the appropriate vector if possible...
5342     SDValue SourceVec = V.getOperand(0);
5343     // If the element number isn't a constant, we can't effectively
5344     // analyze what's going on.
5345     if (!isa<ConstantSDNode>(V.getOperand(1)))
5346       return SDValue();
5347     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5348     bool FoundSource = false;
5349     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5350       if (SourceVecs[j] == SourceVec) {
5351         if (MinElts[j] > EltNo)
5352           MinElts[j] = EltNo;
5353         if (MaxElts[j] < EltNo)
5354           MaxElts[j] = EltNo;
5355         FoundSource = true;
5356         break;
5357       }
5358     }
5359
5360     // Or record a new source if not...
5361     if (!FoundSource) {
5362       SourceVecs.push_back(SourceVec);
5363       MinElts.push_back(EltNo);
5364       MaxElts.push_back(EltNo);
5365     }
5366   }
5367
5368   // Currently only do something sane when at most two source vectors
5369   // involved.
5370   if (SourceVecs.size() > 2)
5371     return SDValue();
5372
5373   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5374   int VEXTOffsets[2] = {0, 0};
5375
5376   // This loop extracts the usage patterns of the source vectors
5377   // and prepares appropriate SDValues for a shuffle if possible.
5378   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5379     if (SourceVecs[i].getValueType() == VT) {
5380       // No VEXT necessary
5381       ShuffleSrcs[i] = SourceVecs[i];
5382       VEXTOffsets[i] = 0;
5383       continue;
5384     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5385       // It probably isn't worth padding out a smaller vector just to
5386       // break it down again in a shuffle.
5387       return SDValue();
5388     }
5389
5390     // Since only 64-bit and 128-bit vectors are legal on ARM and
5391     // we've eliminated the other cases...
5392     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5393            "unexpected vector sizes in ReconstructShuffle");
5394
5395     if (MaxElts[i] - MinElts[i] >= NumElts) {
5396       // Span too large for a VEXT to cope
5397       return SDValue();
5398     }
5399
5400     if (MinElts[i] >= NumElts) {
5401       // The extraction can just take the second half
5402       VEXTOffsets[i] = NumElts;
5403       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5404                                    SourceVecs[i],
5405                                    DAG.getIntPtrConstant(NumElts));
5406     } else if (MaxElts[i] < NumElts) {
5407       // The extraction can just take the first half
5408       VEXTOffsets[i] = 0;
5409       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5410                                    SourceVecs[i],
5411                                    DAG.getIntPtrConstant(0));
5412     } else {
5413       // An actual VEXT is needed
5414       VEXTOffsets[i] = MinElts[i];
5415       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5416                                      SourceVecs[i],
5417                                      DAG.getIntPtrConstant(0));
5418       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5419                                      SourceVecs[i],
5420                                      DAG.getIntPtrConstant(NumElts));
5421       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5422                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5423     }
5424   }
5425
5426   SmallVector<int, 8> Mask;
5427
5428   for (unsigned i = 0; i < NumElts; ++i) {
5429     SDValue Entry = Op.getOperand(i);
5430     if (Entry.getOpcode() == ISD::UNDEF) {
5431       Mask.push_back(-1);
5432       continue;
5433     }
5434
5435     SDValue ExtractVec = Entry.getOperand(0);
5436     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5437                                           .getOperand(1))->getSExtValue();
5438     if (ExtractVec == SourceVecs[0]) {
5439       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5440     } else {
5441       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5442     }
5443   }
5444
5445   // Final check before we try to produce nonsense...
5446   if (isShuffleMaskLegal(Mask, VT))
5447     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5448                                 &Mask[0]);
5449
5450   return SDValue();
5451 }
5452
5453 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5454 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5455 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5456 /// are assumed to be legal.
5457 bool
5458 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5459                                       EVT VT) const {
5460   if (VT.getVectorNumElements() == 4 &&
5461       (VT.is128BitVector() || VT.is64BitVector())) {
5462     unsigned PFIndexes[4];
5463     for (unsigned i = 0; i != 4; ++i) {
5464       if (M[i] < 0)
5465         PFIndexes[i] = 8;
5466       else
5467         PFIndexes[i] = M[i];
5468     }
5469
5470     // Compute the index in the perfect shuffle table.
5471     unsigned PFTableIndex =
5472       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5473     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5474     unsigned Cost = (PFEntry >> 30);
5475
5476     if (Cost <= 4)
5477       return true;
5478   }
5479
5480   bool ReverseVEXT;
5481   unsigned Imm, WhichResult;
5482
5483   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5484   return (EltSize >= 32 ||
5485           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5486           isVREVMask(M, VT, 64) ||
5487           isVREVMask(M, VT, 32) ||
5488           isVREVMask(M, VT, 16) ||
5489           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5490           isVTBLMask(M, VT) ||
5491           isVTRNMask(M, VT, WhichResult) ||
5492           isVUZPMask(M, VT, WhichResult) ||
5493           isVZIPMask(M, VT, WhichResult) ||
5494           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5495           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5496           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5497           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5498 }
5499
5500 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5501 /// the specified operations to build the shuffle.
5502 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5503                                       SDValue RHS, SelectionDAG &DAG,
5504                                       SDLoc dl) {
5505   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5506   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5507   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5508
5509   enum {
5510     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5511     OP_VREV,
5512     OP_VDUP0,
5513     OP_VDUP1,
5514     OP_VDUP2,
5515     OP_VDUP3,
5516     OP_VEXT1,
5517     OP_VEXT2,
5518     OP_VEXT3,
5519     OP_VUZPL, // VUZP, left result
5520     OP_VUZPR, // VUZP, right result
5521     OP_VZIPL, // VZIP, left result
5522     OP_VZIPR, // VZIP, right result
5523     OP_VTRNL, // VTRN, left result
5524     OP_VTRNR  // VTRN, right result
5525   };
5526
5527   if (OpNum == OP_COPY) {
5528     if (LHSID == (1*9+2)*9+3) return LHS;
5529     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5530     return RHS;
5531   }
5532
5533   SDValue OpLHS, OpRHS;
5534   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5535   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5536   EVT VT = OpLHS.getValueType();
5537
5538   switch (OpNum) {
5539   default: llvm_unreachable("Unknown shuffle opcode!");
5540   case OP_VREV:
5541     // VREV divides the vector in half and swaps within the half.
5542     if (VT.getVectorElementType() == MVT::i32 ||
5543         VT.getVectorElementType() == MVT::f32)
5544       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5545     // vrev <4 x i16> -> VREV32
5546     if (VT.getVectorElementType() == MVT::i16)
5547       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5548     // vrev <4 x i8> -> VREV16
5549     assert(VT.getVectorElementType() == MVT::i8);
5550     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5551   case OP_VDUP0:
5552   case OP_VDUP1:
5553   case OP_VDUP2:
5554   case OP_VDUP3:
5555     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5556                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5557   case OP_VEXT1:
5558   case OP_VEXT2:
5559   case OP_VEXT3:
5560     return DAG.getNode(ARMISD::VEXT, dl, VT,
5561                        OpLHS, OpRHS,
5562                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5563   case OP_VUZPL:
5564   case OP_VUZPR:
5565     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5566                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5567   case OP_VZIPL:
5568   case OP_VZIPR:
5569     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5570                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5571   case OP_VTRNL:
5572   case OP_VTRNR:
5573     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5574                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5575   }
5576 }
5577
5578 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5579                                        ArrayRef<int> ShuffleMask,
5580                                        SelectionDAG &DAG) {
5581   // Check to see if we can use the VTBL instruction.
5582   SDValue V1 = Op.getOperand(0);
5583   SDValue V2 = Op.getOperand(1);
5584   SDLoc DL(Op);
5585
5586   SmallVector<SDValue, 8> VTBLMask;
5587   for (ArrayRef<int>::iterator
5588          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5589     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5590
5591   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5592     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5593                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5594
5595   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5596                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5597 }
5598
5599 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5600                                                       SelectionDAG &DAG) {
5601   SDLoc DL(Op);
5602   SDValue OpLHS = Op.getOperand(0);
5603   EVT VT = OpLHS.getValueType();
5604
5605   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5606          "Expect an v8i16/v16i8 type");
5607   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5608   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5609   // extract the first 8 bytes into the top double word and the last 8 bytes
5610   // into the bottom double word. The v8i16 case is similar.
5611   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5612   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5613                      DAG.getConstant(ExtractNum, MVT::i32));
5614 }
5615
5616 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5617   SDValue V1 = Op.getOperand(0);
5618   SDValue V2 = Op.getOperand(1);
5619   SDLoc dl(Op);
5620   EVT VT = Op.getValueType();
5621   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5622
5623   // Convert shuffles that are directly supported on NEON to target-specific
5624   // DAG nodes, instead of keeping them as shuffles and matching them again
5625   // during code selection.  This is more efficient and avoids the possibility
5626   // of inconsistencies between legalization and selection.
5627   // FIXME: floating-point vectors should be canonicalized to integer vectors
5628   // of the same time so that they get CSEd properly.
5629   ArrayRef<int> ShuffleMask = SVN->getMask();
5630
5631   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5632   if (EltSize <= 32) {
5633     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5634       int Lane = SVN->getSplatIndex();
5635       // If this is undef splat, generate it via "just" vdup, if possible.
5636       if (Lane == -1) Lane = 0;
5637
5638       // Test if V1 is a SCALAR_TO_VECTOR.
5639       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5640         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5641       }
5642       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5643       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5644       // reaches it).
5645       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5646           !isa<ConstantSDNode>(V1.getOperand(0))) {
5647         bool IsScalarToVector = true;
5648         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5649           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5650             IsScalarToVector = false;
5651             break;
5652           }
5653         if (IsScalarToVector)
5654           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5655       }
5656       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5657                          DAG.getConstant(Lane, MVT::i32));
5658     }
5659
5660     bool ReverseVEXT;
5661     unsigned Imm;
5662     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5663       if (ReverseVEXT)
5664         std::swap(V1, V2);
5665       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5666                          DAG.getConstant(Imm, MVT::i32));
5667     }
5668
5669     if (isVREVMask(ShuffleMask, VT, 64))
5670       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5671     if (isVREVMask(ShuffleMask, VT, 32))
5672       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5673     if (isVREVMask(ShuffleMask, VT, 16))
5674       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5675
5676     if (V2->getOpcode() == ISD::UNDEF &&
5677         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5678       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5679                          DAG.getConstant(Imm, MVT::i32));
5680     }
5681
5682     // Check for Neon shuffles that modify both input vectors in place.
5683     // If both results are used, i.e., if there are two shuffles with the same
5684     // source operands and with masks corresponding to both results of one of
5685     // these operations, DAG memoization will ensure that a single node is
5686     // used for both shuffles.
5687     unsigned WhichResult;
5688     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5689       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5690                          V1, V2).getValue(WhichResult);
5691     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5692       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5693                          V1, V2).getValue(WhichResult);
5694     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5695       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5696                          V1, V2).getValue(WhichResult);
5697
5698     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5699       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5700                          V1, V1).getValue(WhichResult);
5701     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5702       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5703                          V1, V1).getValue(WhichResult);
5704     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5705       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5706                          V1, V1).getValue(WhichResult);
5707   }
5708
5709   // If the shuffle is not directly supported and it has 4 elements, use
5710   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5711   unsigned NumElts = VT.getVectorNumElements();
5712   if (NumElts == 4) {
5713     unsigned PFIndexes[4];
5714     for (unsigned i = 0; i != 4; ++i) {
5715       if (ShuffleMask[i] < 0)
5716         PFIndexes[i] = 8;
5717       else
5718         PFIndexes[i] = ShuffleMask[i];
5719     }
5720
5721     // Compute the index in the perfect shuffle table.
5722     unsigned PFTableIndex =
5723       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5724     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5725     unsigned Cost = (PFEntry >> 30);
5726
5727     if (Cost <= 4)
5728       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5729   }
5730
5731   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5732   if (EltSize >= 32) {
5733     // Do the expansion with floating-point types, since that is what the VFP
5734     // registers are defined to use, and since i64 is not legal.
5735     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5736     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5737     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5738     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5739     SmallVector<SDValue, 8> Ops;
5740     for (unsigned i = 0; i < NumElts; ++i) {
5741       if (ShuffleMask[i] < 0)
5742         Ops.push_back(DAG.getUNDEF(EltVT));
5743       else
5744         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5745                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5746                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5747                                                   MVT::i32)));
5748     }
5749     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5750     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5751   }
5752
5753   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5754     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5755
5756   if (VT == MVT::v8i8) {
5757     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5758     if (NewOp.getNode())
5759       return NewOp;
5760   }
5761
5762   return SDValue();
5763 }
5764
5765 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5766   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5767   SDValue Lane = Op.getOperand(2);
5768   if (!isa<ConstantSDNode>(Lane))
5769     return SDValue();
5770
5771   return Op;
5772 }
5773
5774 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5775   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5776   SDValue Lane = Op.getOperand(1);
5777   if (!isa<ConstantSDNode>(Lane))
5778     return SDValue();
5779
5780   SDValue Vec = Op.getOperand(0);
5781   if (Op.getValueType() == MVT::i32 &&
5782       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5783     SDLoc dl(Op);
5784     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5785   }
5786
5787   return Op;
5788 }
5789
5790 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5791   // The only time a CONCAT_VECTORS operation can have legal types is when
5792   // two 64-bit vectors are concatenated to a 128-bit vector.
5793   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5794          "unexpected CONCAT_VECTORS");
5795   SDLoc dl(Op);
5796   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5797   SDValue Op0 = Op.getOperand(0);
5798   SDValue Op1 = Op.getOperand(1);
5799   if (Op0.getOpcode() != ISD::UNDEF)
5800     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5801                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5802                       DAG.getIntPtrConstant(0));
5803   if (Op1.getOpcode() != ISD::UNDEF)
5804     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5805                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5806                       DAG.getIntPtrConstant(1));
5807   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5808 }
5809
5810 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5811 /// element has been zero/sign-extended, depending on the isSigned parameter,
5812 /// from an integer type half its size.
5813 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5814                                    bool isSigned) {
5815   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5816   EVT VT = N->getValueType(0);
5817   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5818     SDNode *BVN = N->getOperand(0).getNode();
5819     if (BVN->getValueType(0) != MVT::v4i32 ||
5820         BVN->getOpcode() != ISD::BUILD_VECTOR)
5821       return false;
5822     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5823     unsigned HiElt = 1 - LoElt;
5824     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5825     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5826     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5827     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5828     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5829       return false;
5830     if (isSigned) {
5831       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5832           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5833         return true;
5834     } else {
5835       if (Hi0->isNullValue() && Hi1->isNullValue())
5836         return true;
5837     }
5838     return false;
5839   }
5840
5841   if (N->getOpcode() != ISD::BUILD_VECTOR)
5842     return false;
5843
5844   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5845     SDNode *Elt = N->getOperand(i).getNode();
5846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5847       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5848       unsigned HalfSize = EltSize / 2;
5849       if (isSigned) {
5850         if (!isIntN(HalfSize, C->getSExtValue()))
5851           return false;
5852       } else {
5853         if (!isUIntN(HalfSize, C->getZExtValue()))
5854           return false;
5855       }
5856       continue;
5857     }
5858     return false;
5859   }
5860
5861   return true;
5862 }
5863
5864 /// isSignExtended - Check if a node is a vector value that is sign-extended
5865 /// or a constant BUILD_VECTOR with sign-extended elements.
5866 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5867   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5868     return true;
5869   if (isExtendedBUILD_VECTOR(N, DAG, true))
5870     return true;
5871   return false;
5872 }
5873
5874 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5875 /// or a constant BUILD_VECTOR with zero-extended elements.
5876 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5877   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5878     return true;
5879   if (isExtendedBUILD_VECTOR(N, DAG, false))
5880     return true;
5881   return false;
5882 }
5883
5884 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5885   if (OrigVT.getSizeInBits() >= 64)
5886     return OrigVT;
5887
5888   assert(OrigVT.isSimple() && "Expecting a simple value type");
5889
5890   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5891   switch (OrigSimpleTy) {
5892   default: llvm_unreachable("Unexpected Vector Type");
5893   case MVT::v2i8:
5894   case MVT::v2i16:
5895      return MVT::v2i32;
5896   case MVT::v4i8:
5897     return  MVT::v4i16;
5898   }
5899 }
5900
5901 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5902 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5903 /// We insert the required extension here to get the vector to fill a D register.
5904 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5905                                             const EVT &OrigTy,
5906                                             const EVT &ExtTy,
5907                                             unsigned ExtOpcode) {
5908   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5909   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5910   // 64-bits we need to insert a new extension so that it will be 64-bits.
5911   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5912   if (OrigTy.getSizeInBits() >= 64)
5913     return N;
5914
5915   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5916   EVT NewVT = getExtensionTo64Bits(OrigTy);
5917
5918   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5919 }
5920
5921 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5922 /// does not do any sign/zero extension. If the original vector is less
5923 /// than 64 bits, an appropriate extension will be added after the load to
5924 /// reach a total size of 64 bits. We have to add the extension separately
5925 /// because ARM does not have a sign/zero extending load for vectors.
5926 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5927   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5928
5929   // The load already has the right type.
5930   if (ExtendedTy == LD->getMemoryVT())
5931     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5932                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5933                 LD->isNonTemporal(), LD->isInvariant(),
5934                 LD->getAlignment());
5935
5936   // We need to create a zextload/sextload. We cannot just create a load
5937   // followed by a zext/zext node because LowerMUL is also run during normal
5938   // operation legalization where we can't create illegal types.
5939   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5940                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5941                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5942                         LD->isNonTemporal(), LD->getAlignment());
5943 }
5944
5945 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5946 /// extending load, or BUILD_VECTOR with extended elements, return the
5947 /// unextended value. The unextended vector should be 64 bits so that it can
5948 /// be used as an operand to a VMULL instruction. If the original vector size
5949 /// before extension is less than 64 bits we add a an extension to resize
5950 /// the vector to 64 bits.
5951 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5952   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5953     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5954                                         N->getOperand(0)->getValueType(0),
5955                                         N->getValueType(0),
5956                                         N->getOpcode());
5957
5958   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5959     return SkipLoadExtensionForVMULL(LD, DAG);
5960
5961   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5962   // have been legalized as a BITCAST from v4i32.
5963   if (N->getOpcode() == ISD::BITCAST) {
5964     SDNode *BVN = N->getOperand(0).getNode();
5965     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5966            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5967     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5968     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5969                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5970   }
5971   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5972   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5973   EVT VT = N->getValueType(0);
5974   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5975   unsigned NumElts = VT.getVectorNumElements();
5976   MVT TruncVT = MVT::getIntegerVT(EltSize);
5977   SmallVector<SDValue, 8> Ops;
5978   for (unsigned i = 0; i != NumElts; ++i) {
5979     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5980     const APInt &CInt = C->getAPIntValue();
5981     // Element types smaller than 32 bits are not legal, so use i32 elements.
5982     // The values are implicitly truncated so sext vs. zext doesn't matter.
5983     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5984   }
5985   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5986                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5987 }
5988
5989 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5990   unsigned Opcode = N->getOpcode();
5991   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5992     SDNode *N0 = N->getOperand(0).getNode();
5993     SDNode *N1 = N->getOperand(1).getNode();
5994     return N0->hasOneUse() && N1->hasOneUse() &&
5995       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5996   }
5997   return false;
5998 }
5999
6000 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6001   unsigned Opcode = N->getOpcode();
6002   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6003     SDNode *N0 = N->getOperand(0).getNode();
6004     SDNode *N1 = N->getOperand(1).getNode();
6005     return N0->hasOneUse() && N1->hasOneUse() &&
6006       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6007   }
6008   return false;
6009 }
6010
6011 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6012   // Multiplications are only custom-lowered for 128-bit vectors so that
6013   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6014   EVT VT = Op.getValueType();
6015   assert(VT.is128BitVector() && VT.isInteger() &&
6016          "unexpected type for custom-lowering ISD::MUL");
6017   SDNode *N0 = Op.getOperand(0).getNode();
6018   SDNode *N1 = Op.getOperand(1).getNode();
6019   unsigned NewOpc = 0;
6020   bool isMLA = false;
6021   bool isN0SExt = isSignExtended(N0, DAG);
6022   bool isN1SExt = isSignExtended(N1, DAG);
6023   if (isN0SExt && isN1SExt)
6024     NewOpc = ARMISD::VMULLs;
6025   else {
6026     bool isN0ZExt = isZeroExtended(N0, DAG);
6027     bool isN1ZExt = isZeroExtended(N1, DAG);
6028     if (isN0ZExt && isN1ZExt)
6029       NewOpc = ARMISD::VMULLu;
6030     else if (isN1SExt || isN1ZExt) {
6031       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6032       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6033       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6034         NewOpc = ARMISD::VMULLs;
6035         isMLA = true;
6036       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6037         NewOpc = ARMISD::VMULLu;
6038         isMLA = true;
6039       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6040         std::swap(N0, N1);
6041         NewOpc = ARMISD::VMULLu;
6042         isMLA = true;
6043       }
6044     }
6045
6046     if (!NewOpc) {
6047       if (VT == MVT::v2i64)
6048         // Fall through to expand this.  It is not legal.
6049         return SDValue();
6050       else
6051         // Other vector multiplications are legal.
6052         return Op;
6053     }
6054   }
6055
6056   // Legalize to a VMULL instruction.
6057   SDLoc DL(Op);
6058   SDValue Op0;
6059   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6060   if (!isMLA) {
6061     Op0 = SkipExtensionForVMULL(N0, DAG);
6062     assert(Op0.getValueType().is64BitVector() &&
6063            Op1.getValueType().is64BitVector() &&
6064            "unexpected types for extended operands to VMULL");
6065     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6066   }
6067
6068   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6069   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6070   //   vmull q0, d4, d6
6071   //   vmlal q0, d5, d6
6072   // is faster than
6073   //   vaddl q0, d4, d5
6074   //   vmovl q1, d6
6075   //   vmul  q0, q0, q1
6076   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6077   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6078   EVT Op1VT = Op1.getValueType();
6079   return DAG.getNode(N0->getOpcode(), DL, VT,
6080                      DAG.getNode(NewOpc, DL, VT,
6081                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6082                      DAG.getNode(NewOpc, DL, VT,
6083                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6084 }
6085
6086 static SDValue
6087 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6088   // Convert to float
6089   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6090   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6091   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6092   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6093   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6094   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6095   // Get reciprocal estimate.
6096   // float4 recip = vrecpeq_f32(yf);
6097   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6098                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6099   // Because char has a smaller range than uchar, we can actually get away
6100   // without any newton steps.  This requires that we use a weird bias
6101   // of 0xb000, however (again, this has been exhaustively tested).
6102   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6103   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6104   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6105   Y = DAG.getConstant(0xb000, MVT::i32);
6106   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6107   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6108   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6109   // Convert back to short.
6110   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6111   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6112   return X;
6113 }
6114
6115 static SDValue
6116 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6117   SDValue N2;
6118   // Convert to float.
6119   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6120   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6121   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6122   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6123   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6124   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6125
6126   // Use reciprocal estimate and one refinement step.
6127   // float4 recip = vrecpeq_f32(yf);
6128   // recip *= vrecpsq_f32(yf, recip);
6129   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6130                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6131   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6132                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6133                    N1, N2);
6134   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6135   // Because short has a smaller range than ushort, we can actually get away
6136   // with only a single newton step.  This requires that we use a weird bias
6137   // of 89, however (again, this has been exhaustively tested).
6138   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6139   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6140   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6141   N1 = DAG.getConstant(0x89, MVT::i32);
6142   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6143   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6144   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6145   // Convert back to integer and return.
6146   // return vmovn_s32(vcvt_s32_f32(result));
6147   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6148   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6149   return N0;
6150 }
6151
6152 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6153   EVT VT = Op.getValueType();
6154   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6155          "unexpected type for custom-lowering ISD::SDIV");
6156
6157   SDLoc dl(Op);
6158   SDValue N0 = Op.getOperand(0);
6159   SDValue N1 = Op.getOperand(1);
6160   SDValue N2, N3;
6161
6162   if (VT == MVT::v8i8) {
6163     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6164     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6165
6166     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6167                      DAG.getIntPtrConstant(4));
6168     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6169                      DAG.getIntPtrConstant(4));
6170     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6171                      DAG.getIntPtrConstant(0));
6172     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6173                      DAG.getIntPtrConstant(0));
6174
6175     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6176     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6177
6178     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6179     N0 = LowerCONCAT_VECTORS(N0, DAG);
6180
6181     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6182     return N0;
6183   }
6184   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6185 }
6186
6187 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6188   EVT VT = Op.getValueType();
6189   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6190          "unexpected type for custom-lowering ISD::UDIV");
6191
6192   SDLoc dl(Op);
6193   SDValue N0 = Op.getOperand(0);
6194   SDValue N1 = Op.getOperand(1);
6195   SDValue N2, N3;
6196
6197   if (VT == MVT::v8i8) {
6198     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6199     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6200
6201     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6202                      DAG.getIntPtrConstant(4));
6203     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6204                      DAG.getIntPtrConstant(4));
6205     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6206                      DAG.getIntPtrConstant(0));
6207     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6208                      DAG.getIntPtrConstant(0));
6209
6210     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6211     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6212
6213     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6214     N0 = LowerCONCAT_VECTORS(N0, DAG);
6215
6216     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6217                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6218                      N0);
6219     return N0;
6220   }
6221
6222   // v4i16 sdiv ... Convert to float.
6223   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6224   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6225   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6226   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6227   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6228   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6229
6230   // Use reciprocal estimate and two refinement steps.
6231   // float4 recip = vrecpeq_f32(yf);
6232   // recip *= vrecpsq_f32(yf, recip);
6233   // recip *= vrecpsq_f32(yf, recip);
6234   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6235                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6236   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6237                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6238                    BN1, N2);
6239   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6240   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6241                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6242                    BN1, N2);
6243   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6244   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6245   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6246   // and that it will never cause us to return an answer too large).
6247   // float4 result = as_float4(as_int4(xf*recip) + 2);
6248   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6249   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6250   N1 = DAG.getConstant(2, MVT::i32);
6251   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6252   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6253   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6254   // Convert back to integer and return.
6255   // return vmovn_u32(vcvt_s32_f32(result));
6256   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6257   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6258   return N0;
6259 }
6260
6261 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6262   EVT VT = Op.getNode()->getValueType(0);
6263   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6264
6265   unsigned Opc;
6266   bool ExtraOp = false;
6267   switch (Op.getOpcode()) {
6268   default: llvm_unreachable("Invalid code");
6269   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6270   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6271   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6272   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6273   }
6274
6275   if (!ExtraOp)
6276     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6277                        Op.getOperand(1));
6278   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6279                      Op.getOperand(1), Op.getOperand(2));
6280 }
6281
6282 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6283   assert(Subtarget->isTargetDarwin());
6284
6285   // For iOS, we want to call an alternative entry point: __sincos_stret,
6286   // return values are passed via sret.
6287   SDLoc dl(Op);
6288   SDValue Arg = Op.getOperand(0);
6289   EVT ArgVT = Arg.getValueType();
6290   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6291
6292   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6293   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6294
6295   // Pair of floats / doubles used to pass the result.
6296   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6297
6298   // Create stack object for sret.
6299   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6300   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6301   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6302   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6303
6304   ArgListTy Args;
6305   ArgListEntry Entry;
6306
6307   Entry.Node = SRet;
6308   Entry.Ty = RetTy->getPointerTo();
6309   Entry.isSExt = false;
6310   Entry.isZExt = false;
6311   Entry.isSRet = true;
6312   Args.push_back(Entry);
6313
6314   Entry.Node = Arg;
6315   Entry.Ty = ArgTy;
6316   Entry.isSExt = false;
6317   Entry.isZExt = false;
6318   Args.push_back(Entry);
6319
6320   const char *LibcallName  = (ArgVT == MVT::f64)
6321   ? "__sincos_stret" : "__sincosf_stret";
6322   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6323
6324   TargetLowering::CallLoweringInfo CLI(DAG);
6325   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6326     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6327                std::move(Args), 0)
6328     .setDiscardResult();
6329
6330   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6331
6332   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6333                                 MachinePointerInfo(), false, false, false, 0);
6334
6335   // Address of cos field.
6336   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6337                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6338   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6339                                 MachinePointerInfo(), false, false, false, 0);
6340
6341   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6342   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6343                      LoadSin.getValue(0), LoadCos.getValue(0));
6344 }
6345
6346 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6347   // Monotonic load/store is legal for all targets
6348   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6349     return Op;
6350
6351   // Acquire/Release load/store is not legal for targets without a
6352   // dmb or equivalent available.
6353   return SDValue();
6354 }
6355
6356 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6357                                     SmallVectorImpl<SDValue> &Results,
6358                                     SelectionDAG &DAG,
6359                                     const ARMSubtarget *Subtarget) {
6360   SDLoc DL(N);
6361   SDValue Cycles32, OutChain;
6362
6363   if (Subtarget->hasPerfMon()) {
6364     // Under Power Management extensions, the cycle-count is:
6365     //    mrc p15, #0, <Rt>, c9, c13, #0
6366     SDValue Ops[] = { N->getOperand(0), // Chain
6367                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6368                       DAG.getConstant(15, MVT::i32),
6369                       DAG.getConstant(0, MVT::i32),
6370                       DAG.getConstant(9, MVT::i32),
6371                       DAG.getConstant(13, MVT::i32),
6372                       DAG.getConstant(0, MVT::i32)
6373     };
6374
6375     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6376                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6377     OutChain = Cycles32.getValue(1);
6378   } else {
6379     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6380     // there are older ARM CPUs that have implementation-specific ways of
6381     // obtaining this information (FIXME!).
6382     Cycles32 = DAG.getConstant(0, MVT::i32);
6383     OutChain = DAG.getEntryNode();
6384   }
6385
6386
6387   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6388                                  Cycles32, DAG.getConstant(0, MVT::i32));
6389   Results.push_back(Cycles64);
6390   Results.push_back(OutChain);
6391 }
6392
6393 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6394   switch (Op.getOpcode()) {
6395   default: llvm_unreachable("Don't know how to custom lower this!");
6396   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6397   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6398   case ISD::GlobalAddress:
6399     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6400     default: llvm_unreachable("unknown object format");
6401     case Triple::COFF:
6402       return LowerGlobalAddressWindows(Op, DAG);
6403     case Triple::ELF:
6404       return LowerGlobalAddressELF(Op, DAG);
6405     case Triple::MachO:
6406       return LowerGlobalAddressDarwin(Op, DAG);
6407     }
6408   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6409   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6410   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6411   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6412   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6413   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6414   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6415   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6416   case ISD::SINT_TO_FP:
6417   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6418   case ISD::FP_TO_SINT:
6419   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6420   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6421   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6422   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6423   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6424   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6425   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6426   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6427                                                                Subtarget);
6428   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6429   case ISD::SHL:
6430   case ISD::SRL:
6431   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6432   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6433   case ISD::SRL_PARTS:
6434   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6435   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6436   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6437   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6438   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6439   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6440   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6441   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6442   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6443   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6444   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6445   case ISD::MUL:           return LowerMUL(Op, DAG);
6446   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6447   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6448   case ISD::ADDC:
6449   case ISD::ADDE:
6450   case ISD::SUBC:
6451   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6452   case ISD::SADDO:
6453   case ISD::UADDO:
6454   case ISD::SSUBO:
6455   case ISD::USUBO:
6456     return LowerXALUO(Op, DAG);
6457   case ISD::ATOMIC_LOAD:
6458   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6459   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6460   case ISD::SDIVREM:
6461   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6462   case ISD::DYNAMIC_STACKALLOC:
6463     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6464       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6465     llvm_unreachable("Don't know how to custom lower this!");
6466   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6467   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6468   }
6469 }
6470
6471 /// ReplaceNodeResults - Replace the results of node with an illegal result
6472 /// type with new values built out of custom code.
6473 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6474                                            SmallVectorImpl<SDValue>&Results,
6475                                            SelectionDAG &DAG) const {
6476   SDValue Res;
6477   switch (N->getOpcode()) {
6478   default:
6479     llvm_unreachable("Don't know how to custom expand this!");
6480   case ISD::BITCAST:
6481     Res = ExpandBITCAST(N, DAG);
6482     break;
6483   case ISD::SRL:
6484   case ISD::SRA:
6485     Res = Expand64BitShift(N, DAG, Subtarget);
6486     break;
6487   case ISD::READCYCLECOUNTER:
6488     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6489     return;
6490   }
6491   if (Res.getNode())
6492     Results.push_back(Res);
6493 }
6494
6495 //===----------------------------------------------------------------------===//
6496 //                           ARM Scheduler Hooks
6497 //===----------------------------------------------------------------------===//
6498
6499 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6500 /// registers the function context.
6501 void ARMTargetLowering::
6502 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6503                        MachineBasicBlock *DispatchBB, int FI) const {
6504   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6505   DebugLoc dl = MI->getDebugLoc();
6506   MachineFunction *MF = MBB->getParent();
6507   MachineRegisterInfo *MRI = &MF->getRegInfo();
6508   MachineConstantPool *MCP = MF->getConstantPool();
6509   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6510   const Function *F = MF->getFunction();
6511
6512   bool isThumb = Subtarget->isThumb();
6513   bool isThumb2 = Subtarget->isThumb2();
6514
6515   unsigned PCLabelId = AFI->createPICLabelUId();
6516   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6517   ARMConstantPoolValue *CPV =
6518     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6519   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6520
6521   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6522                                            : &ARM::GPRRegClass;
6523
6524   // Grab constant pool and fixed stack memory operands.
6525   MachineMemOperand *CPMMO =
6526     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6527                              MachineMemOperand::MOLoad, 4, 4);
6528
6529   MachineMemOperand *FIMMOSt =
6530     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6531                              MachineMemOperand::MOStore, 4, 4);
6532
6533   // Load the address of the dispatch MBB into the jump buffer.
6534   if (isThumb2) {
6535     // Incoming value: jbuf
6536     //   ldr.n  r5, LCPI1_1
6537     //   orr    r5, r5, #1
6538     //   add    r5, pc
6539     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6540     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6541     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6542                    .addConstantPoolIndex(CPI)
6543                    .addMemOperand(CPMMO));
6544     // Set the low bit because of thumb mode.
6545     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6546     AddDefaultCC(
6547       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6548                      .addReg(NewVReg1, RegState::Kill)
6549                      .addImm(0x01)));
6550     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6551     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6552       .addReg(NewVReg2, RegState::Kill)
6553       .addImm(PCLabelId);
6554     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6555                    .addReg(NewVReg3, RegState::Kill)
6556                    .addFrameIndex(FI)
6557                    .addImm(36)  // &jbuf[1] :: pc
6558                    .addMemOperand(FIMMOSt));
6559   } else if (isThumb) {
6560     // Incoming value: jbuf
6561     //   ldr.n  r1, LCPI1_4
6562     //   add    r1, pc
6563     //   mov    r2, #1
6564     //   orrs   r1, r2
6565     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6566     //   str    r1, [r2]
6567     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6568     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6569                    .addConstantPoolIndex(CPI)
6570                    .addMemOperand(CPMMO));
6571     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6572     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6573       .addReg(NewVReg1, RegState::Kill)
6574       .addImm(PCLabelId);
6575     // Set the low bit because of thumb mode.
6576     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6577     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6578                    .addReg(ARM::CPSR, RegState::Define)
6579                    .addImm(1));
6580     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6581     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6582                    .addReg(ARM::CPSR, RegState::Define)
6583                    .addReg(NewVReg2, RegState::Kill)
6584                    .addReg(NewVReg3, RegState::Kill));
6585     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6586     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6587             .addFrameIndex(FI)
6588             .addImm(36); // &jbuf[1] :: pc
6589     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6590                    .addReg(NewVReg4, RegState::Kill)
6591                    .addReg(NewVReg5, RegState::Kill)
6592                    .addImm(0)
6593                    .addMemOperand(FIMMOSt));
6594   } else {
6595     // Incoming value: jbuf
6596     //   ldr  r1, LCPI1_1
6597     //   add  r1, pc, r1
6598     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6599     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6600     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6601                    .addConstantPoolIndex(CPI)
6602                    .addImm(0)
6603                    .addMemOperand(CPMMO));
6604     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6605     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6606                    .addReg(NewVReg1, RegState::Kill)
6607                    .addImm(PCLabelId));
6608     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6609                    .addReg(NewVReg2, RegState::Kill)
6610                    .addFrameIndex(FI)
6611                    .addImm(36)  // &jbuf[1] :: pc
6612                    .addMemOperand(FIMMOSt));
6613   }
6614 }
6615
6616 MachineBasicBlock *ARMTargetLowering::
6617 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6618   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6619   DebugLoc dl = MI->getDebugLoc();
6620   MachineFunction *MF = MBB->getParent();
6621   MachineRegisterInfo *MRI = &MF->getRegInfo();
6622   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6623   MachineFrameInfo *MFI = MF->getFrameInfo();
6624   int FI = MFI->getFunctionContextIndex();
6625
6626   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6627                                                         : &ARM::GPRnopcRegClass;
6628
6629   // Get a mapping of the call site numbers to all of the landing pads they're
6630   // associated with.
6631   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6632   unsigned MaxCSNum = 0;
6633   MachineModuleInfo &MMI = MF->getMMI();
6634   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6635        ++BB) {
6636     if (!BB->isLandingPad()) continue;
6637
6638     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6639     // pad.
6640     for (MachineBasicBlock::iterator
6641            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6642       if (!II->isEHLabel()) continue;
6643
6644       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6645       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6646
6647       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6648       for (SmallVectorImpl<unsigned>::iterator
6649              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6650            CSI != CSE; ++CSI) {
6651         CallSiteNumToLPad[*CSI].push_back(BB);
6652         MaxCSNum = std::max(MaxCSNum, *CSI);
6653       }
6654       break;
6655     }
6656   }
6657
6658   // Get an ordered list of the machine basic blocks for the jump table.
6659   std::vector<MachineBasicBlock*> LPadList;
6660   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6661   LPadList.reserve(CallSiteNumToLPad.size());
6662   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6663     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6664     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6665            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6666       LPadList.push_back(*II);
6667       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6668     }
6669   }
6670
6671   assert(!LPadList.empty() &&
6672          "No landing pad destinations for the dispatch jump table!");
6673
6674   // Create the jump table and associated information.
6675   MachineJumpTableInfo *JTI =
6676     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6677   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6678   unsigned UId = AFI->createJumpTableUId();
6679   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6680
6681   // Create the MBBs for the dispatch code.
6682
6683   // Shove the dispatch's address into the return slot in the function context.
6684   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6685   DispatchBB->setIsLandingPad();
6686
6687   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6688   unsigned trap_opcode;
6689   if (Subtarget->isThumb())
6690     trap_opcode = ARM::tTRAP;
6691   else
6692     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6693
6694   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6695   DispatchBB->addSuccessor(TrapBB);
6696
6697   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6698   DispatchBB->addSuccessor(DispContBB);
6699
6700   // Insert and MBBs.
6701   MF->insert(MF->end(), DispatchBB);
6702   MF->insert(MF->end(), DispContBB);
6703   MF->insert(MF->end(), TrapBB);
6704
6705   // Insert code into the entry block that creates and registers the function
6706   // context.
6707   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6708
6709   MachineMemOperand *FIMMOLd =
6710     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6711                              MachineMemOperand::MOLoad |
6712                              MachineMemOperand::MOVolatile, 4, 4);
6713
6714   MachineInstrBuilder MIB;
6715   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6716
6717   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6718   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6719
6720   // Add a register mask with no preserved registers.  This results in all
6721   // registers being marked as clobbered.
6722   MIB.addRegMask(RI.getNoPreservedMask());
6723
6724   unsigned NumLPads = LPadList.size();
6725   if (Subtarget->isThumb2()) {
6726     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6727     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6728                    .addFrameIndex(FI)
6729                    .addImm(4)
6730                    .addMemOperand(FIMMOLd));
6731
6732     if (NumLPads < 256) {
6733       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6734                      .addReg(NewVReg1)
6735                      .addImm(LPadList.size()));
6736     } else {
6737       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6738       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6739                      .addImm(NumLPads & 0xFFFF));
6740
6741       unsigned VReg2 = VReg1;
6742       if ((NumLPads & 0xFFFF0000) != 0) {
6743         VReg2 = MRI->createVirtualRegister(TRC);
6744         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6745                        .addReg(VReg1)
6746                        .addImm(NumLPads >> 16));
6747       }
6748
6749       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6750                      .addReg(NewVReg1)
6751                      .addReg(VReg2));
6752     }
6753
6754     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6755       .addMBB(TrapBB)
6756       .addImm(ARMCC::HI)
6757       .addReg(ARM::CPSR);
6758
6759     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6760     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6761                    .addJumpTableIndex(MJTI)
6762                    .addImm(UId));
6763
6764     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6765     AddDefaultCC(
6766       AddDefaultPred(
6767         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6768         .addReg(NewVReg3, RegState::Kill)
6769         .addReg(NewVReg1)
6770         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6771
6772     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6773       .addReg(NewVReg4, RegState::Kill)
6774       .addReg(NewVReg1)
6775       .addJumpTableIndex(MJTI)
6776       .addImm(UId);
6777   } else if (Subtarget->isThumb()) {
6778     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6779     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6780                    .addFrameIndex(FI)
6781                    .addImm(1)
6782                    .addMemOperand(FIMMOLd));
6783
6784     if (NumLPads < 256) {
6785       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6786                      .addReg(NewVReg1)
6787                      .addImm(NumLPads));
6788     } else {
6789       MachineConstantPool *ConstantPool = MF->getConstantPool();
6790       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6791       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6792
6793       // MachineConstantPool wants an explicit alignment.
6794       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6795       if (Align == 0)
6796         Align = getDataLayout()->getTypeAllocSize(C->getType());
6797       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6798
6799       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6800       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6801                      .addReg(VReg1, RegState::Define)
6802                      .addConstantPoolIndex(Idx));
6803       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6804                      .addReg(NewVReg1)
6805                      .addReg(VReg1));
6806     }
6807
6808     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6809       .addMBB(TrapBB)
6810       .addImm(ARMCC::HI)
6811       .addReg(ARM::CPSR);
6812
6813     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6814     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6815                    .addReg(ARM::CPSR, RegState::Define)
6816                    .addReg(NewVReg1)
6817                    .addImm(2));
6818
6819     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6820     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6821                    .addJumpTableIndex(MJTI)
6822                    .addImm(UId));
6823
6824     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6825     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6826                    .addReg(ARM::CPSR, RegState::Define)
6827                    .addReg(NewVReg2, RegState::Kill)
6828                    .addReg(NewVReg3));
6829
6830     MachineMemOperand *JTMMOLd =
6831       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6832                                MachineMemOperand::MOLoad, 4, 4);
6833
6834     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6835     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6836                    .addReg(NewVReg4, RegState::Kill)
6837                    .addImm(0)
6838                    .addMemOperand(JTMMOLd));
6839
6840     unsigned NewVReg6 = NewVReg5;
6841     if (RelocM == Reloc::PIC_) {
6842       NewVReg6 = MRI->createVirtualRegister(TRC);
6843       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6844                      .addReg(ARM::CPSR, RegState::Define)
6845                      .addReg(NewVReg5, RegState::Kill)
6846                      .addReg(NewVReg3));
6847     }
6848
6849     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6850       .addReg(NewVReg6, RegState::Kill)
6851       .addJumpTableIndex(MJTI)
6852       .addImm(UId);
6853   } else {
6854     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6855     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6856                    .addFrameIndex(FI)
6857                    .addImm(4)
6858                    .addMemOperand(FIMMOLd));
6859
6860     if (NumLPads < 256) {
6861       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6862                      .addReg(NewVReg1)
6863                      .addImm(NumLPads));
6864     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6865       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6866       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6867                      .addImm(NumLPads & 0xFFFF));
6868
6869       unsigned VReg2 = VReg1;
6870       if ((NumLPads & 0xFFFF0000) != 0) {
6871         VReg2 = MRI->createVirtualRegister(TRC);
6872         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6873                        .addReg(VReg1)
6874                        .addImm(NumLPads >> 16));
6875       }
6876
6877       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6878                      .addReg(NewVReg1)
6879                      .addReg(VReg2));
6880     } else {
6881       MachineConstantPool *ConstantPool = MF->getConstantPool();
6882       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6883       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6884
6885       // MachineConstantPool wants an explicit alignment.
6886       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6887       if (Align == 0)
6888         Align = getDataLayout()->getTypeAllocSize(C->getType());
6889       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6890
6891       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6892       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6893                      .addReg(VReg1, RegState::Define)
6894                      .addConstantPoolIndex(Idx)
6895                      .addImm(0));
6896       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6897                      .addReg(NewVReg1)
6898                      .addReg(VReg1, RegState::Kill));
6899     }
6900
6901     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6902       .addMBB(TrapBB)
6903       .addImm(ARMCC::HI)
6904       .addReg(ARM::CPSR);
6905
6906     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6907     AddDefaultCC(
6908       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6909                      .addReg(NewVReg1)
6910                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6911     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6912     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6913                    .addJumpTableIndex(MJTI)
6914                    .addImm(UId));
6915
6916     MachineMemOperand *JTMMOLd =
6917       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6918                                MachineMemOperand::MOLoad, 4, 4);
6919     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6920     AddDefaultPred(
6921       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6922       .addReg(NewVReg3, RegState::Kill)
6923       .addReg(NewVReg4)
6924       .addImm(0)
6925       .addMemOperand(JTMMOLd));
6926
6927     if (RelocM == Reloc::PIC_) {
6928       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6929         .addReg(NewVReg5, RegState::Kill)
6930         .addReg(NewVReg4)
6931         .addJumpTableIndex(MJTI)
6932         .addImm(UId);
6933     } else {
6934       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6935         .addReg(NewVReg5, RegState::Kill)
6936         .addJumpTableIndex(MJTI)
6937         .addImm(UId);
6938     }
6939   }
6940
6941   // Add the jump table entries as successors to the MBB.
6942   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6943   for (std::vector<MachineBasicBlock*>::iterator
6944          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6945     MachineBasicBlock *CurMBB = *I;
6946     if (SeenMBBs.insert(CurMBB).second)
6947       DispContBB->addSuccessor(CurMBB);
6948   }
6949
6950   // N.B. the order the invoke BBs are processed in doesn't matter here.
6951   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6952   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6953   for (MachineBasicBlock *BB : InvokeBBs) {
6954
6955     // Remove the landing pad successor from the invoke block and replace it
6956     // with the new dispatch block.
6957     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6958                                                   BB->succ_end());
6959     while (!Successors.empty()) {
6960       MachineBasicBlock *SMBB = Successors.pop_back_val();
6961       if (SMBB->isLandingPad()) {
6962         BB->removeSuccessor(SMBB);
6963         MBBLPads.push_back(SMBB);
6964       }
6965     }
6966
6967     BB->addSuccessor(DispatchBB);
6968
6969     // Find the invoke call and mark all of the callee-saved registers as
6970     // 'implicit defined' so that they're spilled. This prevents code from
6971     // moving instructions to before the EH block, where they will never be
6972     // executed.
6973     for (MachineBasicBlock::reverse_iterator
6974            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6975       if (!II->isCall()) continue;
6976
6977       DenseMap<unsigned, bool> DefRegs;
6978       for (MachineInstr::mop_iterator
6979              OI = II->operands_begin(), OE = II->operands_end();
6980            OI != OE; ++OI) {
6981         if (!OI->isReg()) continue;
6982         DefRegs[OI->getReg()] = true;
6983       }
6984
6985       MachineInstrBuilder MIB(*MF, &*II);
6986
6987       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6988         unsigned Reg = SavedRegs[i];
6989         if (Subtarget->isThumb2() &&
6990             !ARM::tGPRRegClass.contains(Reg) &&
6991             !ARM::hGPRRegClass.contains(Reg))
6992           continue;
6993         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6994           continue;
6995         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6996           continue;
6997         if (!DefRegs[Reg])
6998           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6999       }
7000
7001       break;
7002     }
7003   }
7004
7005   // Mark all former landing pads as non-landing pads. The dispatch is the only
7006   // landing pad now.
7007   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7008          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7009     (*I)->setIsLandingPad(false);
7010
7011   // The instruction is gone now.
7012   MI->eraseFromParent();
7013
7014   return MBB;
7015 }
7016
7017 static
7018 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7019   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7020        E = MBB->succ_end(); I != E; ++I)
7021     if (*I != Succ)
7022       return *I;
7023   llvm_unreachable("Expecting a BB with two successors!");
7024 }
7025
7026 /// Return the load opcode for a given load size. If load size >= 8,
7027 /// neon opcode will be returned.
7028 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7029   if (LdSize >= 8)
7030     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7031                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7032   if (IsThumb1)
7033     return LdSize == 4 ? ARM::tLDRi
7034                        : LdSize == 2 ? ARM::tLDRHi
7035                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7036   if (IsThumb2)
7037     return LdSize == 4 ? ARM::t2LDR_POST
7038                        : LdSize == 2 ? ARM::t2LDRH_POST
7039                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7040   return LdSize == 4 ? ARM::LDR_POST_IMM
7041                      : LdSize == 2 ? ARM::LDRH_POST
7042                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7043 }
7044
7045 /// Return the store opcode for a given store size. If store size >= 8,
7046 /// neon opcode will be returned.
7047 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7048   if (StSize >= 8)
7049     return StSize == 16 ? ARM::VST1q32wb_fixed
7050                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7051   if (IsThumb1)
7052     return StSize == 4 ? ARM::tSTRi
7053                        : StSize == 2 ? ARM::tSTRHi
7054                                      : StSize == 1 ? ARM::tSTRBi : 0;
7055   if (IsThumb2)
7056     return StSize == 4 ? ARM::t2STR_POST
7057                        : StSize == 2 ? ARM::t2STRH_POST
7058                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7059   return StSize == 4 ? ARM::STR_POST_IMM
7060                      : StSize == 2 ? ARM::STRH_POST
7061                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7062 }
7063
7064 /// Emit a post-increment load operation with given size. The instructions
7065 /// will be added to BB at Pos.
7066 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7067                        const TargetInstrInfo *TII, DebugLoc dl,
7068                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7069                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7070   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7071   assert(LdOpc != 0 && "Should have a load opcode");
7072   if (LdSize >= 8) {
7073     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7074                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7075                        .addImm(0));
7076   } else if (IsThumb1) {
7077     // load + update AddrIn
7078     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7079                        .addReg(AddrIn).addImm(0));
7080     MachineInstrBuilder MIB =
7081         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7082     MIB = AddDefaultT1CC(MIB);
7083     MIB.addReg(AddrIn).addImm(LdSize);
7084     AddDefaultPred(MIB);
7085   } else if (IsThumb2) {
7086     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7087                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7088                        .addImm(LdSize));
7089   } else { // arm
7090     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7091                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7092                        .addReg(0).addImm(LdSize));
7093   }
7094 }
7095
7096 /// Emit a post-increment store operation with given size. The instructions
7097 /// will be added to BB at Pos.
7098 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7099                        const TargetInstrInfo *TII, DebugLoc dl,
7100                        unsigned StSize, unsigned Data, unsigned AddrIn,
7101                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7102   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7103   assert(StOpc != 0 && "Should have a store opcode");
7104   if (StSize >= 8) {
7105     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7106                        .addReg(AddrIn).addImm(0).addReg(Data));
7107   } else if (IsThumb1) {
7108     // store + update AddrIn
7109     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7110                        .addReg(AddrIn).addImm(0));
7111     MachineInstrBuilder MIB =
7112         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7113     MIB = AddDefaultT1CC(MIB);
7114     MIB.addReg(AddrIn).addImm(StSize);
7115     AddDefaultPred(MIB);
7116   } else if (IsThumb2) {
7117     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7118                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7119   } else { // arm
7120     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7121                        .addReg(Data).addReg(AddrIn).addReg(0)
7122                        .addImm(StSize));
7123   }
7124 }
7125
7126 MachineBasicBlock *
7127 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7128                                    MachineBasicBlock *BB) const {
7129   // This pseudo instruction has 3 operands: dst, src, size
7130   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7131   // Otherwise, we will generate unrolled scalar copies.
7132   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7133   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7134   MachineFunction::iterator It = BB;
7135   ++It;
7136
7137   unsigned dest = MI->getOperand(0).getReg();
7138   unsigned src = MI->getOperand(1).getReg();
7139   unsigned SizeVal = MI->getOperand(2).getImm();
7140   unsigned Align = MI->getOperand(3).getImm();
7141   DebugLoc dl = MI->getDebugLoc();
7142
7143   MachineFunction *MF = BB->getParent();
7144   MachineRegisterInfo &MRI = MF->getRegInfo();
7145   unsigned UnitSize = 0;
7146   const TargetRegisterClass *TRC = nullptr;
7147   const TargetRegisterClass *VecTRC = nullptr;
7148
7149   bool IsThumb1 = Subtarget->isThumb1Only();
7150   bool IsThumb2 = Subtarget->isThumb2();
7151
7152   if (Align & 1) {
7153     UnitSize = 1;
7154   } else if (Align & 2) {
7155     UnitSize = 2;
7156   } else {
7157     // Check whether we can use NEON instructions.
7158     if (!MF->getFunction()->hasFnAttribute(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 = *Subtarget->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 = Subtarget->getInstrInfo();
7427   DebugLoc dl = MI->getDebugLoc();
7428   bool isThumb2 = Subtarget->isThumb2();
7429   switch (MI->getOpcode()) {
7430   default: {
7431     MI->dump();
7432     llvm_unreachable("Unexpected instr type to insert");
7433   }
7434   // The Thumb2 pre-indexed stores have the same MI operands, they just
7435   // define them differently in the .td files from the isel patterns, so
7436   // they need pseudos.
7437   case ARM::t2STR_preidx:
7438     MI->setDesc(TII->get(ARM::t2STR_PRE));
7439     return BB;
7440   case ARM::t2STRB_preidx:
7441     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7442     return BB;
7443   case ARM::t2STRH_preidx:
7444     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7445     return BB;
7446
7447   case ARM::STRi_preidx:
7448   case ARM::STRBi_preidx: {
7449     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7450       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7451     // Decode the offset.
7452     unsigned Offset = MI->getOperand(4).getImm();
7453     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7454     Offset = ARM_AM::getAM2Offset(Offset);
7455     if (isSub)
7456       Offset = -Offset;
7457
7458     MachineMemOperand *MMO = *MI->memoperands_begin();
7459     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7460       .addOperand(MI->getOperand(0))  // Rn_wb
7461       .addOperand(MI->getOperand(1))  // Rt
7462       .addOperand(MI->getOperand(2))  // Rn
7463       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7464       .addOperand(MI->getOperand(5))  // pred
7465       .addOperand(MI->getOperand(6))
7466       .addMemOperand(MMO);
7467     MI->eraseFromParent();
7468     return BB;
7469   }
7470   case ARM::STRr_preidx:
7471   case ARM::STRBr_preidx:
7472   case ARM::STRH_preidx: {
7473     unsigned NewOpc;
7474     switch (MI->getOpcode()) {
7475     default: llvm_unreachable("unexpected opcode!");
7476     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7477     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7478     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7479     }
7480     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7481     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7482       MIB.addOperand(MI->getOperand(i));
7483     MI->eraseFromParent();
7484     return BB;
7485   }
7486
7487   case ARM::tMOVCCr_pseudo: {
7488     // To "insert" a SELECT_CC instruction, we actually have to insert the
7489     // diamond control-flow pattern.  The incoming instruction knows the
7490     // destination vreg to set, the condition code register to branch on, the
7491     // true/false values to select between, and a branch opcode to use.
7492     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7493     MachineFunction::iterator It = BB;
7494     ++It;
7495
7496     //  thisMBB:
7497     //  ...
7498     //   TrueVal = ...
7499     //   cmpTY ccX, r1, r2
7500     //   bCC copy1MBB
7501     //   fallthrough --> copy0MBB
7502     MachineBasicBlock *thisMBB  = BB;
7503     MachineFunction *F = BB->getParent();
7504     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7505     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7506     F->insert(It, copy0MBB);
7507     F->insert(It, sinkMBB);
7508
7509     // Transfer the remainder of BB and its successor edges to sinkMBB.
7510     sinkMBB->splice(sinkMBB->begin(), BB,
7511                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7512     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7513
7514     BB->addSuccessor(copy0MBB);
7515     BB->addSuccessor(sinkMBB);
7516
7517     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7518       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7519
7520     //  copy0MBB:
7521     //   %FalseValue = ...
7522     //   # fallthrough to sinkMBB
7523     BB = copy0MBB;
7524
7525     // Update machine-CFG edges
7526     BB->addSuccessor(sinkMBB);
7527
7528     //  sinkMBB:
7529     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7530     //  ...
7531     BB = sinkMBB;
7532     BuildMI(*BB, BB->begin(), dl,
7533             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7534       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7535       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7536
7537     MI->eraseFromParent();   // The pseudo instruction is gone now.
7538     return BB;
7539   }
7540
7541   case ARM::BCCi64:
7542   case ARM::BCCZi64: {
7543     // If there is an unconditional branch to the other successor, remove it.
7544     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7545
7546     // Compare both parts that make up the double comparison separately for
7547     // equality.
7548     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7549
7550     unsigned LHS1 = MI->getOperand(1).getReg();
7551     unsigned LHS2 = MI->getOperand(2).getReg();
7552     if (RHSisZero) {
7553       AddDefaultPred(BuildMI(BB, dl,
7554                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7555                      .addReg(LHS1).addImm(0));
7556       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7557         .addReg(LHS2).addImm(0)
7558         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7559     } else {
7560       unsigned RHS1 = MI->getOperand(3).getReg();
7561       unsigned RHS2 = MI->getOperand(4).getReg();
7562       AddDefaultPred(BuildMI(BB, dl,
7563                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7564                      .addReg(LHS1).addReg(RHS1));
7565       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7566         .addReg(LHS2).addReg(RHS2)
7567         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7568     }
7569
7570     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7571     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7572     if (MI->getOperand(0).getImm() == ARMCC::NE)
7573       std::swap(destMBB, exitMBB);
7574
7575     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7576       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7577     if (isThumb2)
7578       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7579     else
7580       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7581
7582     MI->eraseFromParent();   // The pseudo instruction is gone now.
7583     return BB;
7584   }
7585
7586   case ARM::Int_eh_sjlj_setjmp:
7587   case ARM::Int_eh_sjlj_setjmp_nofp:
7588   case ARM::tInt_eh_sjlj_setjmp:
7589   case ARM::t2Int_eh_sjlj_setjmp:
7590   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7591     EmitSjLjDispatchBlock(MI, BB);
7592     return BB;
7593
7594   case ARM::ABS:
7595   case ARM::t2ABS: {
7596     // To insert an ABS instruction, we have to insert the
7597     // diamond control-flow pattern.  The incoming instruction knows the
7598     // source vreg to test against 0, the destination vreg to set,
7599     // the condition code register to branch on, the
7600     // true/false values to select between, and a branch opcode to use.
7601     // It transforms
7602     //     V1 = ABS V0
7603     // into
7604     //     V2 = MOVS V0
7605     //     BCC                      (branch to SinkBB if V0 >= 0)
7606     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7607     //     SinkBB: V1 = PHI(V2, V3)
7608     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7609     MachineFunction::iterator BBI = BB;
7610     ++BBI;
7611     MachineFunction *Fn = BB->getParent();
7612     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7613     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7614     Fn->insert(BBI, RSBBB);
7615     Fn->insert(BBI, SinkBB);
7616
7617     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7618     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7619     bool isThumb2 = Subtarget->isThumb2();
7620     MachineRegisterInfo &MRI = Fn->getRegInfo();
7621     // In Thumb mode S must not be specified if source register is the SP or
7622     // PC and if destination register is the SP, so restrict register class
7623     unsigned NewRsbDstReg =
7624       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7625
7626     // Transfer the remainder of BB and its successor edges to sinkMBB.
7627     SinkBB->splice(SinkBB->begin(), BB,
7628                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7629     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7630
7631     BB->addSuccessor(RSBBB);
7632     BB->addSuccessor(SinkBB);
7633
7634     // fall through to SinkMBB
7635     RSBBB->addSuccessor(SinkBB);
7636
7637     // insert a cmp at the end of BB
7638     AddDefaultPred(BuildMI(BB, dl,
7639                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7640                    .addReg(ABSSrcReg).addImm(0));
7641
7642     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7643     BuildMI(BB, dl,
7644       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7645       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7646
7647     // insert rsbri in RSBBB
7648     // Note: BCC and rsbri will be converted into predicated rsbmi
7649     // by if-conversion pass
7650     BuildMI(*RSBBB, RSBBB->begin(), dl,
7651       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7652       .addReg(ABSSrcReg, RegState::Kill)
7653       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7654
7655     // insert PHI in SinkBB,
7656     // reuse ABSDstReg to not change uses of ABS instruction
7657     BuildMI(*SinkBB, SinkBB->begin(), dl,
7658       TII->get(ARM::PHI), ABSDstReg)
7659       .addReg(NewRsbDstReg).addMBB(RSBBB)
7660       .addReg(ABSSrcReg).addMBB(BB);
7661
7662     // remove ABS instruction
7663     MI->eraseFromParent();
7664
7665     // return last added BB
7666     return SinkBB;
7667   }
7668   case ARM::COPY_STRUCT_BYVAL_I32:
7669     ++NumLoopByVals;
7670     return EmitStructByval(MI, BB);
7671   case ARM::WIN__CHKSTK:
7672     return EmitLowered__chkstk(MI, BB);
7673   }
7674 }
7675
7676 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7677                                                       SDNode *Node) const {
7678   const MCInstrDesc *MCID = &MI->getDesc();
7679   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7680   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7681   // operand is still set to noreg. If needed, set the optional operand's
7682   // register to CPSR, and remove the redundant implicit def.
7683   //
7684   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7685
7686   // Rename pseudo opcodes.
7687   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7688   if (NewOpc) {
7689     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7690     MCID = &TII->get(NewOpc);
7691
7692     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7693            "converted opcode should be the same except for cc_out");
7694
7695     MI->setDesc(*MCID);
7696
7697     // Add the optional cc_out operand
7698     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7699   }
7700   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7701
7702   // Any ARM instruction that sets the 's' bit should specify an optional
7703   // "cc_out" operand in the last operand position.
7704   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7705     assert(!NewOpc && "Optional cc_out operand required");
7706     return;
7707   }
7708   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7709   // since we already have an optional CPSR def.
7710   bool definesCPSR = false;
7711   bool deadCPSR = false;
7712   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7713        i != e; ++i) {
7714     const MachineOperand &MO = MI->getOperand(i);
7715     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7716       definesCPSR = true;
7717       if (MO.isDead())
7718         deadCPSR = true;
7719       MI->RemoveOperand(i);
7720       break;
7721     }
7722   }
7723   if (!definesCPSR) {
7724     assert(!NewOpc && "Optional cc_out operand required");
7725     return;
7726   }
7727   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7728   if (deadCPSR) {
7729     assert(!MI->getOperand(ccOutIdx).getReg() &&
7730            "expect uninitialized optional cc_out operand");
7731     return;
7732   }
7733
7734   // If this instruction was defined with an optional CPSR def and its dag node
7735   // had a live implicit CPSR def, then activate the optional CPSR def.
7736   MachineOperand &MO = MI->getOperand(ccOutIdx);
7737   MO.setReg(ARM::CPSR);
7738   MO.setIsDef(true);
7739 }
7740
7741 //===----------------------------------------------------------------------===//
7742 //                           ARM Optimization Hooks
7743 //===----------------------------------------------------------------------===//
7744
7745 // Helper function that checks if N is a null or all ones constant.
7746 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7747   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7748   if (!C)
7749     return false;
7750   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7751 }
7752
7753 // Return true if N is conditionally 0 or all ones.
7754 // Detects these expressions where cc is an i1 value:
7755 //
7756 //   (select cc 0, y)   [AllOnes=0]
7757 //   (select cc y, 0)   [AllOnes=0]
7758 //   (zext cc)          [AllOnes=0]
7759 //   (sext cc)          [AllOnes=0/1]
7760 //   (select cc -1, y)  [AllOnes=1]
7761 //   (select cc y, -1)  [AllOnes=1]
7762 //
7763 // Invert is set when N is the null/all ones constant when CC is false.
7764 // OtherOp is set to the alternative value of N.
7765 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7766                                        SDValue &CC, bool &Invert,
7767                                        SDValue &OtherOp,
7768                                        SelectionDAG &DAG) {
7769   switch (N->getOpcode()) {
7770   default: return false;
7771   case ISD::SELECT: {
7772     CC = N->getOperand(0);
7773     SDValue N1 = N->getOperand(1);
7774     SDValue N2 = N->getOperand(2);
7775     if (isZeroOrAllOnes(N1, AllOnes)) {
7776       Invert = false;
7777       OtherOp = N2;
7778       return true;
7779     }
7780     if (isZeroOrAllOnes(N2, AllOnes)) {
7781       Invert = true;
7782       OtherOp = N1;
7783       return true;
7784     }
7785     return false;
7786   }
7787   case ISD::ZERO_EXTEND:
7788     // (zext cc) can never be the all ones value.
7789     if (AllOnes)
7790       return false;
7791     // Fall through.
7792   case ISD::SIGN_EXTEND: {
7793     EVT VT = N->getValueType(0);
7794     CC = N->getOperand(0);
7795     if (CC.getValueType() != MVT::i1)
7796       return false;
7797     Invert = !AllOnes;
7798     if (AllOnes)
7799       // When looking for an AllOnes constant, N is an sext, and the 'other'
7800       // value is 0.
7801       OtherOp = DAG.getConstant(0, VT);
7802     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7803       // When looking for a 0 constant, N can be zext or sext.
7804       OtherOp = DAG.getConstant(1, VT);
7805     else
7806       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7807     return true;
7808   }
7809   }
7810 }
7811
7812 // Combine a constant select operand into its use:
7813 //
7814 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7815 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7816 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7817 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7818 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7819 //
7820 // The transform is rejected if the select doesn't have a constant operand that
7821 // is null, or all ones when AllOnes is set.
7822 //
7823 // Also recognize sext/zext from i1:
7824 //
7825 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7826 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7827 //
7828 // These transformations eventually create predicated instructions.
7829 //
7830 // @param N       The node to transform.
7831 // @param Slct    The N operand that is a select.
7832 // @param OtherOp The other N operand (x above).
7833 // @param DCI     Context.
7834 // @param AllOnes Require the select constant to be all ones instead of null.
7835 // @returns The new node, or SDValue() on failure.
7836 static
7837 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7838                             TargetLowering::DAGCombinerInfo &DCI,
7839                             bool AllOnes = false) {
7840   SelectionDAG &DAG = DCI.DAG;
7841   EVT VT = N->getValueType(0);
7842   SDValue NonConstantVal;
7843   SDValue CCOp;
7844   bool SwapSelectOps;
7845   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7846                                   NonConstantVal, DAG))
7847     return SDValue();
7848
7849   // Slct is now know to be the desired identity constant when CC is true.
7850   SDValue TrueVal = OtherOp;
7851   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7852                                  OtherOp, NonConstantVal);
7853   // Unless SwapSelectOps says CC should be false.
7854   if (SwapSelectOps)
7855     std::swap(TrueVal, FalseVal);
7856
7857   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7858                      CCOp, TrueVal, FalseVal);
7859 }
7860
7861 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7862 static
7863 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7864                                        TargetLowering::DAGCombinerInfo &DCI) {
7865   SDValue N0 = N->getOperand(0);
7866   SDValue N1 = N->getOperand(1);
7867   if (N0.getNode()->hasOneUse()) {
7868     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7869     if (Result.getNode())
7870       return Result;
7871   }
7872   if (N1.getNode()->hasOneUse()) {
7873     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7874     if (Result.getNode())
7875       return Result;
7876   }
7877   return SDValue();
7878 }
7879
7880 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7881 // (only after legalization).
7882 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7883                                  TargetLowering::DAGCombinerInfo &DCI,
7884                                  const ARMSubtarget *Subtarget) {
7885
7886   // Only perform optimization if after legalize, and if NEON is available. We
7887   // also expected both operands to be BUILD_VECTORs.
7888   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7889       || N0.getOpcode() != ISD::BUILD_VECTOR
7890       || N1.getOpcode() != ISD::BUILD_VECTOR)
7891     return SDValue();
7892
7893   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7894   EVT VT = N->getValueType(0);
7895   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7896     return SDValue();
7897
7898   // Check that the vector operands are of the right form.
7899   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7900   // operands, where N is the size of the formed vector.
7901   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7902   // index such that we have a pair wise add pattern.
7903
7904   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7905   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7906     return SDValue();
7907   SDValue Vec = N0->getOperand(0)->getOperand(0);
7908   SDNode *V = Vec.getNode();
7909   unsigned nextIndex = 0;
7910
7911   // For each operands to the ADD which are BUILD_VECTORs,
7912   // check to see if each of their operands are an EXTRACT_VECTOR with
7913   // the same vector and appropriate index.
7914   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7915     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7916         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7917
7918       SDValue ExtVec0 = N0->getOperand(i);
7919       SDValue ExtVec1 = N1->getOperand(i);
7920
7921       // First operand is the vector, verify its the same.
7922       if (V != ExtVec0->getOperand(0).getNode() ||
7923           V != ExtVec1->getOperand(0).getNode())
7924         return SDValue();
7925
7926       // Second is the constant, verify its correct.
7927       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7928       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7929
7930       // For the constant, we want to see all the even or all the odd.
7931       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7932           || C1->getZExtValue() != nextIndex+1)
7933         return SDValue();
7934
7935       // Increment index.
7936       nextIndex+=2;
7937     } else
7938       return SDValue();
7939   }
7940
7941   // Create VPADDL node.
7942   SelectionDAG &DAG = DCI.DAG;
7943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7944
7945   // Build operand list.
7946   SmallVector<SDValue, 8> Ops;
7947   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7948                                 TLI.getPointerTy()));
7949
7950   // Input is the vector.
7951   Ops.push_back(Vec);
7952
7953   // Get widened type and narrowed type.
7954   MVT widenType;
7955   unsigned numElem = VT.getVectorNumElements();
7956   
7957   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7958   switch (inputLaneType.getSimpleVT().SimpleTy) {
7959     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7960     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7961     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7962     default:
7963       llvm_unreachable("Invalid vector element type for padd optimization.");
7964   }
7965
7966   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7967   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7968   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7969 }
7970
7971 static SDValue findMUL_LOHI(SDValue V) {
7972   if (V->getOpcode() == ISD::UMUL_LOHI ||
7973       V->getOpcode() == ISD::SMUL_LOHI)
7974     return V;
7975   return SDValue();
7976 }
7977
7978 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7979                                      TargetLowering::DAGCombinerInfo &DCI,
7980                                      const ARMSubtarget *Subtarget) {
7981
7982   if (Subtarget->isThumb1Only()) return SDValue();
7983
7984   // Only perform the checks after legalize when the pattern is available.
7985   if (DCI.isBeforeLegalize()) return SDValue();
7986
7987   // Look for multiply add opportunities.
7988   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7989   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7990   // a glue link from the first add to the second add.
7991   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7992   // a S/UMLAL instruction.
7993   //          loAdd   UMUL_LOHI
7994   //            \    / :lo    \ :hi
7995   //             \  /          \          [no multiline comment]
7996   //              ADDC         |  hiAdd
7997   //                 \ :glue  /  /
7998   //                  \      /  /
7999   //                    ADDE
8000   //
8001   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8002   SDValue AddcOp0 = AddcNode->getOperand(0);
8003   SDValue AddcOp1 = AddcNode->getOperand(1);
8004
8005   // Check if the two operands are from the same mul_lohi node.
8006   if (AddcOp0.getNode() == AddcOp1.getNode())
8007     return SDValue();
8008
8009   assert(AddcNode->getNumValues() == 2 &&
8010          AddcNode->getValueType(0) == MVT::i32 &&
8011          "Expect ADDC with two result values. First: i32");
8012
8013   // Check that we have a glued ADDC node.
8014   if (AddcNode->getValueType(1) != MVT::Glue)
8015     return SDValue();
8016
8017   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8018   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8019       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8020       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8021       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8022     return SDValue();
8023
8024   // Look for the glued ADDE.
8025   SDNode* AddeNode = AddcNode->getGluedUser();
8026   if (!AddeNode)
8027     return SDValue();
8028
8029   // Make sure it is really an ADDE.
8030   if (AddeNode->getOpcode() != ISD::ADDE)
8031     return SDValue();
8032
8033   assert(AddeNode->getNumOperands() == 3 &&
8034          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8035          "ADDE node has the wrong inputs");
8036
8037   // Check for the triangle shape.
8038   SDValue AddeOp0 = AddeNode->getOperand(0);
8039   SDValue AddeOp1 = AddeNode->getOperand(1);
8040
8041   // Make sure that the ADDE operands are not coming from the same node.
8042   if (AddeOp0.getNode() == AddeOp1.getNode())
8043     return SDValue();
8044
8045   // Find the MUL_LOHI node walking up ADDE's operands.
8046   bool IsLeftOperandMUL = false;
8047   SDValue MULOp = findMUL_LOHI(AddeOp0);
8048   if (MULOp == SDValue())
8049    MULOp = findMUL_LOHI(AddeOp1);
8050   else
8051     IsLeftOperandMUL = true;
8052   if (MULOp == SDValue())
8053     return SDValue();
8054
8055   // Figure out the right opcode.
8056   unsigned Opc = MULOp->getOpcode();
8057   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8058
8059   // Figure out the high and low input values to the MLAL node.
8060   SDValue* HiAdd = nullptr;
8061   SDValue* LoMul = nullptr;
8062   SDValue* LowAdd = nullptr;
8063
8064   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8065   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8066     return SDValue();
8067
8068   if (IsLeftOperandMUL)
8069     HiAdd = &AddeOp1;
8070   else
8071     HiAdd = &AddeOp0;
8072
8073
8074   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8075   // whose low result is fed to the ADDC we are checking.
8076
8077   if (AddcOp0 == MULOp.getValue(0)) {
8078     LoMul = &AddcOp0;
8079     LowAdd = &AddcOp1;
8080   }
8081   if (AddcOp1 == MULOp.getValue(0)) {
8082     LoMul = &AddcOp1;
8083     LowAdd = &AddcOp0;
8084   }
8085
8086   if (!LoMul)
8087     return SDValue();
8088
8089   // Create the merged node.
8090   SelectionDAG &DAG = DCI.DAG;
8091
8092   // Build operand list.
8093   SmallVector<SDValue, 8> Ops;
8094   Ops.push_back(LoMul->getOperand(0));
8095   Ops.push_back(LoMul->getOperand(1));
8096   Ops.push_back(*LowAdd);
8097   Ops.push_back(*HiAdd);
8098
8099   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8100                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8101
8102   // Replace the ADDs' nodes uses by the MLA node's values.
8103   SDValue HiMLALResult(MLALNode.getNode(), 1);
8104   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8105
8106   SDValue LoMLALResult(MLALNode.getNode(), 0);
8107   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8108
8109   // Return original node to notify the driver to stop replacing.
8110   SDValue resNode(AddcNode, 0);
8111   return resNode;
8112 }
8113
8114 /// PerformADDCCombine - Target-specific dag combine transform from
8115 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8116 static SDValue PerformADDCCombine(SDNode *N,
8117                                  TargetLowering::DAGCombinerInfo &DCI,
8118                                  const ARMSubtarget *Subtarget) {
8119
8120   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8121
8122 }
8123
8124 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8125 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8126 /// called with the default operands, and if that fails, with commuted
8127 /// operands.
8128 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8129                                           TargetLowering::DAGCombinerInfo &DCI,
8130                                           const ARMSubtarget *Subtarget){
8131
8132   // Attempt to create vpaddl for this add.
8133   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8134   if (Result.getNode())
8135     return Result;
8136
8137   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8138   if (N0.getNode()->hasOneUse()) {
8139     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8140     if (Result.getNode()) return Result;
8141   }
8142   return SDValue();
8143 }
8144
8145 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8146 ///
8147 static SDValue PerformADDCombine(SDNode *N,
8148                                  TargetLowering::DAGCombinerInfo &DCI,
8149                                  const ARMSubtarget *Subtarget) {
8150   SDValue N0 = N->getOperand(0);
8151   SDValue N1 = N->getOperand(1);
8152
8153   // First try with the default operand order.
8154   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8155   if (Result.getNode())
8156     return Result;
8157
8158   // If that didn't work, try again with the operands commuted.
8159   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8160 }
8161
8162 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8163 ///
8164 static SDValue PerformSUBCombine(SDNode *N,
8165                                  TargetLowering::DAGCombinerInfo &DCI) {
8166   SDValue N0 = N->getOperand(0);
8167   SDValue N1 = N->getOperand(1);
8168
8169   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8170   if (N1.getNode()->hasOneUse()) {
8171     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8172     if (Result.getNode()) return Result;
8173   }
8174
8175   return SDValue();
8176 }
8177
8178 /// PerformVMULCombine
8179 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8180 /// special multiplier accumulator forwarding.
8181 ///   vmul d3, d0, d2
8182 ///   vmla d3, d1, d2
8183 /// is faster than
8184 ///   vadd d3, d0, d1
8185 ///   vmul d3, d3, d2
8186 //  However, for (A + B) * (A + B),
8187 //    vadd d2, d0, d1
8188 //    vmul d3, d0, d2
8189 //    vmla d3, d1, d2
8190 //  is slower than
8191 //    vadd d2, d0, d1
8192 //    vmul d3, d2, d2
8193 static SDValue PerformVMULCombine(SDNode *N,
8194                                   TargetLowering::DAGCombinerInfo &DCI,
8195                                   const ARMSubtarget *Subtarget) {
8196   if (!Subtarget->hasVMLxForwarding())
8197     return SDValue();
8198
8199   SelectionDAG &DAG = DCI.DAG;
8200   SDValue N0 = N->getOperand(0);
8201   SDValue N1 = N->getOperand(1);
8202   unsigned Opcode = N0.getOpcode();
8203   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8204       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8205     Opcode = N1.getOpcode();
8206     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8207         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8208       return SDValue();
8209     std::swap(N0, N1);
8210   }
8211
8212   if (N0 == N1)
8213     return SDValue();
8214
8215   EVT VT = N->getValueType(0);
8216   SDLoc DL(N);
8217   SDValue N00 = N0->getOperand(0);
8218   SDValue N01 = N0->getOperand(1);
8219   return DAG.getNode(Opcode, DL, VT,
8220                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8221                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8222 }
8223
8224 static SDValue PerformMULCombine(SDNode *N,
8225                                  TargetLowering::DAGCombinerInfo &DCI,
8226                                  const ARMSubtarget *Subtarget) {
8227   SelectionDAG &DAG = DCI.DAG;
8228
8229   if (Subtarget->isThumb1Only())
8230     return SDValue();
8231
8232   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8233     return SDValue();
8234
8235   EVT VT = N->getValueType(0);
8236   if (VT.is64BitVector() || VT.is128BitVector())
8237     return PerformVMULCombine(N, DCI, Subtarget);
8238   if (VT != MVT::i32)
8239     return SDValue();
8240
8241   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8242   if (!C)
8243     return SDValue();
8244
8245   int64_t MulAmt = C->getSExtValue();
8246   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8247
8248   ShiftAmt = ShiftAmt & (32 - 1);
8249   SDValue V = N->getOperand(0);
8250   SDLoc DL(N);
8251
8252   SDValue Res;
8253   MulAmt >>= ShiftAmt;
8254
8255   if (MulAmt >= 0) {
8256     if (isPowerOf2_32(MulAmt - 1)) {
8257       // (mul x, 2^N + 1) => (add (shl x, N), x)
8258       Res = DAG.getNode(ISD::ADD, DL, VT,
8259                         V,
8260                         DAG.getNode(ISD::SHL, DL, VT,
8261                                     V,
8262                                     DAG.getConstant(Log2_32(MulAmt - 1),
8263                                                     MVT::i32)));
8264     } else if (isPowerOf2_32(MulAmt + 1)) {
8265       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8266       Res = DAG.getNode(ISD::SUB, DL, VT,
8267                         DAG.getNode(ISD::SHL, DL, VT,
8268                                     V,
8269                                     DAG.getConstant(Log2_32(MulAmt + 1),
8270                                                     MVT::i32)),
8271                         V);
8272     } else
8273       return SDValue();
8274   } else {
8275     uint64_t MulAmtAbs = -MulAmt;
8276     if (isPowerOf2_32(MulAmtAbs + 1)) {
8277       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8278       Res = DAG.getNode(ISD::SUB, DL, VT,
8279                         V,
8280                         DAG.getNode(ISD::SHL, DL, VT,
8281                                     V,
8282                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8283                                                     MVT::i32)));
8284     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8285       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8286       Res = DAG.getNode(ISD::ADD, DL, VT,
8287                         V,
8288                         DAG.getNode(ISD::SHL, DL, VT,
8289                                     V,
8290                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8291                                                     MVT::i32)));
8292       Res = DAG.getNode(ISD::SUB, DL, VT,
8293                         DAG.getConstant(0, MVT::i32),Res);
8294
8295     } else
8296       return SDValue();
8297   }
8298
8299   if (ShiftAmt != 0)
8300     Res = DAG.getNode(ISD::SHL, DL, VT,
8301                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8302
8303   // Do not add new nodes to DAG combiner worklist.
8304   DCI.CombineTo(N, Res, false);
8305   return SDValue();
8306 }
8307
8308 static SDValue PerformANDCombine(SDNode *N,
8309                                  TargetLowering::DAGCombinerInfo &DCI,
8310                                  const ARMSubtarget *Subtarget) {
8311
8312   // Attempt to use immediate-form VBIC
8313   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8314   SDLoc dl(N);
8315   EVT VT = N->getValueType(0);
8316   SelectionDAG &DAG = DCI.DAG;
8317
8318   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8319     return SDValue();
8320
8321   APInt SplatBits, SplatUndef;
8322   unsigned SplatBitSize;
8323   bool HasAnyUndefs;
8324   if (BVN &&
8325       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8326     if (SplatBitSize <= 64) {
8327       EVT VbicVT;
8328       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8329                                       SplatUndef.getZExtValue(), SplatBitSize,
8330                                       DAG, VbicVT, VT.is128BitVector(),
8331                                       OtherModImm);
8332       if (Val.getNode()) {
8333         SDValue Input =
8334           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8335         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8336         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8337       }
8338     }
8339   }
8340
8341   if (!Subtarget->isThumb1Only()) {
8342     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8343     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8344     if (Result.getNode())
8345       return Result;
8346   }
8347
8348   return SDValue();
8349 }
8350
8351 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8352 static SDValue PerformORCombine(SDNode *N,
8353                                 TargetLowering::DAGCombinerInfo &DCI,
8354                                 const ARMSubtarget *Subtarget) {
8355   // Attempt to use immediate-form VORR
8356   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8357   SDLoc dl(N);
8358   EVT VT = N->getValueType(0);
8359   SelectionDAG &DAG = DCI.DAG;
8360
8361   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8362     return SDValue();
8363
8364   APInt SplatBits, SplatUndef;
8365   unsigned SplatBitSize;
8366   bool HasAnyUndefs;
8367   if (BVN && Subtarget->hasNEON() &&
8368       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8369     if (SplatBitSize <= 64) {
8370       EVT VorrVT;
8371       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8372                                       SplatUndef.getZExtValue(), SplatBitSize,
8373                                       DAG, VorrVT, VT.is128BitVector(),
8374                                       OtherModImm);
8375       if (Val.getNode()) {
8376         SDValue Input =
8377           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8378         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8379         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8380       }
8381     }
8382   }
8383
8384   if (!Subtarget->isThumb1Only()) {
8385     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8386     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8387     if (Result.getNode())
8388       return Result;
8389   }
8390
8391   // The code below optimizes (or (and X, Y), Z).
8392   // The AND operand needs to have a single user to make these optimizations
8393   // profitable.
8394   SDValue N0 = N->getOperand(0);
8395   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8396     return SDValue();
8397   SDValue N1 = N->getOperand(1);
8398
8399   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8400   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8401       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8402     APInt SplatUndef;
8403     unsigned SplatBitSize;
8404     bool HasAnyUndefs;
8405
8406     APInt SplatBits0, SplatBits1;
8407     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8408     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8409     // Ensure that the second operand of both ands are constants
8410     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8411                                       HasAnyUndefs) && !HasAnyUndefs) {
8412         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8413                                           HasAnyUndefs) && !HasAnyUndefs) {
8414             // Ensure that the bit width of the constants are the same and that
8415             // the splat arguments are logical inverses as per the pattern we
8416             // are trying to simplify.
8417             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8418                 SplatBits0 == ~SplatBits1) {
8419                 // Canonicalize the vector type to make instruction selection
8420                 // simpler.
8421                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8422                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8423                                              N0->getOperand(1),
8424                                              N0->getOperand(0),
8425                                              N1->getOperand(0));
8426                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8427             }
8428         }
8429     }
8430   }
8431
8432   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8433   // reasonable.
8434
8435   // BFI is only available on V6T2+
8436   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8437     return SDValue();
8438
8439   SDLoc DL(N);
8440   // 1) or (and A, mask), val => ARMbfi A, val, mask
8441   //      iff (val & mask) == val
8442   //
8443   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8444   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8445   //          && mask == ~mask2
8446   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8447   //          && ~mask == mask2
8448   //  (i.e., copy a bitfield value into another bitfield of the same width)
8449
8450   if (VT != MVT::i32)
8451     return SDValue();
8452
8453   SDValue N00 = N0.getOperand(0);
8454
8455   // The value and the mask need to be constants so we can verify this is
8456   // actually a bitfield set. If the mask is 0xffff, we can do better
8457   // via a movt instruction, so don't use BFI in that case.
8458   SDValue MaskOp = N0.getOperand(1);
8459   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8460   if (!MaskC)
8461     return SDValue();
8462   unsigned Mask = MaskC->getZExtValue();
8463   if (Mask == 0xffff)
8464     return SDValue();
8465   SDValue Res;
8466   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8467   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8468   if (N1C) {
8469     unsigned Val = N1C->getZExtValue();
8470     if ((Val & ~Mask) != Val)
8471       return SDValue();
8472
8473     if (ARM::isBitFieldInvertedMask(Mask)) {
8474       Val >>= countTrailingZeros(~Mask);
8475
8476       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8477                         DAG.getConstant(Val, MVT::i32),
8478                         DAG.getConstant(Mask, MVT::i32));
8479
8480       // Do not add new nodes to DAG combiner worklist.
8481       DCI.CombineTo(N, Res, false);
8482       return SDValue();
8483     }
8484   } else if (N1.getOpcode() == ISD::AND) {
8485     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8486     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8487     if (!N11C)
8488       return SDValue();
8489     unsigned Mask2 = N11C->getZExtValue();
8490
8491     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8492     // as is to match.
8493     if (ARM::isBitFieldInvertedMask(Mask) &&
8494         (Mask == ~Mask2)) {
8495       // The pack halfword instruction works better for masks that fit it,
8496       // so use that when it's available.
8497       if (Subtarget->hasT2ExtractPack() &&
8498           (Mask == 0xffff || Mask == 0xffff0000))
8499         return SDValue();
8500       // 2a
8501       unsigned amt = countTrailingZeros(Mask2);
8502       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8503                         DAG.getConstant(amt, MVT::i32));
8504       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8505                         DAG.getConstant(Mask, MVT::i32));
8506       // Do not add new nodes to DAG combiner worklist.
8507       DCI.CombineTo(N, Res, false);
8508       return SDValue();
8509     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8510                (~Mask == Mask2)) {
8511       // The pack halfword instruction works better for masks that fit it,
8512       // so use that when it's available.
8513       if (Subtarget->hasT2ExtractPack() &&
8514           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8515         return SDValue();
8516       // 2b
8517       unsigned lsb = countTrailingZeros(Mask);
8518       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8519                         DAG.getConstant(lsb, MVT::i32));
8520       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8521                         DAG.getConstant(Mask2, MVT::i32));
8522       // Do not add new nodes to DAG combiner worklist.
8523       DCI.CombineTo(N, Res, false);
8524       return SDValue();
8525     }
8526   }
8527
8528   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8529       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8530       ARM::isBitFieldInvertedMask(~Mask)) {
8531     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8532     // where lsb(mask) == #shamt and masked bits of B are known zero.
8533     SDValue ShAmt = N00.getOperand(1);
8534     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8535     unsigned LSB = countTrailingZeros(Mask);
8536     if (ShAmtC != LSB)
8537       return SDValue();
8538
8539     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8540                       DAG.getConstant(~Mask, MVT::i32));
8541
8542     // Do not add new nodes to DAG combiner worklist.
8543     DCI.CombineTo(N, Res, false);
8544   }
8545
8546   return SDValue();
8547 }
8548
8549 static SDValue PerformXORCombine(SDNode *N,
8550                                  TargetLowering::DAGCombinerInfo &DCI,
8551                                  const ARMSubtarget *Subtarget) {
8552   EVT VT = N->getValueType(0);
8553   SelectionDAG &DAG = DCI.DAG;
8554
8555   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8556     return SDValue();
8557
8558   if (!Subtarget->isThumb1Only()) {
8559     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8560     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8561     if (Result.getNode())
8562       return Result;
8563   }
8564
8565   return SDValue();
8566 }
8567
8568 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8569 /// the bits being cleared by the AND are not demanded by the BFI.
8570 static SDValue PerformBFICombine(SDNode *N,
8571                                  TargetLowering::DAGCombinerInfo &DCI) {
8572   SDValue N1 = N->getOperand(1);
8573   if (N1.getOpcode() == ISD::AND) {
8574     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8575     if (!N11C)
8576       return SDValue();
8577     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8578     unsigned LSB = countTrailingZeros(~InvMask);
8579     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8580     assert(Width <
8581                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8582            "undefined behavior");
8583     unsigned Mask = (1u << Width) - 1;
8584     unsigned Mask2 = N11C->getZExtValue();
8585     if ((Mask & (~Mask2)) == 0)
8586       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8587                              N->getOperand(0), N1.getOperand(0),
8588                              N->getOperand(2));
8589   }
8590   return SDValue();
8591 }
8592
8593 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8594 /// ARMISD::VMOVRRD.
8595 static SDValue PerformVMOVRRDCombine(SDNode *N,
8596                                      TargetLowering::DAGCombinerInfo &DCI,
8597                                      const ARMSubtarget *Subtarget) {
8598   // vmovrrd(vmovdrr x, y) -> x,y
8599   SDValue InDouble = N->getOperand(0);
8600   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8601     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8602
8603   // vmovrrd(load f64) -> (load i32), (load i32)
8604   SDNode *InNode = InDouble.getNode();
8605   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8606       InNode->getValueType(0) == MVT::f64 &&
8607       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8608       !cast<LoadSDNode>(InNode)->isVolatile()) {
8609     // TODO: Should this be done for non-FrameIndex operands?
8610     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8611
8612     SelectionDAG &DAG = DCI.DAG;
8613     SDLoc DL(LD);
8614     SDValue BasePtr = LD->getBasePtr();
8615     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8616                                  LD->getPointerInfo(), LD->isVolatile(),
8617                                  LD->isNonTemporal(), LD->isInvariant(),
8618                                  LD->getAlignment());
8619
8620     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8621                                     DAG.getConstant(4, MVT::i32));
8622     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8623                                  LD->getPointerInfo(), LD->isVolatile(),
8624                                  LD->isNonTemporal(), LD->isInvariant(),
8625                                  std::min(4U, LD->getAlignment() / 2));
8626
8627     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8628     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8629       std::swap (NewLD1, NewLD2);
8630     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8631     return Result;
8632   }
8633
8634   return SDValue();
8635 }
8636
8637 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8638 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8639 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8640   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8641   SDValue Op0 = N->getOperand(0);
8642   SDValue Op1 = N->getOperand(1);
8643   if (Op0.getOpcode() == ISD::BITCAST)
8644     Op0 = Op0.getOperand(0);
8645   if (Op1.getOpcode() == ISD::BITCAST)
8646     Op1 = Op1.getOperand(0);
8647   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8648       Op0.getNode() == Op1.getNode() &&
8649       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8650     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8651                        N->getValueType(0), Op0.getOperand(0));
8652   return SDValue();
8653 }
8654
8655 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8656 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8657 /// i64 vector to have f64 elements, since the value can then be loaded
8658 /// directly into a VFP register.
8659 static bool hasNormalLoadOperand(SDNode *N) {
8660   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8661   for (unsigned i = 0; i < NumElts; ++i) {
8662     SDNode *Elt = N->getOperand(i).getNode();
8663     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8664       return true;
8665   }
8666   return false;
8667 }
8668
8669 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8670 /// ISD::BUILD_VECTOR.
8671 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8672                                           TargetLowering::DAGCombinerInfo &DCI,
8673                                           const ARMSubtarget *Subtarget) {
8674   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8675   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8676   // into a pair of GPRs, which is fine when the value is used as a scalar,
8677   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8678   SelectionDAG &DAG = DCI.DAG;
8679   if (N->getNumOperands() == 2) {
8680     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8681     if (RV.getNode())
8682       return RV;
8683   }
8684
8685   // Load i64 elements as f64 values so that type legalization does not split
8686   // them up into i32 values.
8687   EVT VT = N->getValueType(0);
8688   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8689     return SDValue();
8690   SDLoc dl(N);
8691   SmallVector<SDValue, 8> Ops;
8692   unsigned NumElts = VT.getVectorNumElements();
8693   for (unsigned i = 0; i < NumElts; ++i) {
8694     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8695     Ops.push_back(V);
8696     // Make the DAGCombiner fold the bitcast.
8697     DCI.AddToWorklist(V.getNode());
8698   }
8699   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8700   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8701   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8702 }
8703
8704 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8705 static SDValue
8706 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8707   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8708   // At that time, we may have inserted bitcasts from integer to float.
8709   // If these bitcasts have survived DAGCombine, change the lowering of this
8710   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8711   // force to use floating point types.
8712
8713   // Make sure we can change the type of the vector.
8714   // This is possible iff:
8715   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8716   //    1.1. Vector is used only once.
8717   //    1.2. Use is a bit convert to an integer type.
8718   // 2. The size of its operands are 32-bits (64-bits are not legal).
8719   EVT VT = N->getValueType(0);
8720   EVT EltVT = VT.getVectorElementType();
8721
8722   // Check 1.1. and 2.
8723   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8724     return SDValue();
8725
8726   // By construction, the input type must be float.
8727   assert(EltVT == MVT::f32 && "Unexpected type!");
8728
8729   // Check 1.2.
8730   SDNode *Use = *N->use_begin();
8731   if (Use->getOpcode() != ISD::BITCAST ||
8732       Use->getValueType(0).isFloatingPoint())
8733     return SDValue();
8734
8735   // Check profitability.
8736   // Model is, if more than half of the relevant operands are bitcast from
8737   // i32, turn the build_vector into a sequence of insert_vector_elt.
8738   // Relevant operands are everything that is not statically
8739   // (i.e., at compile time) bitcasted.
8740   unsigned NumOfBitCastedElts = 0;
8741   unsigned NumElts = VT.getVectorNumElements();
8742   unsigned NumOfRelevantElts = NumElts;
8743   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8744     SDValue Elt = N->getOperand(Idx);
8745     if (Elt->getOpcode() == ISD::BITCAST) {
8746       // Assume only bit cast to i32 will go away.
8747       if (Elt->getOperand(0).getValueType() == MVT::i32)
8748         ++NumOfBitCastedElts;
8749     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8750       // Constants are statically casted, thus do not count them as
8751       // relevant operands.
8752       --NumOfRelevantElts;
8753   }
8754
8755   // Check if more than half of the elements require a non-free bitcast.
8756   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8757     return SDValue();
8758
8759   SelectionDAG &DAG = DCI.DAG;
8760   // Create the new vector type.
8761   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8762   // Check if the type is legal.
8763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8764   if (!TLI.isTypeLegal(VecVT))
8765     return SDValue();
8766
8767   // Combine:
8768   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8769   // => BITCAST INSERT_VECTOR_ELT
8770   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8771   //                      (BITCAST EN), N.
8772   SDValue Vec = DAG.getUNDEF(VecVT);
8773   SDLoc dl(N);
8774   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8775     SDValue V = N->getOperand(Idx);
8776     if (V.getOpcode() == ISD::UNDEF)
8777       continue;
8778     if (V.getOpcode() == ISD::BITCAST &&
8779         V->getOperand(0).getValueType() == MVT::i32)
8780       // Fold obvious case.
8781       V = V.getOperand(0);
8782     else {
8783       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8784       // Make the DAGCombiner fold the bitcasts.
8785       DCI.AddToWorklist(V.getNode());
8786     }
8787     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8788     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8789   }
8790   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8791   // Make the DAGCombiner fold the bitcasts.
8792   DCI.AddToWorklist(Vec.getNode());
8793   return Vec;
8794 }
8795
8796 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8797 /// ISD::INSERT_VECTOR_ELT.
8798 static SDValue PerformInsertEltCombine(SDNode *N,
8799                                        TargetLowering::DAGCombinerInfo &DCI) {
8800   // Bitcast an i64 load inserted into a vector to f64.
8801   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8802   EVT VT = N->getValueType(0);
8803   SDNode *Elt = N->getOperand(1).getNode();
8804   if (VT.getVectorElementType() != MVT::i64 ||
8805       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8806     return SDValue();
8807
8808   SelectionDAG &DAG = DCI.DAG;
8809   SDLoc dl(N);
8810   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8811                                  VT.getVectorNumElements());
8812   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8813   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8814   // Make the DAGCombiner fold the bitcasts.
8815   DCI.AddToWorklist(Vec.getNode());
8816   DCI.AddToWorklist(V.getNode());
8817   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8818                                Vec, V, N->getOperand(2));
8819   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8820 }
8821
8822 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8823 /// ISD::VECTOR_SHUFFLE.
8824 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8825   // The LLVM shufflevector instruction does not require the shuffle mask
8826   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8827   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8828   // operands do not match the mask length, they are extended by concatenating
8829   // them with undef vectors.  That is probably the right thing for other
8830   // targets, but for NEON it is better to concatenate two double-register
8831   // size vector operands into a single quad-register size vector.  Do that
8832   // transformation here:
8833   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8834   //   shuffle(concat(v1, v2), undef)
8835   SDValue Op0 = N->getOperand(0);
8836   SDValue Op1 = N->getOperand(1);
8837   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8838       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8839       Op0.getNumOperands() != 2 ||
8840       Op1.getNumOperands() != 2)
8841     return SDValue();
8842   SDValue Concat0Op1 = Op0.getOperand(1);
8843   SDValue Concat1Op1 = Op1.getOperand(1);
8844   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8845       Concat1Op1.getOpcode() != ISD::UNDEF)
8846     return SDValue();
8847   // Skip the transformation if any of the types are illegal.
8848   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8849   EVT VT = N->getValueType(0);
8850   if (!TLI.isTypeLegal(VT) ||
8851       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8852       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8853     return SDValue();
8854
8855   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8856                                   Op0.getOperand(0), Op1.getOperand(0));
8857   // Translate the shuffle mask.
8858   SmallVector<int, 16> NewMask;
8859   unsigned NumElts = VT.getVectorNumElements();
8860   unsigned HalfElts = NumElts/2;
8861   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8862   for (unsigned n = 0; n < NumElts; ++n) {
8863     int MaskElt = SVN->getMaskElt(n);
8864     int NewElt = -1;
8865     if (MaskElt < (int)HalfElts)
8866       NewElt = MaskElt;
8867     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8868       NewElt = HalfElts + MaskElt - NumElts;
8869     NewMask.push_back(NewElt);
8870   }
8871   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8872                               DAG.getUNDEF(VT), NewMask.data());
8873 }
8874
8875 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8876 /// NEON load/store intrinsics to merge base address updates.
8877 static SDValue CombineBaseUpdate(SDNode *N,
8878                                  TargetLowering::DAGCombinerInfo &DCI) {
8879   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8880     return SDValue();
8881
8882   SelectionDAG &DAG = DCI.DAG;
8883   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8884                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8885   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8886   SDValue Addr = N->getOperand(AddrOpIdx);
8887
8888   // Search for a use of the address operand that is an increment.
8889   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8890          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8891     SDNode *User = *UI;
8892     if (User->getOpcode() != ISD::ADD ||
8893         UI.getUse().getResNo() != Addr.getResNo())
8894       continue;
8895
8896     // Check that the add is independent of the load/store.  Otherwise, folding
8897     // it would create a cycle.
8898     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8899       continue;
8900
8901     // Find the new opcode for the updating load/store.
8902     bool isLoad = true;
8903     bool isLaneOp = false;
8904     unsigned NewOpc = 0;
8905     unsigned NumVecs = 0;
8906     if (isIntrinsic) {
8907       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8908       switch (IntNo) {
8909       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8910       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8911         NumVecs = 1; break;
8912       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8913         NumVecs = 2; break;
8914       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8915         NumVecs = 3; break;
8916       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8917         NumVecs = 4; break;
8918       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8919         NumVecs = 2; isLaneOp = true; break;
8920       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8921         NumVecs = 3; isLaneOp = true; break;
8922       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8923         NumVecs = 4; isLaneOp = true; break;
8924       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8925         NumVecs = 1; isLoad = false; break;
8926       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8927         NumVecs = 2; isLoad = false; break;
8928       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8929         NumVecs = 3; isLoad = false; break;
8930       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8931         NumVecs = 4; isLoad = false; break;
8932       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8933         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8934       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8935         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8936       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8937         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8938       }
8939     } else {
8940       isLaneOp = true;
8941       switch (N->getOpcode()) {
8942       default: llvm_unreachable("unexpected opcode for Neon base update");
8943       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8944       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8945       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8946       }
8947     }
8948
8949     // Find the size of memory referenced by the load/store.
8950     EVT VecTy;
8951     if (isLoad)
8952       VecTy = N->getValueType(0);
8953     else
8954       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8955     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8956     if (isLaneOp)
8957       NumBytes /= VecTy.getVectorNumElements();
8958
8959     // If the increment is a constant, it must match the memory ref size.
8960     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8961     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8962       uint64_t IncVal = CInc->getZExtValue();
8963       if (IncVal != NumBytes)
8964         continue;
8965     } else if (NumBytes >= 3 * 16) {
8966       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8967       // separate instructions that make it harder to use a non-constant update.
8968       continue;
8969     }
8970
8971     // Create the new updating load/store node.
8972     EVT Tys[6];
8973     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8974     unsigned n;
8975     for (n = 0; n < NumResultVecs; ++n)
8976       Tys[n] = VecTy;
8977     Tys[n++] = MVT::i32;
8978     Tys[n] = MVT::Other;
8979     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8980     SmallVector<SDValue, 8> Ops;
8981     Ops.push_back(N->getOperand(0)); // incoming chain
8982     Ops.push_back(N->getOperand(AddrOpIdx));
8983     Ops.push_back(Inc);
8984     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8985       Ops.push_back(N->getOperand(i));
8986     }
8987     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8988     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8989                                            Ops, MemInt->getMemoryVT(),
8990                                            MemInt->getMemOperand());
8991
8992     // Update the uses.
8993     SmallVector<SDValue, 5> NewResults;
8994     for (unsigned i = 0; i < NumResultVecs; ++i) {
8995       NewResults.push_back(SDValue(UpdN.getNode(), i));
8996     }
8997     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8998     DCI.CombineTo(N, NewResults);
8999     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9000
9001     break;
9002   }
9003   return SDValue();
9004 }
9005
9006 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9007 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9008 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9009 /// return true.
9010 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9011   SelectionDAG &DAG = DCI.DAG;
9012   EVT VT = N->getValueType(0);
9013   // vldN-dup instructions only support 64-bit vectors for N > 1.
9014   if (!VT.is64BitVector())
9015     return false;
9016
9017   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9018   SDNode *VLD = N->getOperand(0).getNode();
9019   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9020     return false;
9021   unsigned NumVecs = 0;
9022   unsigned NewOpc = 0;
9023   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9024   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9025     NumVecs = 2;
9026     NewOpc = ARMISD::VLD2DUP;
9027   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9028     NumVecs = 3;
9029     NewOpc = ARMISD::VLD3DUP;
9030   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9031     NumVecs = 4;
9032     NewOpc = ARMISD::VLD4DUP;
9033   } else {
9034     return false;
9035   }
9036
9037   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9038   // numbers match the load.
9039   unsigned VLDLaneNo =
9040     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9041   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9042        UI != UE; ++UI) {
9043     // Ignore uses of the chain result.
9044     if (UI.getUse().getResNo() == NumVecs)
9045       continue;
9046     SDNode *User = *UI;
9047     if (User->getOpcode() != ARMISD::VDUPLANE ||
9048         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9049       return false;
9050   }
9051
9052   // Create the vldN-dup node.
9053   EVT Tys[5];
9054   unsigned n;
9055   for (n = 0; n < NumVecs; ++n)
9056     Tys[n] = VT;
9057   Tys[n] = MVT::Other;
9058   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9059   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9060   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9061   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9062                                            Ops, VLDMemInt->getMemoryVT(),
9063                                            VLDMemInt->getMemOperand());
9064
9065   // Update the uses.
9066   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9067        UI != UE; ++UI) {
9068     unsigned ResNo = UI.getUse().getResNo();
9069     // Ignore uses of the chain result.
9070     if (ResNo == NumVecs)
9071       continue;
9072     SDNode *User = *UI;
9073     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9074   }
9075
9076   // Now the vldN-lane intrinsic is dead except for its chain result.
9077   // Update uses of the chain.
9078   std::vector<SDValue> VLDDupResults;
9079   for (unsigned n = 0; n < NumVecs; ++n)
9080     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9081   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9082   DCI.CombineTo(VLD, VLDDupResults);
9083
9084   return true;
9085 }
9086
9087 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9088 /// ARMISD::VDUPLANE.
9089 static SDValue PerformVDUPLANECombine(SDNode *N,
9090                                       TargetLowering::DAGCombinerInfo &DCI) {
9091   SDValue Op = N->getOperand(0);
9092
9093   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9094   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9095   if (CombineVLDDUP(N, DCI))
9096     return SDValue(N, 0);
9097
9098   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9099   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9100   while (Op.getOpcode() == ISD::BITCAST)
9101     Op = Op.getOperand(0);
9102   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9103     return SDValue();
9104
9105   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9106   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9107   // The canonical VMOV for a zero vector uses a 32-bit element size.
9108   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9109   unsigned EltBits;
9110   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9111     EltSize = 8;
9112   EVT VT = N->getValueType(0);
9113   if (EltSize > VT.getVectorElementType().getSizeInBits())
9114     return SDValue();
9115
9116   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9117 }
9118
9119 /// PerformSTORECombine - Target-specific dag combine xforms for
9120 /// ISD::STORE.
9121 static SDValue PerformSTORECombine(SDNode *N,
9122                                    TargetLowering::DAGCombinerInfo &DCI) {
9123   StoreSDNode *St = cast<StoreSDNode>(N);
9124   if (St->isVolatile())
9125     return SDValue();
9126
9127   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9128   // pack all of the elements in one place.  Next, store to memory in fewer
9129   // chunks.
9130   SDValue StVal = St->getValue();
9131   EVT VT = StVal.getValueType();
9132   if (St->isTruncatingStore() && VT.isVector()) {
9133     SelectionDAG &DAG = DCI.DAG;
9134     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9135     EVT StVT = St->getMemoryVT();
9136     unsigned NumElems = VT.getVectorNumElements();
9137     assert(StVT != VT && "Cannot truncate to the same type");
9138     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9139     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9140
9141     // From, To sizes and ElemCount must be pow of two
9142     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9143
9144     // We are going to use the original vector elt for storing.
9145     // Accumulated smaller vector elements must be a multiple of the store size.
9146     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9147
9148     unsigned SizeRatio  = FromEltSz / ToEltSz;
9149     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9150
9151     // Create a type on which we perform the shuffle.
9152     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9153                                      NumElems*SizeRatio);
9154     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9155
9156     SDLoc DL(St);
9157     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9158     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9159     for (unsigned i = 0; i < NumElems; ++i)
9160       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9161
9162     // Can't shuffle using an illegal type.
9163     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9164
9165     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9166                                 DAG.getUNDEF(WideVec.getValueType()),
9167                                 ShuffleVec.data());
9168     // At this point all of the data is stored at the bottom of the
9169     // register. We now need to save it to mem.
9170
9171     // Find the largest store unit
9172     MVT StoreType = MVT::i8;
9173     for (MVT Tp : MVT::integer_valuetypes()) {
9174       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9175         StoreType = Tp;
9176     }
9177     // Didn't find a legal store type.
9178     if (!TLI.isTypeLegal(StoreType))
9179       return SDValue();
9180
9181     // Bitcast the original vector into a vector of store-size units
9182     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9183             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9184     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9185     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9186     SmallVector<SDValue, 8> Chains;
9187     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9188                                         TLI.getPointerTy());
9189     SDValue BasePtr = St->getBasePtr();
9190
9191     // Perform one or more big stores into memory.
9192     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9193     for (unsigned I = 0; I < E; I++) {
9194       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9195                                    StoreType, ShuffWide,
9196                                    DAG.getIntPtrConstant(I));
9197       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9198                                 St->getPointerInfo(), St->isVolatile(),
9199                                 St->isNonTemporal(), St->getAlignment());
9200       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9201                             Increment);
9202       Chains.push_back(Ch);
9203     }
9204     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9205   }
9206
9207   if (!ISD::isNormalStore(St))
9208     return SDValue();
9209
9210   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9211   // ARM stores of arguments in the same cache line.
9212   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9213       StVal.getNode()->hasOneUse()) {
9214     SelectionDAG  &DAG = DCI.DAG;
9215     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9216     SDLoc DL(St);
9217     SDValue BasePtr = St->getBasePtr();
9218     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9219                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9220                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9221                                   St->isNonTemporal(), St->getAlignment());
9222
9223     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9224                                     DAG.getConstant(4, MVT::i32));
9225     return DAG.getStore(NewST1.getValue(0), DL,
9226                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9227                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9228                         St->isNonTemporal(),
9229                         std::min(4U, St->getAlignment() / 2));
9230   }
9231
9232   if (StVal.getValueType() == MVT::i64 &&
9233       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9234
9235     // Bitcast an i64 store extracted from a vector to f64.
9236     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9237     SelectionDAG &DAG = DCI.DAG;
9238     SDLoc dl(StVal);
9239     SDValue IntVec = StVal.getOperand(0);
9240     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9241                                    IntVec.getValueType().getVectorNumElements());
9242     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9243     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9244                                  Vec, StVal.getOperand(1));
9245     dl = SDLoc(N);
9246     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9247     // Make the DAGCombiner fold the bitcasts.
9248     DCI.AddToWorklist(Vec.getNode());
9249     DCI.AddToWorklist(ExtElt.getNode());
9250     DCI.AddToWorklist(V.getNode());
9251     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9252                         St->getPointerInfo(), St->isVolatile(),
9253                         St->isNonTemporal(), St->getAlignment(),
9254                         St->getAAInfo());
9255   }
9256
9257   return SDValue();
9258 }
9259
9260 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9261 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9262 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9263 {
9264   integerPart cN;
9265   integerPart c0 = 0;
9266   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9267        I != E; I++) {
9268     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9269     if (!C)
9270       return false;
9271
9272     bool isExact;
9273     APFloat APF = C->getValueAPF();
9274     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9275         != APFloat::opOK || !isExact)
9276       return false;
9277
9278     c0 = (I == 0) ? cN : c0;
9279     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9280       return false;
9281   }
9282   C = c0;
9283   return true;
9284 }
9285
9286 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9287 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9288 /// when the VMUL has a constant operand that is a power of 2.
9289 ///
9290 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9291 ///  vmul.f32        d16, d17, d16
9292 ///  vcvt.s32.f32    d16, d16
9293 /// becomes:
9294 ///  vcvt.s32.f32    d16, d16, #3
9295 static SDValue PerformVCVTCombine(SDNode *N,
9296                                   TargetLowering::DAGCombinerInfo &DCI,
9297                                   const ARMSubtarget *Subtarget) {
9298   SelectionDAG &DAG = DCI.DAG;
9299   SDValue Op = N->getOperand(0);
9300
9301   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9302       Op.getOpcode() != ISD::FMUL)
9303     return SDValue();
9304
9305   uint64_t C;
9306   SDValue N0 = Op->getOperand(0);
9307   SDValue ConstVec = Op->getOperand(1);
9308   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9309
9310   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9311       !isConstVecPow2(ConstVec, isSigned, C))
9312     return SDValue();
9313
9314   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9315   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9316   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9317   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9318       NumLanes > 4) {
9319     // These instructions only exist converting from f32 to i32. We can handle
9320     // smaller integers by generating an extra truncate, but larger ones would
9321     // be lossy. We also can't handle more then 4 lanes, since these intructions
9322     // only support v2i32/v4i32 types.
9323     return SDValue();
9324   }
9325
9326   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9327     Intrinsic::arm_neon_vcvtfp2fxu;
9328   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9329                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9330                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9331                                  DAG.getConstant(Log2_64(C), MVT::i32));
9332
9333   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9334     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9335
9336   return FixConv;
9337 }
9338
9339 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9340 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9341 /// when the VDIV has a constant operand that is a power of 2.
9342 ///
9343 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9344 ///  vcvt.f32.s32    d16, d16
9345 ///  vdiv.f32        d16, d17, d16
9346 /// becomes:
9347 ///  vcvt.f32.s32    d16, d16, #3
9348 static SDValue PerformVDIVCombine(SDNode *N,
9349                                   TargetLowering::DAGCombinerInfo &DCI,
9350                                   const ARMSubtarget *Subtarget) {
9351   SelectionDAG &DAG = DCI.DAG;
9352   SDValue Op = N->getOperand(0);
9353   unsigned OpOpcode = Op.getNode()->getOpcode();
9354
9355   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9356       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9357     return SDValue();
9358
9359   uint64_t C;
9360   SDValue ConstVec = N->getOperand(1);
9361   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9362
9363   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9364       !isConstVecPow2(ConstVec, isSigned, C))
9365     return SDValue();
9366
9367   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9368   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9369   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9370     // These instructions only exist converting from i32 to f32. We can handle
9371     // smaller integers by generating an extra extend, but larger ones would
9372     // be lossy.
9373     return SDValue();
9374   }
9375
9376   SDValue ConvInput = Op.getOperand(0);
9377   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9378   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9379     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9380                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9381                             ConvInput);
9382
9383   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9384     Intrinsic::arm_neon_vcvtfxu2fp;
9385   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9386                      Op.getValueType(),
9387                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9388                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9389 }
9390
9391 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9392 /// operand of a vector shift operation, where all the elements of the
9393 /// build_vector must have the same constant integer value.
9394 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9395   // Ignore bit_converts.
9396   while (Op.getOpcode() == ISD::BITCAST)
9397     Op = Op.getOperand(0);
9398   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9399   APInt SplatBits, SplatUndef;
9400   unsigned SplatBitSize;
9401   bool HasAnyUndefs;
9402   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9403                                       HasAnyUndefs, ElementBits) ||
9404       SplatBitSize > ElementBits)
9405     return false;
9406   Cnt = SplatBits.getSExtValue();
9407   return true;
9408 }
9409
9410 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9411 /// operand of a vector shift left operation.  That value must be in the range:
9412 ///   0 <= Value < ElementBits for a left shift; or
9413 ///   0 <= Value <= ElementBits for a long left shift.
9414 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9415   assert(VT.isVector() && "vector shift count is not a vector type");
9416   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9417   if (! getVShiftImm(Op, ElementBits, Cnt))
9418     return false;
9419   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9420 }
9421
9422 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9423 /// operand of a vector shift right operation.  For a shift opcode, the value
9424 /// is positive, but for an intrinsic the value count must be negative. The
9425 /// absolute value must be in the range:
9426 ///   1 <= |Value| <= ElementBits for a right shift; or
9427 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9428 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9429                          int64_t &Cnt) {
9430   assert(VT.isVector() && "vector shift count is not a vector type");
9431   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9432   if (! getVShiftImm(Op, ElementBits, Cnt))
9433     return false;
9434   if (isIntrinsic)
9435     Cnt = -Cnt;
9436   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9437 }
9438
9439 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9440 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9441   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9442   switch (IntNo) {
9443   default:
9444     // Don't do anything for most intrinsics.
9445     break;
9446
9447   // Vector shifts: check for immediate versions and lower them.
9448   // Note: This is done during DAG combining instead of DAG legalizing because
9449   // the build_vectors for 64-bit vector element shift counts are generally
9450   // not legal, and it is hard to see their values after they get legalized to
9451   // loads from a constant pool.
9452   case Intrinsic::arm_neon_vshifts:
9453   case Intrinsic::arm_neon_vshiftu:
9454   case Intrinsic::arm_neon_vrshifts:
9455   case Intrinsic::arm_neon_vrshiftu:
9456   case Intrinsic::arm_neon_vrshiftn:
9457   case Intrinsic::arm_neon_vqshifts:
9458   case Intrinsic::arm_neon_vqshiftu:
9459   case Intrinsic::arm_neon_vqshiftsu:
9460   case Intrinsic::arm_neon_vqshiftns:
9461   case Intrinsic::arm_neon_vqshiftnu:
9462   case Intrinsic::arm_neon_vqshiftnsu:
9463   case Intrinsic::arm_neon_vqrshiftns:
9464   case Intrinsic::arm_neon_vqrshiftnu:
9465   case Intrinsic::arm_neon_vqrshiftnsu: {
9466     EVT VT = N->getOperand(1).getValueType();
9467     int64_t Cnt;
9468     unsigned VShiftOpc = 0;
9469
9470     switch (IntNo) {
9471     case Intrinsic::arm_neon_vshifts:
9472     case Intrinsic::arm_neon_vshiftu:
9473       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9474         VShiftOpc = ARMISD::VSHL;
9475         break;
9476       }
9477       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9478         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9479                      ARMISD::VSHRs : ARMISD::VSHRu);
9480         break;
9481       }
9482       return SDValue();
9483
9484     case Intrinsic::arm_neon_vrshifts:
9485     case Intrinsic::arm_neon_vrshiftu:
9486       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9487         break;
9488       return SDValue();
9489
9490     case Intrinsic::arm_neon_vqshifts:
9491     case Intrinsic::arm_neon_vqshiftu:
9492       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9493         break;
9494       return SDValue();
9495
9496     case Intrinsic::arm_neon_vqshiftsu:
9497       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9498         break;
9499       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9500
9501     case Intrinsic::arm_neon_vrshiftn:
9502     case Intrinsic::arm_neon_vqshiftns:
9503     case Intrinsic::arm_neon_vqshiftnu:
9504     case Intrinsic::arm_neon_vqshiftnsu:
9505     case Intrinsic::arm_neon_vqrshiftns:
9506     case Intrinsic::arm_neon_vqrshiftnu:
9507     case Intrinsic::arm_neon_vqrshiftnsu:
9508       // Narrowing shifts require an immediate right shift.
9509       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9510         break;
9511       llvm_unreachable("invalid shift count for narrowing vector shift "
9512                        "intrinsic");
9513
9514     default:
9515       llvm_unreachable("unhandled vector shift");
9516     }
9517
9518     switch (IntNo) {
9519     case Intrinsic::arm_neon_vshifts:
9520     case Intrinsic::arm_neon_vshiftu:
9521       // Opcode already set above.
9522       break;
9523     case Intrinsic::arm_neon_vrshifts:
9524       VShiftOpc = ARMISD::VRSHRs; break;
9525     case Intrinsic::arm_neon_vrshiftu:
9526       VShiftOpc = ARMISD::VRSHRu; break;
9527     case Intrinsic::arm_neon_vrshiftn:
9528       VShiftOpc = ARMISD::VRSHRN; break;
9529     case Intrinsic::arm_neon_vqshifts:
9530       VShiftOpc = ARMISD::VQSHLs; break;
9531     case Intrinsic::arm_neon_vqshiftu:
9532       VShiftOpc = ARMISD::VQSHLu; break;
9533     case Intrinsic::arm_neon_vqshiftsu:
9534       VShiftOpc = ARMISD::VQSHLsu; break;
9535     case Intrinsic::arm_neon_vqshiftns:
9536       VShiftOpc = ARMISD::VQSHRNs; break;
9537     case Intrinsic::arm_neon_vqshiftnu:
9538       VShiftOpc = ARMISD::VQSHRNu; break;
9539     case Intrinsic::arm_neon_vqshiftnsu:
9540       VShiftOpc = ARMISD::VQSHRNsu; break;
9541     case Intrinsic::arm_neon_vqrshiftns:
9542       VShiftOpc = ARMISD::VQRSHRNs; break;
9543     case Intrinsic::arm_neon_vqrshiftnu:
9544       VShiftOpc = ARMISD::VQRSHRNu; break;
9545     case Intrinsic::arm_neon_vqrshiftnsu:
9546       VShiftOpc = ARMISD::VQRSHRNsu; break;
9547     }
9548
9549     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9550                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9551   }
9552
9553   case Intrinsic::arm_neon_vshiftins: {
9554     EVT VT = N->getOperand(1).getValueType();
9555     int64_t Cnt;
9556     unsigned VShiftOpc = 0;
9557
9558     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9559       VShiftOpc = ARMISD::VSLI;
9560     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9561       VShiftOpc = ARMISD::VSRI;
9562     else {
9563       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9564     }
9565
9566     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9567                        N->getOperand(1), N->getOperand(2),
9568                        DAG.getConstant(Cnt, MVT::i32));
9569   }
9570
9571   case Intrinsic::arm_neon_vqrshifts:
9572   case Intrinsic::arm_neon_vqrshiftu:
9573     // No immediate versions of these to check for.
9574     break;
9575   }
9576
9577   return SDValue();
9578 }
9579
9580 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9581 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9582 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9583 /// vector element shift counts are generally not legal, and it is hard to see
9584 /// their values after they get legalized to loads from a constant pool.
9585 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9586                                    const ARMSubtarget *ST) {
9587   EVT VT = N->getValueType(0);
9588   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9589     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9590     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9591     SDValue N1 = N->getOperand(1);
9592     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9593       SDValue N0 = N->getOperand(0);
9594       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9595           DAG.MaskedValueIsZero(N0.getOperand(0),
9596                                 APInt::getHighBitsSet(32, 16)))
9597         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9598     }
9599   }
9600
9601   // Nothing to be done for scalar shifts.
9602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9603   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9604     return SDValue();
9605
9606   assert(ST->hasNEON() && "unexpected vector shift");
9607   int64_t Cnt;
9608
9609   switch (N->getOpcode()) {
9610   default: llvm_unreachable("unexpected shift opcode");
9611
9612   case ISD::SHL:
9613     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9614       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9615                          DAG.getConstant(Cnt, MVT::i32));
9616     break;
9617
9618   case ISD::SRA:
9619   case ISD::SRL:
9620     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9621       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9622                             ARMISD::VSHRs : ARMISD::VSHRu);
9623       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9624                          DAG.getConstant(Cnt, MVT::i32));
9625     }
9626   }
9627   return SDValue();
9628 }
9629
9630 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9631 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9632 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9633                                     const ARMSubtarget *ST) {
9634   SDValue N0 = N->getOperand(0);
9635
9636   // Check for sign- and zero-extensions of vector extract operations of 8-
9637   // and 16-bit vector elements.  NEON supports these directly.  They are
9638   // handled during DAG combining because type legalization will promote them
9639   // to 32-bit types and it is messy to recognize the operations after that.
9640   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9641     SDValue Vec = N0.getOperand(0);
9642     SDValue Lane = N0.getOperand(1);
9643     EVT VT = N->getValueType(0);
9644     EVT EltVT = N0.getValueType();
9645     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9646
9647     if (VT == MVT::i32 &&
9648         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9649         TLI.isTypeLegal(Vec.getValueType()) &&
9650         isa<ConstantSDNode>(Lane)) {
9651
9652       unsigned Opc = 0;
9653       switch (N->getOpcode()) {
9654       default: llvm_unreachable("unexpected opcode");
9655       case ISD::SIGN_EXTEND:
9656         Opc = ARMISD::VGETLANEs;
9657         break;
9658       case ISD::ZERO_EXTEND:
9659       case ISD::ANY_EXTEND:
9660         Opc = ARMISD::VGETLANEu;
9661         break;
9662       }
9663       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9664     }
9665   }
9666
9667   return SDValue();
9668 }
9669
9670 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9671 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9672 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9673                                        const ARMSubtarget *ST) {
9674   // If the target supports NEON, try to use vmax/vmin instructions for f32
9675   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9676   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9677   // a NaN; only do the transformation when it matches that behavior.
9678
9679   // For now only do this when using NEON for FP operations; if using VFP, it
9680   // is not obvious that the benefit outweighs the cost of switching to the
9681   // NEON pipeline.
9682   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9683       N->getValueType(0) != MVT::f32)
9684     return SDValue();
9685
9686   SDValue CondLHS = N->getOperand(0);
9687   SDValue CondRHS = N->getOperand(1);
9688   SDValue LHS = N->getOperand(2);
9689   SDValue RHS = N->getOperand(3);
9690   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9691
9692   unsigned Opcode = 0;
9693   bool IsReversed;
9694   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9695     IsReversed = false; // x CC y ? x : y
9696   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9697     IsReversed = true ; // x CC y ? y : x
9698   } else {
9699     return SDValue();
9700   }
9701
9702   bool IsUnordered;
9703   switch (CC) {
9704   default: break;
9705   case ISD::SETOLT:
9706   case ISD::SETOLE:
9707   case ISD::SETLT:
9708   case ISD::SETLE:
9709   case ISD::SETULT:
9710   case ISD::SETULE:
9711     // If LHS is NaN, an ordered comparison will be false and the result will
9712     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9713     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9714     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9715     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9716       break;
9717     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9718     // will return -0, so vmin can only be used for unsafe math or if one of
9719     // the operands is known to be nonzero.
9720     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9721         !DAG.getTarget().Options.UnsafeFPMath &&
9722         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9723       break;
9724     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9725     break;
9726
9727   case ISD::SETOGT:
9728   case ISD::SETOGE:
9729   case ISD::SETGT:
9730   case ISD::SETGE:
9731   case ISD::SETUGT:
9732   case ISD::SETUGE:
9733     // If LHS is NaN, an ordered comparison will be false and the result will
9734     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9735     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9736     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9737     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9738       break;
9739     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9740     // will return +0, so vmax can only be used for unsafe math or if one of
9741     // the operands is known to be nonzero.
9742     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9743         !DAG.getTarget().Options.UnsafeFPMath &&
9744         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9745       break;
9746     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9747     break;
9748   }
9749
9750   if (!Opcode)
9751     return SDValue();
9752   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9753 }
9754
9755 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9756 SDValue
9757 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9758   SDValue Cmp = N->getOperand(4);
9759   if (Cmp.getOpcode() != ARMISD::CMPZ)
9760     // Only looking at EQ and NE cases.
9761     return SDValue();
9762
9763   EVT VT = N->getValueType(0);
9764   SDLoc dl(N);
9765   SDValue LHS = Cmp.getOperand(0);
9766   SDValue RHS = Cmp.getOperand(1);
9767   SDValue FalseVal = N->getOperand(0);
9768   SDValue TrueVal = N->getOperand(1);
9769   SDValue ARMcc = N->getOperand(2);
9770   ARMCC::CondCodes CC =
9771     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9772
9773   // Simplify
9774   //   mov     r1, r0
9775   //   cmp     r1, x
9776   //   mov     r0, y
9777   //   moveq   r0, x
9778   // to
9779   //   cmp     r0, x
9780   //   movne   r0, y
9781   //
9782   //   mov     r1, r0
9783   //   cmp     r1, x
9784   //   mov     r0, x
9785   //   movne   r0, y
9786   // to
9787   //   cmp     r0, x
9788   //   movne   r0, y
9789   /// FIXME: Turn this into a target neutral optimization?
9790   SDValue Res;
9791   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9792     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9793                       N->getOperand(3), Cmp);
9794   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9795     SDValue ARMcc;
9796     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9797     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9798                       N->getOperand(3), NewCmp);
9799   }
9800
9801   if (Res.getNode()) {
9802     APInt KnownZero, KnownOne;
9803     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9804     // Capture demanded bits information that would be otherwise lost.
9805     if (KnownZero == 0xfffffffe)
9806       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9807                         DAG.getValueType(MVT::i1));
9808     else if (KnownZero == 0xffffff00)
9809       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9810                         DAG.getValueType(MVT::i8));
9811     else if (KnownZero == 0xffff0000)
9812       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9813                         DAG.getValueType(MVT::i16));
9814   }
9815
9816   return Res;
9817 }
9818
9819 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9820                                              DAGCombinerInfo &DCI) const {
9821   switch (N->getOpcode()) {
9822   default: break;
9823   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9824   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9825   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9826   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9827   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9828   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9829   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9830   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9831   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9832   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9833   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9834   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9835   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9836   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9837   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9838   case ISD::FP_TO_SINT:
9839   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9840   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9841   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9842   case ISD::SHL:
9843   case ISD::SRA:
9844   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9845   case ISD::SIGN_EXTEND:
9846   case ISD::ZERO_EXTEND:
9847   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9848   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9849   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9850   case ARMISD::VLD2DUP:
9851   case ARMISD::VLD3DUP:
9852   case ARMISD::VLD4DUP:
9853     return CombineBaseUpdate(N, DCI);
9854   case ARMISD::BUILD_VECTOR:
9855     return PerformARMBUILD_VECTORCombine(N, DCI);
9856   case ISD::INTRINSIC_VOID:
9857   case ISD::INTRINSIC_W_CHAIN:
9858     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9859     case Intrinsic::arm_neon_vld1:
9860     case Intrinsic::arm_neon_vld2:
9861     case Intrinsic::arm_neon_vld3:
9862     case Intrinsic::arm_neon_vld4:
9863     case Intrinsic::arm_neon_vld2lane:
9864     case Intrinsic::arm_neon_vld3lane:
9865     case Intrinsic::arm_neon_vld4lane:
9866     case Intrinsic::arm_neon_vst1:
9867     case Intrinsic::arm_neon_vst2:
9868     case Intrinsic::arm_neon_vst3:
9869     case Intrinsic::arm_neon_vst4:
9870     case Intrinsic::arm_neon_vst2lane:
9871     case Intrinsic::arm_neon_vst3lane:
9872     case Intrinsic::arm_neon_vst4lane:
9873       return CombineBaseUpdate(N, DCI);
9874     default: break;
9875     }
9876     break;
9877   }
9878   return SDValue();
9879 }
9880
9881 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9882                                                           EVT VT) const {
9883   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9884 }
9885
9886 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9887                                                        unsigned,
9888                                                        unsigned,
9889                                                        bool *Fast) const {
9890   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9891   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9892
9893   switch (VT.getSimpleVT().SimpleTy) {
9894   default:
9895     return false;
9896   case MVT::i8:
9897   case MVT::i16:
9898   case MVT::i32: {
9899     // Unaligned access can use (for example) LRDB, LRDH, LDR
9900     if (AllowsUnaligned) {
9901       if (Fast)
9902         *Fast = Subtarget->hasV7Ops();
9903       return true;
9904     }
9905     return false;
9906   }
9907   case MVT::f64:
9908   case MVT::v2f64: {
9909     // For any little-endian targets with neon, we can support unaligned ld/st
9910     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9911     // A big-endian target may also explicitly support unaligned accesses
9912     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9913       if (Fast)
9914         *Fast = true;
9915       return true;
9916     }
9917     return false;
9918   }
9919   }
9920 }
9921
9922 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9923                        unsigned AlignCheck) {
9924   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9925           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9926 }
9927
9928 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9929                                            unsigned DstAlign, unsigned SrcAlign,
9930                                            bool IsMemset, bool ZeroMemset,
9931                                            bool MemcpyStrSrc,
9932                                            MachineFunction &MF) const {
9933   const Function *F = MF.getFunction();
9934
9935   // See if we can use NEON instructions for this...
9936   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
9937       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9938     bool Fast;
9939     if (Size >= 16 &&
9940         (memOpAlign(SrcAlign, DstAlign, 16) ||
9941          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9942       return MVT::v2f64;
9943     } else if (Size >= 8 &&
9944                (memOpAlign(SrcAlign, DstAlign, 8) ||
9945                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9946                  Fast))) {
9947       return MVT::f64;
9948     }
9949   }
9950
9951   // Lowering to i32/i16 if the size permits.
9952   if (Size >= 4)
9953     return MVT::i32;
9954   else if (Size >= 2)
9955     return MVT::i16;
9956
9957   // Let the target-independent logic figure it out.
9958   return MVT::Other;
9959 }
9960
9961 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9962   if (Val.getOpcode() != ISD::LOAD)
9963     return false;
9964
9965   EVT VT1 = Val.getValueType();
9966   if (!VT1.isSimple() || !VT1.isInteger() ||
9967       !VT2.isSimple() || !VT2.isInteger())
9968     return false;
9969
9970   switch (VT1.getSimpleVT().SimpleTy) {
9971   default: break;
9972   case MVT::i1:
9973   case MVT::i8:
9974   case MVT::i16:
9975     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9976     return true;
9977   }
9978
9979   return false;
9980 }
9981
9982 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9983   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9984     return false;
9985
9986   if (!isTypeLegal(EVT::getEVT(Ty1)))
9987     return false;
9988
9989   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9990
9991   // Assuming the caller doesn't have a zeroext or signext return parameter,
9992   // truncation all the way down to i1 is valid.
9993   return true;
9994 }
9995
9996
9997 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9998   if (V < 0)
9999     return false;
10000
10001   unsigned Scale = 1;
10002   switch (VT.getSimpleVT().SimpleTy) {
10003   default: return false;
10004   case MVT::i1:
10005   case MVT::i8:
10006     // Scale == 1;
10007     break;
10008   case MVT::i16:
10009     // Scale == 2;
10010     Scale = 2;
10011     break;
10012   case MVT::i32:
10013     // Scale == 4;
10014     Scale = 4;
10015     break;
10016   }
10017
10018   if ((V & (Scale - 1)) != 0)
10019     return false;
10020   V /= Scale;
10021   return V == (V & ((1LL << 5) - 1));
10022 }
10023
10024 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10025                                       const ARMSubtarget *Subtarget) {
10026   bool isNeg = false;
10027   if (V < 0) {
10028     isNeg = true;
10029     V = - V;
10030   }
10031
10032   switch (VT.getSimpleVT().SimpleTy) {
10033   default: return false;
10034   case MVT::i1:
10035   case MVT::i8:
10036   case MVT::i16:
10037   case MVT::i32:
10038     // + imm12 or - imm8
10039     if (isNeg)
10040       return V == (V & ((1LL << 8) - 1));
10041     return V == (V & ((1LL << 12) - 1));
10042   case MVT::f32:
10043   case MVT::f64:
10044     // Same as ARM mode. FIXME: NEON?
10045     if (!Subtarget->hasVFP2())
10046       return false;
10047     if ((V & 3) != 0)
10048       return false;
10049     V >>= 2;
10050     return V == (V & ((1LL << 8) - 1));
10051   }
10052 }
10053
10054 /// isLegalAddressImmediate - Return true if the integer value can be used
10055 /// as the offset of the target addressing mode for load / store of the
10056 /// given type.
10057 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10058                                     const ARMSubtarget *Subtarget) {
10059   if (V == 0)
10060     return true;
10061
10062   if (!VT.isSimple())
10063     return false;
10064
10065   if (Subtarget->isThumb1Only())
10066     return isLegalT1AddressImmediate(V, VT);
10067   else if (Subtarget->isThumb2())
10068     return isLegalT2AddressImmediate(V, VT, Subtarget);
10069
10070   // ARM mode.
10071   if (V < 0)
10072     V = - V;
10073   switch (VT.getSimpleVT().SimpleTy) {
10074   default: return false;
10075   case MVT::i1:
10076   case MVT::i8:
10077   case MVT::i32:
10078     // +- imm12
10079     return V == (V & ((1LL << 12) - 1));
10080   case MVT::i16:
10081     // +- imm8
10082     return V == (V & ((1LL << 8) - 1));
10083   case MVT::f32:
10084   case MVT::f64:
10085     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10086       return false;
10087     if ((V & 3) != 0)
10088       return false;
10089     V >>= 2;
10090     return V == (V & ((1LL << 8) - 1));
10091   }
10092 }
10093
10094 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10095                                                       EVT VT) const {
10096   int Scale = AM.Scale;
10097   if (Scale < 0)
10098     return false;
10099
10100   switch (VT.getSimpleVT().SimpleTy) {
10101   default: return false;
10102   case MVT::i1:
10103   case MVT::i8:
10104   case MVT::i16:
10105   case MVT::i32:
10106     if (Scale == 1)
10107       return true;
10108     // r + r << imm
10109     Scale = Scale & ~1;
10110     return Scale == 2 || Scale == 4 || Scale == 8;
10111   case MVT::i64:
10112     // r + r
10113     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10114       return true;
10115     return false;
10116   case MVT::isVoid:
10117     // Note, we allow "void" uses (basically, uses that aren't loads or
10118     // stores), because arm allows folding a scale into many arithmetic
10119     // operations.  This should be made more precise and revisited later.
10120
10121     // Allow r << imm, but the imm has to be a multiple of two.
10122     if (Scale & 1) return false;
10123     return isPowerOf2_32(Scale);
10124   }
10125 }
10126
10127 /// isLegalAddressingMode - Return true if the addressing mode represented
10128 /// by AM is legal for this target, for a load/store of the specified type.
10129 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10130                                               Type *Ty) const {
10131   EVT VT = getValueType(Ty, true);
10132   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10133     return false;
10134
10135   // Can never fold addr of global into load/store.
10136   if (AM.BaseGV)
10137     return false;
10138
10139   switch (AM.Scale) {
10140   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10141     break;
10142   case 1:
10143     if (Subtarget->isThumb1Only())
10144       return false;
10145     // FALL THROUGH.
10146   default:
10147     // ARM doesn't support any R+R*scale+imm addr modes.
10148     if (AM.BaseOffs)
10149       return false;
10150
10151     if (!VT.isSimple())
10152       return false;
10153
10154     if (Subtarget->isThumb2())
10155       return isLegalT2ScaledAddressingMode(AM, VT);
10156
10157     int Scale = AM.Scale;
10158     switch (VT.getSimpleVT().SimpleTy) {
10159     default: return false;
10160     case MVT::i1:
10161     case MVT::i8:
10162     case MVT::i32:
10163       if (Scale < 0) Scale = -Scale;
10164       if (Scale == 1)
10165         return true;
10166       // r + r << imm
10167       return isPowerOf2_32(Scale & ~1);
10168     case MVT::i16:
10169     case MVT::i64:
10170       // r + r
10171       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10172         return true;
10173       return false;
10174
10175     case MVT::isVoid:
10176       // Note, we allow "void" uses (basically, uses that aren't loads or
10177       // stores), because arm allows folding a scale into many arithmetic
10178       // operations.  This should be made more precise and revisited later.
10179
10180       // Allow r << imm, but the imm has to be a multiple of two.
10181       if (Scale & 1) return false;
10182       return isPowerOf2_32(Scale);
10183     }
10184   }
10185   return true;
10186 }
10187
10188 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10189 /// icmp immediate, that is the target has icmp instructions which can compare
10190 /// a register against the immediate without having to materialize the
10191 /// immediate into a register.
10192 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10193   // Thumb2 and ARM modes can use cmn for negative immediates.
10194   if (!Subtarget->isThumb())
10195     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10196   if (Subtarget->isThumb2())
10197     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10198   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10199   return Imm >= 0 && Imm <= 255;
10200 }
10201
10202 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10203 /// *or sub* immediate, that is the target has add or sub instructions which can
10204 /// add a register with the immediate without having to materialize the
10205 /// immediate into a register.
10206 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10207   // Same encoding for add/sub, just flip the sign.
10208   int64_t AbsImm = llvm::abs64(Imm);
10209   if (!Subtarget->isThumb())
10210     return ARM_AM::getSOImmVal(AbsImm) != -1;
10211   if (Subtarget->isThumb2())
10212     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10213   // Thumb1 only has 8-bit unsigned immediate.
10214   return AbsImm >= 0 && AbsImm <= 255;
10215 }
10216
10217 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10218                                       bool isSEXTLoad, SDValue &Base,
10219                                       SDValue &Offset, bool &isInc,
10220                                       SelectionDAG &DAG) {
10221   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10222     return false;
10223
10224   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10225     // AddressingMode 3
10226     Base = Ptr->getOperand(0);
10227     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10228       int RHSC = (int)RHS->getZExtValue();
10229       if (RHSC < 0 && RHSC > -256) {
10230         assert(Ptr->getOpcode() == ISD::ADD);
10231         isInc = false;
10232         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10233         return true;
10234       }
10235     }
10236     isInc = (Ptr->getOpcode() == ISD::ADD);
10237     Offset = Ptr->getOperand(1);
10238     return true;
10239   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10240     // AddressingMode 2
10241     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10242       int RHSC = (int)RHS->getZExtValue();
10243       if (RHSC < 0 && RHSC > -0x1000) {
10244         assert(Ptr->getOpcode() == ISD::ADD);
10245         isInc = false;
10246         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10247         Base = Ptr->getOperand(0);
10248         return true;
10249       }
10250     }
10251
10252     if (Ptr->getOpcode() == ISD::ADD) {
10253       isInc = true;
10254       ARM_AM::ShiftOpc ShOpcVal=
10255         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10256       if (ShOpcVal != ARM_AM::no_shift) {
10257         Base = Ptr->getOperand(1);
10258         Offset = Ptr->getOperand(0);
10259       } else {
10260         Base = Ptr->getOperand(0);
10261         Offset = Ptr->getOperand(1);
10262       }
10263       return true;
10264     }
10265
10266     isInc = (Ptr->getOpcode() == ISD::ADD);
10267     Base = Ptr->getOperand(0);
10268     Offset = Ptr->getOperand(1);
10269     return true;
10270   }
10271
10272   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10273   return false;
10274 }
10275
10276 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10277                                      bool isSEXTLoad, SDValue &Base,
10278                                      SDValue &Offset, bool &isInc,
10279                                      SelectionDAG &DAG) {
10280   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10281     return false;
10282
10283   Base = Ptr->getOperand(0);
10284   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10285     int RHSC = (int)RHS->getZExtValue();
10286     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10287       assert(Ptr->getOpcode() == ISD::ADD);
10288       isInc = false;
10289       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10290       return true;
10291     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10292       isInc = Ptr->getOpcode() == ISD::ADD;
10293       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10294       return true;
10295     }
10296   }
10297
10298   return false;
10299 }
10300
10301 /// getPreIndexedAddressParts - returns true by value, base pointer and
10302 /// offset pointer and addressing mode by reference if the node's address
10303 /// can be legally represented as pre-indexed load / store address.
10304 bool
10305 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10306                                              SDValue &Offset,
10307                                              ISD::MemIndexedMode &AM,
10308                                              SelectionDAG &DAG) const {
10309   if (Subtarget->isThumb1Only())
10310     return false;
10311
10312   EVT VT;
10313   SDValue Ptr;
10314   bool isSEXTLoad = false;
10315   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10316     Ptr = LD->getBasePtr();
10317     VT  = LD->getMemoryVT();
10318     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10319   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10320     Ptr = ST->getBasePtr();
10321     VT  = ST->getMemoryVT();
10322   } else
10323     return false;
10324
10325   bool isInc;
10326   bool isLegal = false;
10327   if (Subtarget->isThumb2())
10328     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10329                                        Offset, isInc, DAG);
10330   else
10331     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10332                                         Offset, isInc, DAG);
10333   if (!isLegal)
10334     return false;
10335
10336   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10337   return true;
10338 }
10339
10340 /// getPostIndexedAddressParts - returns true by value, base pointer and
10341 /// offset pointer and addressing mode by reference if this node can be
10342 /// combined with a load / store to form a post-indexed load / store.
10343 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10344                                                    SDValue &Base,
10345                                                    SDValue &Offset,
10346                                                    ISD::MemIndexedMode &AM,
10347                                                    SelectionDAG &DAG) const {
10348   if (Subtarget->isThumb1Only())
10349     return false;
10350
10351   EVT VT;
10352   SDValue Ptr;
10353   bool isSEXTLoad = false;
10354   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10355     VT  = LD->getMemoryVT();
10356     Ptr = LD->getBasePtr();
10357     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10358   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10359     VT  = ST->getMemoryVT();
10360     Ptr = ST->getBasePtr();
10361   } else
10362     return false;
10363
10364   bool isInc;
10365   bool isLegal = false;
10366   if (Subtarget->isThumb2())
10367     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10368                                        isInc, DAG);
10369   else
10370     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10371                                         isInc, DAG);
10372   if (!isLegal)
10373     return false;
10374
10375   if (Ptr != Base) {
10376     // Swap base ptr and offset to catch more post-index load / store when
10377     // it's legal. In Thumb2 mode, offset must be an immediate.
10378     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10379         !Subtarget->isThumb2())
10380       std::swap(Base, Offset);
10381
10382     // Post-indexed load / store update the base pointer.
10383     if (Ptr != Base)
10384       return false;
10385   }
10386
10387   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10388   return true;
10389 }
10390
10391 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10392                                                       APInt &KnownZero,
10393                                                       APInt &KnownOne,
10394                                                       const SelectionDAG &DAG,
10395                                                       unsigned Depth) const {
10396   unsigned BitWidth = KnownOne.getBitWidth();
10397   KnownZero = KnownOne = APInt(BitWidth, 0);
10398   switch (Op.getOpcode()) {
10399   default: break;
10400   case ARMISD::ADDC:
10401   case ARMISD::ADDE:
10402   case ARMISD::SUBC:
10403   case ARMISD::SUBE:
10404     // These nodes' second result is a boolean
10405     if (Op.getResNo() == 0)
10406       break;
10407     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10408     break;
10409   case ARMISD::CMOV: {
10410     // Bits are known zero/one if known on the LHS and RHS.
10411     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10412     if (KnownZero == 0 && KnownOne == 0) return;
10413
10414     APInt KnownZeroRHS, KnownOneRHS;
10415     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10416     KnownZero &= KnownZeroRHS;
10417     KnownOne  &= KnownOneRHS;
10418     return;
10419   }
10420   case ISD::INTRINSIC_W_CHAIN: {
10421     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10422     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10423     switch (IntID) {
10424     default: return;
10425     case Intrinsic::arm_ldaex:
10426     case Intrinsic::arm_ldrex: {
10427       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10428       unsigned MemBits = VT.getScalarType().getSizeInBits();
10429       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10430       return;
10431     }
10432     }
10433   }
10434   }
10435 }
10436
10437 //===----------------------------------------------------------------------===//
10438 //                           ARM Inline Assembly Support
10439 //===----------------------------------------------------------------------===//
10440
10441 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10442   // Looking for "rev" which is V6+.
10443   if (!Subtarget->hasV6Ops())
10444     return false;
10445
10446   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10447   std::string AsmStr = IA->getAsmString();
10448   SmallVector<StringRef, 4> AsmPieces;
10449   SplitString(AsmStr, AsmPieces, ";\n");
10450
10451   switch (AsmPieces.size()) {
10452   default: return false;
10453   case 1:
10454     AsmStr = AsmPieces[0];
10455     AsmPieces.clear();
10456     SplitString(AsmStr, AsmPieces, " \t,");
10457
10458     // rev $0, $1
10459     if (AsmPieces.size() == 3 &&
10460         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10461         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10462       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10463       if (Ty && Ty->getBitWidth() == 32)
10464         return IntrinsicLowering::LowerToByteSwap(CI);
10465     }
10466     break;
10467   }
10468
10469   return false;
10470 }
10471
10472 /// getConstraintType - Given a constraint letter, return the type of
10473 /// constraint it is for this target.
10474 ARMTargetLowering::ConstraintType
10475 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10476   if (Constraint.size() == 1) {
10477     switch (Constraint[0]) {
10478     default:  break;
10479     case 'l': return C_RegisterClass;
10480     case 'w': return C_RegisterClass;
10481     case 'h': return C_RegisterClass;
10482     case 'x': return C_RegisterClass;
10483     case 't': return C_RegisterClass;
10484     case 'j': return C_Other; // Constant for movw.
10485       // An address with a single base register. Due to the way we
10486       // currently handle addresses it is the same as an 'r' memory constraint.
10487     case 'Q': return C_Memory;
10488     }
10489   } else if (Constraint.size() == 2) {
10490     switch (Constraint[0]) {
10491     default: break;
10492     // All 'U+' constraints are addresses.
10493     case 'U': return C_Memory;
10494     }
10495   }
10496   return TargetLowering::getConstraintType(Constraint);
10497 }
10498
10499 /// Examine constraint type and operand type and determine a weight value.
10500 /// This object must already have been set up with the operand type
10501 /// and the current alternative constraint selected.
10502 TargetLowering::ConstraintWeight
10503 ARMTargetLowering::getSingleConstraintMatchWeight(
10504     AsmOperandInfo &info, const char *constraint) const {
10505   ConstraintWeight weight = CW_Invalid;
10506   Value *CallOperandVal = info.CallOperandVal;
10507     // If we don't have a value, we can't do a match,
10508     // but allow it at the lowest weight.
10509   if (!CallOperandVal)
10510     return CW_Default;
10511   Type *type = CallOperandVal->getType();
10512   // Look at the constraint type.
10513   switch (*constraint) {
10514   default:
10515     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10516     break;
10517   case 'l':
10518     if (type->isIntegerTy()) {
10519       if (Subtarget->isThumb())
10520         weight = CW_SpecificReg;
10521       else
10522         weight = CW_Register;
10523     }
10524     break;
10525   case 'w':
10526     if (type->isFloatingPointTy())
10527       weight = CW_Register;
10528     break;
10529   }
10530   return weight;
10531 }
10532
10533 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10534 RCPair
10535 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10536                                                 MVT VT) const {
10537   if (Constraint.size() == 1) {
10538     // GCC ARM Constraint Letters
10539     switch (Constraint[0]) {
10540     case 'l': // Low regs or general regs.
10541       if (Subtarget->isThumb())
10542         return RCPair(0U, &ARM::tGPRRegClass);
10543       return RCPair(0U, &ARM::GPRRegClass);
10544     case 'h': // High regs or no regs.
10545       if (Subtarget->isThumb())
10546         return RCPair(0U, &ARM::hGPRRegClass);
10547       break;
10548     case 'r':
10549       if (Subtarget->isThumb1Only())
10550         return RCPair(0U, &ARM::tGPRRegClass);
10551       return RCPair(0U, &ARM::GPRRegClass);
10552     case 'w':
10553       if (VT == MVT::Other)
10554         break;
10555       if (VT == MVT::f32)
10556         return RCPair(0U, &ARM::SPRRegClass);
10557       if (VT.getSizeInBits() == 64)
10558         return RCPair(0U, &ARM::DPRRegClass);
10559       if (VT.getSizeInBits() == 128)
10560         return RCPair(0U, &ARM::QPRRegClass);
10561       break;
10562     case 'x':
10563       if (VT == MVT::Other)
10564         break;
10565       if (VT == MVT::f32)
10566         return RCPair(0U, &ARM::SPR_8RegClass);
10567       if (VT.getSizeInBits() == 64)
10568         return RCPair(0U, &ARM::DPR_8RegClass);
10569       if (VT.getSizeInBits() == 128)
10570         return RCPair(0U, &ARM::QPR_8RegClass);
10571       break;
10572     case 't':
10573       if (VT == MVT::f32)
10574         return RCPair(0U, &ARM::SPRRegClass);
10575       break;
10576     }
10577   }
10578   if (StringRef("{cc}").equals_lower(Constraint))
10579     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10580
10581   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10582 }
10583
10584 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10585 /// vector.  If it is invalid, don't add anything to Ops.
10586 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10587                                                      std::string &Constraint,
10588                                                      std::vector<SDValue>&Ops,
10589                                                      SelectionDAG &DAG) const {
10590   SDValue Result;
10591
10592   // Currently only support length 1 constraints.
10593   if (Constraint.length() != 1) return;
10594
10595   char ConstraintLetter = Constraint[0];
10596   switch (ConstraintLetter) {
10597   default: break;
10598   case 'j':
10599   case 'I': case 'J': case 'K': case 'L':
10600   case 'M': case 'N': case 'O':
10601     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10602     if (!C)
10603       return;
10604
10605     int64_t CVal64 = C->getSExtValue();
10606     int CVal = (int) CVal64;
10607     // None of these constraints allow values larger than 32 bits.  Check
10608     // that the value fits in an int.
10609     if (CVal != CVal64)
10610       return;
10611
10612     switch (ConstraintLetter) {
10613       case 'j':
10614         // Constant suitable for movw, must be between 0 and
10615         // 65535.
10616         if (Subtarget->hasV6T2Ops())
10617           if (CVal >= 0 && CVal <= 65535)
10618             break;
10619         return;
10620       case 'I':
10621         if (Subtarget->isThumb1Only()) {
10622           // This must be a constant between 0 and 255, for ADD
10623           // immediates.
10624           if (CVal >= 0 && CVal <= 255)
10625             break;
10626         } else if (Subtarget->isThumb2()) {
10627           // A constant that can be used as an immediate value in a
10628           // data-processing instruction.
10629           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10630             break;
10631         } else {
10632           // A constant that can be used as an immediate value in a
10633           // data-processing instruction.
10634           if (ARM_AM::getSOImmVal(CVal) != -1)
10635             break;
10636         }
10637         return;
10638
10639       case 'J':
10640         if (Subtarget->isThumb()) {  // FIXME thumb2
10641           // This must be a constant between -255 and -1, for negated ADD
10642           // immediates. This can be used in GCC with an "n" modifier that
10643           // prints the negated value, for use with SUB instructions. It is
10644           // not useful otherwise but is implemented for compatibility.
10645           if (CVal >= -255 && CVal <= -1)
10646             break;
10647         } else {
10648           // This must be a constant between -4095 and 4095. It is not clear
10649           // what this constraint is intended for. Implemented for
10650           // compatibility with GCC.
10651           if (CVal >= -4095 && CVal <= 4095)
10652             break;
10653         }
10654         return;
10655
10656       case 'K':
10657         if (Subtarget->isThumb1Only()) {
10658           // A 32-bit value where only one byte has a nonzero value. Exclude
10659           // zero to match GCC. This constraint is used by GCC internally for
10660           // constants that can be loaded with a move/shift combination.
10661           // It is not useful otherwise but is implemented for compatibility.
10662           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10663             break;
10664         } else if (Subtarget->isThumb2()) {
10665           // A constant whose bitwise inverse can be used as an immediate
10666           // value in a data-processing instruction. This can be used in GCC
10667           // with a "B" modifier that prints the inverted value, for use with
10668           // BIC and MVN instructions. It is not useful otherwise but is
10669           // implemented for compatibility.
10670           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10671             break;
10672         } else {
10673           // A constant whose bitwise inverse can be used as an immediate
10674           // value in a data-processing instruction. This can be used in GCC
10675           // with a "B" modifier that prints the inverted value, for use with
10676           // BIC and MVN instructions. It is not useful otherwise but is
10677           // implemented for compatibility.
10678           if (ARM_AM::getSOImmVal(~CVal) != -1)
10679             break;
10680         }
10681         return;
10682
10683       case 'L':
10684         if (Subtarget->isThumb1Only()) {
10685           // This must be a constant between -7 and 7,
10686           // for 3-operand ADD/SUB immediate instructions.
10687           if (CVal >= -7 && CVal < 7)
10688             break;
10689         } else if (Subtarget->isThumb2()) {
10690           // A constant whose negation can be used as an immediate value in a
10691           // data-processing instruction. This can be used in GCC with an "n"
10692           // modifier that prints the negated value, for use with SUB
10693           // instructions. It is not useful otherwise but is implemented for
10694           // compatibility.
10695           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10696             break;
10697         } else {
10698           // A constant whose negation can be used as an immediate value in a
10699           // data-processing instruction. This can be used in GCC with an "n"
10700           // modifier that prints the negated value, for use with SUB
10701           // instructions. It is not useful otherwise but is implemented for
10702           // compatibility.
10703           if (ARM_AM::getSOImmVal(-CVal) != -1)
10704             break;
10705         }
10706         return;
10707
10708       case 'M':
10709         if (Subtarget->isThumb()) { // FIXME thumb2
10710           // This must be a multiple of 4 between 0 and 1020, for
10711           // ADD sp + immediate.
10712           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10713             break;
10714         } else {
10715           // A power of two or a constant between 0 and 32.  This is used in
10716           // GCC for the shift amount on shifted register operands, but it is
10717           // useful in general for any shift amounts.
10718           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10719             break;
10720         }
10721         return;
10722
10723       case 'N':
10724         if (Subtarget->isThumb()) {  // FIXME thumb2
10725           // This must be a constant between 0 and 31, for shift amounts.
10726           if (CVal >= 0 && CVal <= 31)
10727             break;
10728         }
10729         return;
10730
10731       case 'O':
10732         if (Subtarget->isThumb()) {  // FIXME thumb2
10733           // This must be a multiple of 4 between -508 and 508, for
10734           // ADD/SUB sp = sp + immediate.
10735           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10736             break;
10737         }
10738         return;
10739     }
10740     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10741     break;
10742   }
10743
10744   if (Result.getNode()) {
10745     Ops.push_back(Result);
10746     return;
10747   }
10748   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10749 }
10750
10751 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10752   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10753   unsigned Opcode = Op->getOpcode();
10754   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10755          "Invalid opcode for Div/Rem lowering");
10756   bool isSigned = (Opcode == ISD::SDIVREM);
10757   EVT VT = Op->getValueType(0);
10758   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10759
10760   RTLIB::Libcall LC;
10761   switch (VT.getSimpleVT().SimpleTy) {
10762   default: llvm_unreachable("Unexpected request for libcall!");
10763   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10764   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10765   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10766   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10767   }
10768
10769   SDValue InChain = DAG.getEntryNode();
10770
10771   TargetLowering::ArgListTy Args;
10772   TargetLowering::ArgListEntry Entry;
10773   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10774     EVT ArgVT = Op->getOperand(i).getValueType();
10775     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10776     Entry.Node = Op->getOperand(i);
10777     Entry.Ty = ArgTy;
10778     Entry.isSExt = isSigned;
10779     Entry.isZExt = !isSigned;
10780     Args.push_back(Entry);
10781   }
10782
10783   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10784                                          getPointerTy());
10785
10786   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10787
10788   SDLoc dl(Op);
10789   TargetLowering::CallLoweringInfo CLI(DAG);
10790   CLI.setDebugLoc(dl).setChain(InChain)
10791     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10792     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10793
10794   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10795   return CallInfo.first;
10796 }
10797
10798 SDValue
10799 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10800   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10801   SDLoc DL(Op);
10802
10803   // Get the inputs.
10804   SDValue Chain = Op.getOperand(0);
10805   SDValue Size  = Op.getOperand(1);
10806
10807   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10808                               DAG.getConstant(2, MVT::i32));
10809
10810   SDValue Flag;
10811   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10812   Flag = Chain.getValue(1);
10813
10814   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10815   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10816
10817   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10818   Chain = NewSP.getValue(1);
10819
10820   SDValue Ops[2] = { NewSP, Chain };
10821   return DAG.getMergeValues(Ops, DL);
10822 }
10823
10824 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10825   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10826          "Unexpected type for custom-lowering FP_EXTEND");
10827
10828   RTLIB::Libcall LC;
10829   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10830
10831   SDValue SrcVal = Op.getOperand(0);
10832   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10833                      /*isSigned*/ false, SDLoc(Op)).first;
10834 }
10835
10836 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10837   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10838          Subtarget->isFPOnlySP() &&
10839          "Unexpected type for custom-lowering FP_ROUND");
10840
10841   RTLIB::Libcall LC;
10842   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10843
10844   SDValue SrcVal = Op.getOperand(0);
10845   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10846                      /*isSigned*/ false, SDLoc(Op)).first;
10847 }
10848
10849 bool
10850 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10851   // The ARM target isn't yet aware of offsets.
10852   return false;
10853 }
10854
10855 bool ARM::isBitFieldInvertedMask(unsigned v) {
10856   if (v == 0xffffffff)
10857     return false;
10858
10859   // there can be 1's on either or both "outsides", all the "inside"
10860   // bits must be 0's
10861   return isShiftedMask_32(~v);
10862 }
10863
10864 /// isFPImmLegal - Returns true if the target can instruction select the
10865 /// specified FP immediate natively. If false, the legalizer will
10866 /// materialize the FP immediate as a load from a constant pool.
10867 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10868   if (!Subtarget->hasVFP3())
10869     return false;
10870   if (VT == MVT::f32)
10871     return ARM_AM::getFP32Imm(Imm) != -1;
10872   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10873     return ARM_AM::getFP64Imm(Imm) != -1;
10874   return false;
10875 }
10876
10877 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10878 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10879 /// specified in the intrinsic calls.
10880 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10881                                            const CallInst &I,
10882                                            unsigned Intrinsic) const {
10883   switch (Intrinsic) {
10884   case Intrinsic::arm_neon_vld1:
10885   case Intrinsic::arm_neon_vld2:
10886   case Intrinsic::arm_neon_vld3:
10887   case Intrinsic::arm_neon_vld4:
10888   case Intrinsic::arm_neon_vld2lane:
10889   case Intrinsic::arm_neon_vld3lane:
10890   case Intrinsic::arm_neon_vld4lane: {
10891     Info.opc = ISD::INTRINSIC_W_CHAIN;
10892     // Conservatively set memVT to the entire set of vectors loaded.
10893     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10894     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10895     Info.ptrVal = I.getArgOperand(0);
10896     Info.offset = 0;
10897     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10898     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10899     Info.vol = false; // volatile loads with NEON intrinsics not supported
10900     Info.readMem = true;
10901     Info.writeMem = false;
10902     return true;
10903   }
10904   case Intrinsic::arm_neon_vst1:
10905   case Intrinsic::arm_neon_vst2:
10906   case Intrinsic::arm_neon_vst3:
10907   case Intrinsic::arm_neon_vst4:
10908   case Intrinsic::arm_neon_vst2lane:
10909   case Intrinsic::arm_neon_vst3lane:
10910   case Intrinsic::arm_neon_vst4lane: {
10911     Info.opc = ISD::INTRINSIC_VOID;
10912     // Conservatively set memVT to the entire set of vectors stored.
10913     unsigned NumElts = 0;
10914     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10915       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10916       if (!ArgTy->isVectorTy())
10917         break;
10918       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10919     }
10920     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10921     Info.ptrVal = I.getArgOperand(0);
10922     Info.offset = 0;
10923     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10924     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10925     Info.vol = false; // volatile stores with NEON intrinsics not supported
10926     Info.readMem = false;
10927     Info.writeMem = true;
10928     return true;
10929   }
10930   case Intrinsic::arm_ldaex:
10931   case Intrinsic::arm_ldrex: {
10932     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10933     Info.opc = ISD::INTRINSIC_W_CHAIN;
10934     Info.memVT = MVT::getVT(PtrTy->getElementType());
10935     Info.ptrVal = I.getArgOperand(0);
10936     Info.offset = 0;
10937     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10938     Info.vol = true;
10939     Info.readMem = true;
10940     Info.writeMem = false;
10941     return true;
10942   }
10943   case Intrinsic::arm_stlex:
10944   case Intrinsic::arm_strex: {
10945     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10946     Info.opc = ISD::INTRINSIC_W_CHAIN;
10947     Info.memVT = MVT::getVT(PtrTy->getElementType());
10948     Info.ptrVal = I.getArgOperand(1);
10949     Info.offset = 0;
10950     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10951     Info.vol = true;
10952     Info.readMem = false;
10953     Info.writeMem = true;
10954     return true;
10955   }
10956   case Intrinsic::arm_stlexd:
10957   case Intrinsic::arm_strexd: {
10958     Info.opc = ISD::INTRINSIC_W_CHAIN;
10959     Info.memVT = MVT::i64;
10960     Info.ptrVal = I.getArgOperand(2);
10961     Info.offset = 0;
10962     Info.align = 8;
10963     Info.vol = true;
10964     Info.readMem = false;
10965     Info.writeMem = true;
10966     return true;
10967   }
10968   case Intrinsic::arm_ldaexd:
10969   case Intrinsic::arm_ldrexd: {
10970     Info.opc = ISD::INTRINSIC_W_CHAIN;
10971     Info.memVT = MVT::i64;
10972     Info.ptrVal = I.getArgOperand(0);
10973     Info.offset = 0;
10974     Info.align = 8;
10975     Info.vol = true;
10976     Info.readMem = true;
10977     Info.writeMem = false;
10978     return true;
10979   }
10980   default:
10981     break;
10982   }
10983
10984   return false;
10985 }
10986
10987 /// \brief Returns true if it is beneficial to convert a load of a constant
10988 /// to just the constant itself.
10989 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10990                                                           Type *Ty) const {
10991   assert(Ty->isIntegerTy());
10992
10993   unsigned Bits = Ty->getPrimitiveSizeInBits();
10994   if (Bits == 0 || Bits > 32)
10995     return false;
10996   return true;
10997 }
10998
10999 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11000
11001 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11002                                         ARM_MB::MemBOpt Domain) const {
11003   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11004
11005   // First, if the target has no DMB, see what fallback we can use.
11006   if (!Subtarget->hasDataBarrier()) {
11007     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11008     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11009     // here.
11010     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11011       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11012       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11013                         Builder.getInt32(0), Builder.getInt32(7),
11014                         Builder.getInt32(10), Builder.getInt32(5)};
11015       return Builder.CreateCall(MCR, args);
11016     } else {
11017       // Instead of using barriers, atomic accesses on these subtargets use
11018       // libcalls.
11019       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11020     }
11021   } else {
11022     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11023     // Only a full system barrier exists in the M-class architectures.
11024     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11025     Constant *CDomain = Builder.getInt32(Domain);
11026     return Builder.CreateCall(DMB, CDomain);
11027   }
11028 }
11029
11030 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11031 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11032                                          AtomicOrdering Ord, bool IsStore,
11033                                          bool IsLoad) const {
11034   if (!getInsertFencesForAtomic())
11035     return nullptr;
11036
11037   switch (Ord) {
11038   case NotAtomic:
11039   case Unordered:
11040     llvm_unreachable("Invalid fence: unordered/non-atomic");
11041   case Monotonic:
11042   case Acquire:
11043     return nullptr; // Nothing to do
11044   case SequentiallyConsistent:
11045     if (!IsStore)
11046       return nullptr; // Nothing to do
11047     /*FALLTHROUGH*/
11048   case Release:
11049   case AcquireRelease:
11050     if (Subtarget->isSwift())
11051       return makeDMB(Builder, ARM_MB::ISHST);
11052     // FIXME: add a comment with a link to documentation justifying this.
11053     else
11054       return makeDMB(Builder, ARM_MB::ISH);
11055   }
11056   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11057 }
11058
11059 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11060                                           AtomicOrdering Ord, bool IsStore,
11061                                           bool IsLoad) const {
11062   if (!getInsertFencesForAtomic())
11063     return nullptr;
11064
11065   switch (Ord) {
11066   case NotAtomic:
11067   case Unordered:
11068     llvm_unreachable("Invalid fence: unordered/not-atomic");
11069   case Monotonic:
11070   case Release:
11071     return nullptr; // Nothing to do
11072   case Acquire:
11073   case AcquireRelease:
11074   case SequentiallyConsistent:
11075     return makeDMB(Builder, ARM_MB::ISH);
11076   }
11077   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11078 }
11079
11080 // Loads and stores less than 64-bits are already atomic; ones above that
11081 // are doomed anyway, so defer to the default libcall and blame the OS when
11082 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11083 // anything for those.
11084 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11085   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11086   return (Size == 64) && !Subtarget->isMClass();
11087 }
11088
11089 // Loads and stores less than 64-bits are already atomic; ones above that
11090 // are doomed anyway, so defer to the default libcall and blame the OS when
11091 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11092 // anything for those.
11093 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11094 // guarantee, see DDI0406C ARM architecture reference manual,
11095 // sections A8.8.72-74 LDRD)
11096 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11097   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11098   return (Size == 64) && !Subtarget->isMClass();
11099 }
11100
11101 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11102 // and up to 64 bits on the non-M profiles
11103 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11104   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11105   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11106 }
11107
11108 // This has so far only been implemented for MachO.
11109 bool ARMTargetLowering::useLoadStackGuardNode() const {
11110   return Subtarget->isTargetMachO();
11111 }
11112
11113 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11114                                                   unsigned &Cost) const {
11115   // If we do not have NEON, vector types are not natively supported.
11116   if (!Subtarget->hasNEON())
11117     return false;
11118
11119   // Floating point values and vector values map to the same register file.
11120   // Therefore, althought we could do a store extract of a vector type, this is
11121   // better to leave at float as we have more freedom in the addressing mode for
11122   // those.
11123   if (VectorTy->isFPOrFPVectorTy())
11124     return false;
11125
11126   // If the index is unknown at compile time, this is very expensive to lower
11127   // and it is not possible to combine the store with the extract.
11128   if (!isa<ConstantInt>(Idx))
11129     return false;
11130
11131   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11132   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11133   // We can do a store + vector extract on any vector that fits perfectly in a D
11134   // or Q register.
11135   if (BitWidth == 64 || BitWidth == 128) {
11136     Cost = 0;
11137     return true;
11138   }
11139   return false;
11140 }
11141
11142 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11143                                          AtomicOrdering Ord) const {
11144   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11145   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11146   bool IsAcquire = isAtLeastAcquire(Ord);
11147
11148   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11149   // intrinsic must return {i32, i32} and we have to recombine them into a
11150   // single i64 here.
11151   if (ValTy->getPrimitiveSizeInBits() == 64) {
11152     Intrinsic::ID Int =
11153         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11154     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11155
11156     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11157     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11158
11159     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11160     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11161     if (!Subtarget->isLittle())
11162       std::swap (Lo, Hi);
11163     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11164     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11165     return Builder.CreateOr(
11166         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11167   }
11168
11169   Type *Tys[] = { Addr->getType() };
11170   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11171   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11172
11173   return Builder.CreateTruncOrBitCast(
11174       Builder.CreateCall(Ldrex, Addr),
11175       cast<PointerType>(Addr->getType())->getElementType());
11176 }
11177
11178 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11179                                                Value *Addr,
11180                                                AtomicOrdering Ord) const {
11181   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11182   bool IsRelease = isAtLeastRelease(Ord);
11183
11184   // Since the intrinsics must have legal type, the i64 intrinsics take two
11185   // parameters: "i32, i32". We must marshal Val into the appropriate form
11186   // before the call.
11187   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11188     Intrinsic::ID Int =
11189         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11190     Function *Strex = Intrinsic::getDeclaration(M, Int);
11191     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11192
11193     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11194     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11195     if (!Subtarget->isLittle())
11196       std::swap (Lo, Hi);
11197     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11198     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11199   }
11200
11201   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11202   Type *Tys[] = { Addr->getType() };
11203   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11204
11205   return Builder.CreateCall2(
11206       Strex, Builder.CreateZExtOrBitCast(
11207                  Val, Strex->getFunctionType()->getParamType(0)),
11208       Addr);
11209 }
11210
11211 enum HABaseType {
11212   HA_UNKNOWN = 0,
11213   HA_FLOAT,
11214   HA_DOUBLE,
11215   HA_VECT64,
11216   HA_VECT128
11217 };
11218
11219 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11220                                    uint64_t &Members) {
11221   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11222     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11223       uint64_t SubMembers = 0;
11224       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11225         return false;
11226       Members += SubMembers;
11227     }
11228   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11229     uint64_t SubMembers = 0;
11230     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11231       return false;
11232     Members += SubMembers * AT->getNumElements();
11233   } else if (Ty->isFloatTy()) {
11234     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11235       return false;
11236     Members = 1;
11237     Base = HA_FLOAT;
11238   } else if (Ty->isDoubleTy()) {
11239     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11240       return false;
11241     Members = 1;
11242     Base = HA_DOUBLE;
11243   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11244     Members = 1;
11245     switch (Base) {
11246     case HA_FLOAT:
11247     case HA_DOUBLE:
11248       return false;
11249     case HA_VECT64:
11250       return VT->getBitWidth() == 64;
11251     case HA_VECT128:
11252       return VT->getBitWidth() == 128;
11253     case HA_UNKNOWN:
11254       switch (VT->getBitWidth()) {
11255       case 64:
11256         Base = HA_VECT64;
11257         return true;
11258       case 128:
11259         Base = HA_VECT128;
11260         return true;
11261       default:
11262         return false;
11263       }
11264     }
11265   }
11266
11267   return (Members > 0 && Members <= 4);
11268 }
11269
11270 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11271 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11272     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11273   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11274       CallingConv::ARM_AAPCS_VFP)
11275     return false;
11276
11277   HABaseType Base = HA_UNKNOWN;
11278   uint64_t Members = 0;
11279   bool result = isHomogeneousAggregate(Ty, Base, Members);
11280   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11281   return result;
11282 }