CodeGen: convert CCState interface to using ArrayRefs
[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     setTargetDAGCombine(ISD::LOAD);
569
570     // It is legal to extload from v4i8 to v4i16 or v4i32.
571     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
572                   MVT::v4i16, MVT::v2i16,
573                   MVT::v2i32};
574     for (unsigned i = 0; i < 6; ++i) {
575       for (MVT VT : MVT::integer_vector_valuetypes()) {
576         setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
577         setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
578         setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
579       }
580     }
581   }
582
583   // ARM and Thumb2 support UMLAL/SMLAL.
584   if (!Subtarget->isThumb1Only())
585     setTargetDAGCombine(ISD::ADDC);
586
587   if (Subtarget->isFPOnlySP()) {
588     // When targetting a floating-point unit with only single-precision
589     // operations, f64 is legal for the few double-precision instructions which
590     // are present However, no double-precision operations other than moves,
591     // loads and stores are provided by the hardware.
592     setOperationAction(ISD::FADD,       MVT::f64, Expand);
593     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
594     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
595     setOperationAction(ISD::FMA,        MVT::f64, Expand);
596     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
597     setOperationAction(ISD::FREM,       MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
599     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
600     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
601     setOperationAction(ISD::FABS,       MVT::f64, Expand);
602     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
603     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
604     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
605     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
606     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
607     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
608     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
609     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
610     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
611     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
612     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
613     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
614     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
615     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
616     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
617     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
618     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
619   }
620
621   computeRegisterProperties();
622
623   // ARM does not have floating-point extending loads.
624   for (MVT VT : MVT::fp_valuetypes()) {
625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
626     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
627   }
628
629   // ... or truncating stores
630   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
631   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
632   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
633
634   // ARM does not have i1 sign extending load.
635   for (MVT VT : MVT::integer_valuetypes())
636     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
637
638   // ARM supports all 4 flavors of integer indexed load / store.
639   if (!Subtarget->isThumb1Only()) {
640     for (unsigned im = (unsigned)ISD::PRE_INC;
641          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
642       setIndexedLoadAction(im,  MVT::i1,  Legal);
643       setIndexedLoadAction(im,  MVT::i8,  Legal);
644       setIndexedLoadAction(im,  MVT::i16, Legal);
645       setIndexedLoadAction(im,  MVT::i32, Legal);
646       setIndexedStoreAction(im, MVT::i1,  Legal);
647       setIndexedStoreAction(im, MVT::i8,  Legal);
648       setIndexedStoreAction(im, MVT::i16, Legal);
649       setIndexedStoreAction(im, MVT::i32, Legal);
650     }
651   }
652
653   setOperationAction(ISD::SADDO, MVT::i32, Custom);
654   setOperationAction(ISD::UADDO, MVT::i32, Custom);
655   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
656   setOperationAction(ISD::USUBO, MVT::i32, Custom);
657
658   // i64 operation support.
659   setOperationAction(ISD::MUL,     MVT::i64, Expand);
660   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
661   if (Subtarget->isThumb1Only()) {
662     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
663     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
664   }
665   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
666       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
667     setOperationAction(ISD::MULHS, MVT::i32, Expand);
668
669   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
670   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
671   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
672   setOperationAction(ISD::SRL,       MVT::i64, Custom);
673   setOperationAction(ISD::SRA,       MVT::i64, Custom);
674
675   if (!Subtarget->isThumb1Only()) {
676     // FIXME: We should do this for Thumb1 as well.
677     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
678     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
679     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
680     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
681   }
682
683   // ARM does not have ROTL.
684   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
685   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
686   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
687   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
688     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
689
690   // These just redirect to CTTZ and CTLZ on ARM.
691   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
692   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
693
694   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
695
696   // Only ARMv6 has BSWAP.
697   if (!Subtarget->hasV6Ops())
698     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
699
700   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
701       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
702     // These are expanded into libcalls if the cpu doesn't have HW divider.
703     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
704     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
705   }
706
707   // FIXME: Also set divmod for SREM on EABI
708   setOperationAction(ISD::SREM,  MVT::i32, Expand);
709   setOperationAction(ISD::UREM,  MVT::i32, Expand);
710   // Register based DivRem for AEABI (RTABI 4.2)
711   if (Subtarget->isTargetAEABI()) {
712     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
713     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
714     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
715     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
716     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
717     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
718     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
719     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
720
721     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
722     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
723     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
724     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
725     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
729
730     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
731     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
732   } else {
733     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
734     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
735   }
736
737   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
738   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
739   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
740   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
741   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
742
743   setOperationAction(ISD::TRAP, MVT::Other, Legal);
744
745   // Use the default implementation.
746   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
747   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
748   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
749   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
750   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
751   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
752
753   if (!Subtarget->isTargetMachO()) {
754     // Non-MachO platforms may return values in these registers via the
755     // personality function.
756     setExceptionPointerRegister(ARM::R0);
757     setExceptionSelectorRegister(ARM::R1);
758   }
759
760   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
761     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
762   else
763     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
764
765   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
766   // the default expansion. If we are targeting a single threaded system,
767   // then set them all for expand so we can lower them later into their
768   // non-atomic form.
769   if (TM.Options.ThreadModel == ThreadModel::Single)
770     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
771   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
772     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
773     // to ldrex/strex loops already.
774     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
775
776     // On v8, we have particularly efficient implementations of atomic fences
777     // if they can be combined with nearby atomic loads and stores.
778     if (!Subtarget->hasV8Ops()) {
779       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
780       setInsertFencesForAtomic(true);
781     }
782   } else {
783     // If there's anything we can use as a barrier, go through custom lowering
784     // for ATOMIC_FENCE.
785     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
786                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
787
788     // Set them all for expansion, which will force libcalls.
789     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
790     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
791     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
792     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
793     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
801     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
802     // Unordered/Monotonic case.
803     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
804     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
805   }
806
807   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
808
809   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
810   if (!Subtarget->hasV6Ops()) {
811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
812     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
813   }
814   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
815
816   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
817       !Subtarget->isThumb1Only()) {
818     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
819     // iff target supports vfp2.
820     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
821     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
822   }
823
824   // We want to custom lower some of our intrinsics.
825   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
826   if (Subtarget->isTargetDarwin()) {
827     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
828     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
829     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
830   }
831
832   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
833   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
834   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
835   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
836   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
837   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
838   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
839   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
840   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
841
842   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
843   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
844   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
845   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
846   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
847
848   // We don't support sin/cos/fmod/copysign/pow
849   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
850   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
851   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
852   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
853   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
854   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
855   setOperationAction(ISD::FREM,      MVT::f64, Expand);
856   setOperationAction(ISD::FREM,      MVT::f32, Expand);
857   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
858       !Subtarget->isThumb1Only()) {
859     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
860     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
861   }
862   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
863   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
864
865   if (!Subtarget->hasVFP4()) {
866     setOperationAction(ISD::FMA, MVT::f64, Expand);
867     setOperationAction(ISD::FMA, MVT::f32, Expand);
868   }
869
870   // Various VFP goodness
871   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
872     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
873     if (Subtarget->hasVFP2()) {
874       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
875       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
876       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
877       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
878     }
879
880     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
881     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
882       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
883       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
884     }
885
886     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
887     if (!Subtarget->hasFP16()) {
888       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
889       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
890     }
891   }
892
893   // Combine sin / cos into one node or libcall if possible.
894   if (Subtarget->hasSinCos()) {
895     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
896     setLibcallName(RTLIB::SINCOS_F64, "sincos");
897     if (Subtarget->getTargetTriple().isiOS()) {
898       // For iOS, we don't want to the normal expansion of a libcall to
899       // sincos. We want to issue a libcall to __sincos_stret.
900       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
901       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
902     }
903   }
904
905   // FP-ARMv8 implements a lot of rounding-like FP operations.
906   if (Subtarget->hasFPARMv8()) {
907     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
908     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
909     setOperationAction(ISD::FROUND, MVT::f32, Legal);
910     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
911     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
912     setOperationAction(ISD::FRINT, MVT::f32, Legal);
913     if (!Subtarget->isFPOnlySP()) {
914       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
915       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
916       setOperationAction(ISD::FROUND, MVT::f64, Legal);
917       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
918       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
919       setOperationAction(ISD::FRINT, MVT::f64, Legal);
920     }
921   }
922   // We have target-specific dag combine patterns for the following nodes:
923   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
924   setTargetDAGCombine(ISD::ADD);
925   setTargetDAGCombine(ISD::SUB);
926   setTargetDAGCombine(ISD::MUL);
927   setTargetDAGCombine(ISD::AND);
928   setTargetDAGCombine(ISD::OR);
929   setTargetDAGCombine(ISD::XOR);
930
931   if (Subtarget->hasV6Ops())
932     setTargetDAGCombine(ISD::SRL);
933
934   setStackPointerRegisterToSaveRestore(ARM::SP);
935
936   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
937       !Subtarget->hasVFP2())
938     setSchedulingPreference(Sched::RegPressure);
939   else
940     setSchedulingPreference(Sched::Hybrid);
941
942   //// temporary - rewrite interface to use type
943   MaxStoresPerMemset = 8;
944   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
945   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
946   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
947   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
948   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949
950   // On ARM arguments smaller than 4 bytes are extended, so all arguments
951   // are at least 4 bytes aligned.
952   setMinStackArgumentAlignment(4);
953
954   // Prefer likely predicted branches to selects on out-of-order cores.
955   PredictableSelectIsExpensive = Subtarget->isLikeA9();
956
957   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
958 }
959
960 // FIXME: It might make sense to define the representative register class as the
961 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
962 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
963 // SPR's representative would be DPR_VFP2. This should work well if register
964 // pressure tracking were modified such that a register use would increment the
965 // pressure of the register class's representative and all of it's super
966 // classes' representatives transitively. We have not implemented this because
967 // of the difficulty prior to coalescing of modeling operand register classes
968 // due to the common occurrence of cross class copies and subregister insertions
969 // and extractions.
970 std::pair<const TargetRegisterClass*, uint8_t>
971 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
972   const TargetRegisterClass *RRC = nullptr;
973   uint8_t Cost = 1;
974   switch (VT.SimpleTy) {
975   default:
976     return TargetLowering::findRepresentativeClass(VT);
977   // Use DPR as representative register class for all floating point
978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979   // the cost is 1 for both f32 and f64.
980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982     RRC = &ARM::DPRRegClass;
983     // When NEON is used for SP, only half of the register file is available
984     // because operations that define both SP and DP results will be constrained
985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
986     // coalescing by double-counting the SP regs. See the FIXME above.
987     if (Subtarget->useNEONForSinglePrecisionFP())
988       Cost = 2;
989     break;
990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991   case MVT::v4f32: case MVT::v2f64:
992     RRC = &ARM::DPRRegClass;
993     Cost = 2;
994     break;
995   case MVT::v4i64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 4;
998     break;
999   case MVT::v8i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 8;
1002     break;
1003   }
1004   return std::make_pair(RRC, Cost);
1005 }
1006
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008   switch (Opcode) {
1009   default: return nullptr;
1010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1013   case ARMISD::CALL:          return "ARMISD::CALL";
1014   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1015   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1016   case ARMISD::tCALL:         return "ARMISD::tCALL";
1017   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1018   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1019   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1020   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1021   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1022   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1023   case ARMISD::CMP:           return "ARMISD::CMP";
1024   case ARMISD::CMN:           return "ARMISD::CMN";
1025   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1026   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1027   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1028   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1029   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1030
1031   case ARMISD::CMOV:          return "ARMISD::CMOV";
1032
1033   case ARMISD::RBIT:          return "ARMISD::RBIT";
1034
1035   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1036   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1037   case ARMISD::SITOF:         return "ARMISD::SITOF";
1038   case ARMISD::UITOF:         return "ARMISD::UITOF";
1039
1040   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1041   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1042   case ARMISD::RRX:           return "ARMISD::RRX";
1043
1044   case ARMISD::ADDC:          return "ARMISD::ADDC";
1045   case ARMISD::ADDE:          return "ARMISD::ADDE";
1046   case ARMISD::SUBC:          return "ARMISD::SUBC";
1047   case ARMISD::SUBE:          return "ARMISD::SUBE";
1048
1049   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1050   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1051
1052   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1053   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1054
1055   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1056
1057   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1058
1059   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1060
1061   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1062
1063   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1064
1065   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1066
1067   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1068   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1069   case ARMISD::VCGE:          return "ARMISD::VCGE";
1070   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1071   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1072   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1073   case ARMISD::VCGT:          return "ARMISD::VCGT";
1074   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1075   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1076   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1077   case ARMISD::VTST:          return "ARMISD::VTST";
1078
1079   case ARMISD::VSHL:          return "ARMISD::VSHL";
1080   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1081   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1082   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1083   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1084   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1085   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1086   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1087   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1088   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1089   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1090   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1091   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1092   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1093   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1094   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1095   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1096   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1097   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1098   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1099   case ARMISD::VDUP:          return "ARMISD::VDUP";
1100   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1101   case ARMISD::VEXT:          return "ARMISD::VEXT";
1102   case ARMISD::VREV64:        return "ARMISD::VREV64";
1103   case ARMISD::VREV32:        return "ARMISD::VREV32";
1104   case ARMISD::VREV16:        return "ARMISD::VREV16";
1105   case ARMISD::VZIP:          return "ARMISD::VZIP";
1106   case ARMISD::VUZP:          return "ARMISD::VUZP";
1107   case ARMISD::VTRN:          return "ARMISD::VTRN";
1108   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1109   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1110   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1111   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1112   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1113   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1114   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1115   case ARMISD::FMAX:          return "ARMISD::FMAX";
1116   case ARMISD::FMIN:          return "ARMISD::FMIN";
1117   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1118   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1119   case ARMISD::BFI:           return "ARMISD::BFI";
1120   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1121   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1122   case ARMISD::VBSL:          return "ARMISD::VBSL";
1123   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1124   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1125   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1126   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1127   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1128   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1129   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1130   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1131   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1132   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1133   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1134   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1135   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1136   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1137   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1138   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1139   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1140   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1141   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1142   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1143   }
1144 }
1145
1146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1147   if (!VT.isVector()) return getPointerTy();
1148   return VT.changeVectorElementTypeToInteger();
1149 }
1150
1151 /// getRegClassFor - Return the register class that should be used for the
1152 /// specified value type.
1153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1154   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1155   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1156   // load / store 4 to 8 consecutive D registers.
1157   if (Subtarget->hasNEON()) {
1158     if (VT == MVT::v4i64)
1159       return &ARM::QQPRRegClass;
1160     if (VT == MVT::v8i64)
1161       return &ARM::QQQQPRRegClass;
1162   }
1163   return TargetLowering::getRegClassFor(VT);
1164 }
1165
1166 // Create a fast isel object.
1167 FastISel *
1168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1169                                   const TargetLibraryInfo *libInfo) const {
1170   return ARM::createFastISel(funcInfo, libInfo);
1171 }
1172
1173 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1174 /// be used for loads / stores from the global.
1175 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1176   return (Subtarget->isThumb1Only() ? 127 : 4095);
1177 }
1178
1179 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1180   unsigned NumVals = N->getNumValues();
1181   if (!NumVals)
1182     return Sched::RegPressure;
1183
1184   for (unsigned i = 0; i != NumVals; ++i) {
1185     EVT VT = N->getValueType(i);
1186     if (VT == MVT::Glue || VT == MVT::Other)
1187       continue;
1188     if (VT.isFloatingPoint() || VT.isVector())
1189       return Sched::ILP;
1190   }
1191
1192   if (!N->isMachineOpcode())
1193     return Sched::RegPressure;
1194
1195   // Load are scheduled for latency even if there instruction itinerary
1196   // is not available.
1197   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1198   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199
1200   if (MCID.getNumDefs() == 0)
1201     return Sched::RegPressure;
1202   if (!Itins->isEmpty() &&
1203       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1204     return Sched::ILP;
1205
1206   return Sched::RegPressure;
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // Lowering Code
1211 //===----------------------------------------------------------------------===//
1212
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1215   switch (CC) {
1216   default: llvm_unreachable("Unknown condition code!");
1217   case ISD::SETNE:  return ARMCC::NE;
1218   case ISD::SETEQ:  return ARMCC::EQ;
1219   case ISD::SETGT:  return ARMCC::GT;
1220   case ISD::SETGE:  return ARMCC::GE;
1221   case ISD::SETLT:  return ARMCC::LT;
1222   case ISD::SETLE:  return ARMCC::LE;
1223   case ISD::SETUGT: return ARMCC::HI;
1224   case ISD::SETUGE: return ARMCC::HS;
1225   case ISD::SETULT: return ARMCC::LO;
1226   case ISD::SETULE: return ARMCC::LS;
1227   }
1228 }
1229
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232                         ARMCC::CondCodes &CondCode2) {
1233   CondCode2 = ARMCC::AL;
1234   switch (CC) {
1235   default: llvm_unreachable("Unknown FP condition!");
1236   case ISD::SETEQ:
1237   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1238   case ISD::SETGT:
1239   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1240   case ISD::SETGE:
1241   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245   case ISD::SETO:   CondCode = ARMCC::VC; break;
1246   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1247   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1250   case ISD::SETLT:
1251   case ISD::SETULT: CondCode = ARMCC::LT; break;
1252   case ISD::SETLE:
1253   case ISD::SETULE: CondCode = ARMCC::LE; break;
1254   case ISD::SETNE:
1255   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1256   }
1257 }
1258
1259 //===----------------------------------------------------------------------===//
1260 //                      Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1262
1263 #include "ARMGenCallingConv.inc"
1264
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1268 CallingConv::ID
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270                                            bool isVarArg) const {
1271   switch (CC) {
1272   default:
1273     llvm_unreachable("Unsupported calling convention");
1274   case CallingConv::ARM_AAPCS:
1275   case CallingConv::ARM_APCS:
1276   case CallingConv::GHC:
1277     return CC;
1278   case CallingConv::ARM_AAPCS_VFP:
1279     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280   case CallingConv::C:
1281     if (!Subtarget->isAAPCS_ABI())
1282       return CallingConv::ARM_APCS;
1283     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1285              !isVarArg)
1286       return CallingConv::ARM_AAPCS_VFP;
1287     else
1288       return CallingConv::ARM_AAPCS;
1289   case CallingConv::Fast:
1290     if (!Subtarget->isAAPCS_ABI()) {
1291       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292         return CallingConv::Fast;
1293       return CallingConv::ARM_APCS;
1294     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295       return CallingConv::ARM_AAPCS_VFP;
1296     else
1297       return CallingConv::ARM_AAPCS;
1298   }
1299 }
1300
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1304                                                  bool Return,
1305                                                  bool isVarArg) const {
1306   switch (getEffectiveCallingConv(CC, isVarArg)) {
1307   default:
1308     llvm_unreachable("Unsupported calling convention");
1309   case CallingConv::ARM_APCS:
1310     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311   case CallingConv::ARM_AAPCS:
1312     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313   case CallingConv::ARM_AAPCS_VFP:
1314     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315   case CallingConv::Fast:
1316     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317   case CallingConv::GHC:
1318     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1319   }
1320 }
1321
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1324 SDValue
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326                                    CallingConv::ID CallConv, bool isVarArg,
1327                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1328                                    SDLoc dl, SelectionDAG &DAG,
1329                                    SmallVectorImpl<SDValue> &InVals,
1330                                    bool isThisReturn, SDValue ThisVal) const {
1331
1332   // Assign locations to each value returned by this call.
1333   SmallVector<CCValAssign, 16> RVLocs;
1334   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335                     *DAG.getContext(), Call);
1336   CCInfo.AnalyzeCallResult(Ins,
1337                            CCAssignFnForNode(CallConv, /* Return*/ true,
1338                                              isVarArg));
1339
1340   // Copy all of the result registers out of their specified physreg.
1341   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342     CCValAssign VA = RVLocs[i];
1343
1344     // Pass 'this' value directly from the argument to return value, to avoid
1345     // reg unit interference
1346     if (i == 0 && isThisReturn) {
1347       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348              "unexpected return calling convention register assignment");
1349       InVals.push_back(ThisVal);
1350       continue;
1351     }
1352
1353     SDValue Val;
1354     if (VA.needsCustom()) {
1355       // Handle f64 or half of a v2f64.
1356       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357                                       InFlag);
1358       Chain = Lo.getValue(1);
1359       InFlag = Lo.getValue(2);
1360       VA = RVLocs[++i]; // skip ahead to next loc
1361       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1362                                       InFlag);
1363       Chain = Hi.getValue(1);
1364       InFlag = Hi.getValue(2);
1365       if (!Subtarget->isLittle())
1366         std::swap (Lo, Hi);
1367       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1368
1369       if (VA.getLocVT() == MVT::v2f64) {
1370         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372                           DAG.getConstant(0, MVT::i32));
1373
1374         VA = RVLocs[++i]; // skip ahead to next loc
1375         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376         Chain = Lo.getValue(1);
1377         InFlag = Lo.getValue(2);
1378         VA = RVLocs[++i]; // skip ahead to next loc
1379         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380         Chain = Hi.getValue(1);
1381         InFlag = Hi.getValue(2);
1382         if (!Subtarget->isLittle())
1383           std::swap (Lo, Hi);
1384         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386                           DAG.getConstant(1, MVT::i32));
1387       }
1388     } else {
1389       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1390                                InFlag);
1391       Chain = Val.getValue(1);
1392       InFlag = Val.getValue(2);
1393     }
1394
1395     switch (VA.getLocInfo()) {
1396     default: llvm_unreachable("Unknown loc info!");
1397     case CCValAssign::Full: break;
1398     case CCValAssign::BCvt:
1399       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1400       break;
1401     }
1402
1403     InVals.push_back(Val);
1404   }
1405
1406   return Chain;
1407 }
1408
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1410 SDValue
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412                                     SDValue StackPtr, SDValue Arg,
1413                                     SDLoc dl, SelectionDAG &DAG,
1414                                     const CCValAssign &VA,
1415                                     ISD::ArgFlagsTy Flags) const {
1416   unsigned LocMemOffset = VA.getLocMemOffset();
1417   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419   return DAG.getStore(Chain, dl, Arg, PtrOff,
1420                       MachinePointerInfo::getStack(LocMemOffset),
1421                       false, false, 0);
1422 }
1423
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425                                          SDValue Chain, SDValue &Arg,
1426                                          RegsToPassVector &RegsToPass,
1427                                          CCValAssign &VA, CCValAssign &NextVA,
1428                                          SDValue &StackPtr,
1429                                          SmallVectorImpl<SDValue> &MemOpChains,
1430                                          ISD::ArgFlagsTy Flags) const {
1431
1432   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434   unsigned id = Subtarget->isLittle() ? 0 : 1;
1435   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1436
1437   if (NextVA.isRegLoc())
1438     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1439   else {
1440     assert(NextVA.isMemLoc());
1441     if (!StackPtr.getNode())
1442       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1443
1444     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1445                                            dl, DAG, NextVA,
1446                                            Flags));
1447   }
1448 }
1449
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1452 /// nodes.
1453 SDValue
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455                              SmallVectorImpl<SDValue> &InVals) const {
1456   SelectionDAG &DAG                     = CLI.DAG;
1457   SDLoc &dl                          = CLI.DL;
1458   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1460   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1461   SDValue Chain                         = CLI.Chain;
1462   SDValue Callee                        = CLI.Callee;
1463   bool &isTailCall                      = CLI.IsTailCall;
1464   CallingConv::ID CallConv              = CLI.CallConv;
1465   bool doesNotRet                       = CLI.DoesNotReturn;
1466   bool isVarArg                         = CLI.IsVarArg;
1467
1468   MachineFunction &MF = DAG.getMachineFunction();
1469   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470   bool isThisReturn   = false;
1471   bool isSibCall      = false;
1472
1473   // Disable tail calls if they're not supported.
1474   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1475     isTailCall = false;
1476
1477   if (isTailCall) {
1478     // Check if it's really possible to do a tail call.
1479     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481                                                    Outs, OutVals, Ins, DAG);
1482     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483       report_fatal_error("failed to perform tail call elimination on a call "
1484                          "site marked musttail");
1485     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486     // detected sibcalls.
1487     if (isTailCall) {
1488       ++NumTailCalls;
1489       isSibCall = true;
1490     }
1491   }
1492
1493   // Analyze operands of the call, assigning locations to each operand.
1494   SmallVector<CCValAssign, 16> ArgLocs;
1495   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496                     *DAG.getContext(), Call);
1497   CCInfo.AnalyzeCallOperands(Outs,
1498                              CCAssignFnForNode(CallConv, /* Return*/ false,
1499                                                isVarArg));
1500
1501   // Get a count of how many bytes are to be pushed on the stack.
1502   unsigned NumBytes = CCInfo.getNextStackOffset();
1503
1504   // For tail calls, memory operands are available in our caller's stack.
1505   if (isSibCall)
1506     NumBytes = 0;
1507
1508   // Adjust the stack pointer for the new arguments...
1509   // These operations are automatically eliminated by the prolog/epilog pass
1510   if (!isSibCall)
1511     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1512                                  dl);
1513
1514   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1515
1516   RegsToPassVector RegsToPass;
1517   SmallVector<SDValue, 8> MemOpChains;
1518
1519   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1520   // of tail call optimization, arguments are handled later.
1521   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1522        i != e;
1523        ++i, ++realArgIdx) {
1524     CCValAssign &VA = ArgLocs[i];
1525     SDValue Arg = OutVals[realArgIdx];
1526     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527     bool isByVal = Flags.isByVal();
1528
1529     // Promote the value if needed.
1530     switch (VA.getLocInfo()) {
1531     default: llvm_unreachable("Unknown loc info!");
1532     case CCValAssign::Full: break;
1533     case CCValAssign::SExt:
1534       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1535       break;
1536     case CCValAssign::ZExt:
1537       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::AExt:
1540       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::BCvt:
1543       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1544       break;
1545     }
1546
1547     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548     if (VA.needsCustom()) {
1549       if (VA.getLocVT() == MVT::v2f64) {
1550         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551                                   DAG.getConstant(0, MVT::i32));
1552         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553                                   DAG.getConstant(1, MVT::i32));
1554
1555         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557
1558         VA = ArgLocs[++i]; // skip ahead to next loc
1559         if (VA.isRegLoc()) {
1560           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1562         } else {
1563           assert(VA.isMemLoc());
1564
1565           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566                                                  dl, DAG, VA, Flags));
1567         }
1568       } else {
1569         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570                          StackPtr, MemOpChains, Flags);
1571       }
1572     } else if (VA.isRegLoc()) {
1573       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574         assert(VA.getLocVT() == MVT::i32 &&
1575                "unexpected calling convention register assignment");
1576         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577                "unexpected use of 'returned'");
1578         isThisReturn = true;
1579       }
1580       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581     } else if (isByVal) {
1582       assert(VA.isMemLoc());
1583       unsigned offset = 0;
1584
1585       // True if this byval aggregate will be split between registers
1586       // and memory.
1587       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1589
1590       if (CurByValIdx < ByValArgsCount) {
1591
1592         unsigned RegBegin, RegEnd;
1593         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1594
1595         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1596         unsigned int i, j;
1597         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601                                      MachinePointerInfo(),
1602                                      false, false, false,
1603                                      DAG.InferPtrAlignment(AddArg));
1604           MemOpChains.push_back(Load.getValue(1));
1605           RegsToPass.push_back(std::make_pair(j, Load));
1606         }
1607
1608         // If parameter size outsides register area, "offset" value
1609         // helps us to calculate stack slot for remained part properly.
1610         offset = RegEnd - RegBegin;
1611
1612         CCInfo.nextInRegsParam();
1613       }
1614
1615       if (Flags.getByValSize() > 4*offset) {
1616         unsigned LocMemOffset = VA.getLocMemOffset();
1617         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1619                                   StkPtrOff);
1620         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1623                                            MVT::i32);
1624         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1625
1626         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1629                                           Ops));
1630       }
1631     } else if (!isSibCall) {
1632       assert(VA.isMemLoc());
1633
1634       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635                                              dl, DAG, VA, Flags));
1636     }
1637   }
1638
1639   if (!MemOpChains.empty())
1640     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1641
1642   // Build a sequence of copy-to-reg nodes chained together with token chain
1643   // and flag operands which copy the outgoing args into the appropriate regs.
1644   SDValue InFlag;
1645   // Tail call byval lowering might overwrite argument registers so in case of
1646   // tail call optimization the copies to registers are lowered later.
1647   if (!isTailCall)
1648     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650                                RegsToPass[i].second, InFlag);
1651       InFlag = Chain.getValue(1);
1652     }
1653
1654   // For tail calls lower the arguments to the 'real' stack slot.
1655   if (isTailCall) {
1656     // Force all the incoming stack arguments to be loaded from the stack
1657     // before any new outgoing arguments are stored to the stack, because the
1658     // outgoing stack slots may alias the incoming argument stack slots, and
1659     // the alias isn't otherwise explicit. This is slightly more conservative
1660     // than necessary, because it means that each store effectively depends
1661     // on every argument instead of just those arguments it would clobber.
1662
1663     // Do not flag preceding copytoreg stuff together with the following stuff.
1664     InFlag = SDValue();
1665     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667                                RegsToPass[i].second, InFlag);
1668       InFlag = Chain.getValue(1);
1669     }
1670     InFlag = SDValue();
1671   }
1672
1673   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675   // node so that legalize doesn't hack it.
1676   bool isDirect = false;
1677   bool isARMFunc = false;
1678   bool isLocalARMFunc = false;
1679   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1680
1681   if (EnableARMLongCalls) {
1682     assert((Subtarget->isTargetWindows() ||
1683             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684            "long-calls with non-static relocation model!");
1685     // Handle a global address or an external symbol. If it's not one of
1686     // those, the target's already in a register, so we don't need to do
1687     // anything extra.
1688     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689       const GlobalValue *GV = G->getGlobal();
1690       // Create a constant pool entry for the callee address
1691       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692       ARMConstantPoolValue *CPV =
1693         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1694
1695       // Get the address of the callee into a register
1696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698       Callee = DAG.getLoad(getPointerTy(), dl,
1699                            DAG.getEntryNode(), CPAddr,
1700                            MachinePointerInfo::getConstantPool(),
1701                            false, false, false, 0);
1702     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703       const char *Sym = S->getSymbol();
1704
1705       // Create a constant pool entry for the callee address
1706       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707       ARMConstantPoolValue *CPV =
1708         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709                                       ARMPCLabelIndex, 0);
1710       // Get the address of the callee into a register
1711       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713       Callee = DAG.getLoad(getPointerTy(), dl,
1714                            DAG.getEntryNode(), CPAddr,
1715                            MachinePointerInfo::getConstantPool(),
1716                            false, false, false, 0);
1717     }
1718   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719     const GlobalValue *GV = G->getGlobal();
1720     isDirect = true;
1721     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723                    getTargetMachine().getRelocationModel() != Reloc::Static;
1724     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725     // ARM call to a local ARM function is predicable.
1726     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727     // tBX takes a register source operand.
1728     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732                                                       0, ARMII::MO_NONLAZY));
1733       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734                            MachinePointerInfo::getGOT(), false, false, true, 0);
1735     } else if (Subtarget->isTargetCOFF()) {
1736       assert(Subtarget->isTargetWindows() &&
1737              "Windows is the only supported COFF target");
1738       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739                                  ? ARMII::MO_DLLIMPORT
1740                                  : ARMII::MO_NO_FLAG;
1741       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1742                                           TargetFlags);
1743       if (GV->hasDLLImportStorageClass())
1744         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746                                          Callee), MachinePointerInfo::getGOT(),
1747                              false, false, false, 0);
1748     } else {
1749       // On ELF targets for PIC code, direct calls should go through the PLT
1750       unsigned OpFlags = 0;
1751       if (Subtarget->isTargetELF() &&
1752           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753         OpFlags = ARMII::MO_PLT;
1754       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1755     }
1756   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1757     isDirect = true;
1758     bool isStub = Subtarget->isTargetMachO() &&
1759                   getTargetMachine().getRelocationModel() != Reloc::Static;
1760     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761     // tBX takes a register source operand.
1762     const char *Sym = S->getSymbol();
1763     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765       ARMConstantPoolValue *CPV =
1766         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767                                       ARMPCLabelIndex, 4);
1768       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770       Callee = DAG.getLoad(getPointerTy(), dl,
1771                            DAG.getEntryNode(), CPAddr,
1772                            MachinePointerInfo::getConstantPool(),
1773                            false, false, false, 0);
1774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776                            getPointerTy(), Callee, PICLabel);
1777     } else {
1778       unsigned OpFlags = 0;
1779       // On ELF targets for PIC code, direct calls should go through the PLT
1780       if (Subtarget->isTargetELF() &&
1781                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782         OpFlags = ARMII::MO_PLT;
1783       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1784     }
1785   }
1786
1787   // FIXME: handle tail calls differently.
1788   unsigned CallOpc;
1789   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1790   if (Subtarget->isThumb()) {
1791     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1792       CallOpc = ARMISD::CALL_NOLINK;
1793     else
1794       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1795   } else {
1796     if (!isDirect && !Subtarget->hasV5TOps())
1797       CallOpc = ARMISD::CALL_NOLINK;
1798     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1799                // Emit regular call when code size is the priority
1800                !HasMinSizeAttr)
1801       // "mov lr, pc; b _foo" to avoid confusing the RSP
1802       CallOpc = ARMISD::CALL_NOLINK;
1803     else
1804       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1805   }
1806
1807   std::vector<SDValue> Ops;
1808   Ops.push_back(Chain);
1809   Ops.push_back(Callee);
1810
1811   // Add argument registers to the end of the list so that they are known live
1812   // into the call.
1813   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815                                   RegsToPass[i].second.getValueType()));
1816
1817   // Add a register mask operand representing the call-preserved registers.
1818   if (!isTailCall) {
1819     const uint32_t *Mask;
1820     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1821     if (isThisReturn) {
1822       // For 'this' returns, use the R0-preserving mask if applicable
1823       Mask = ARI->getThisReturnPreservedMask(CallConv);
1824       if (!Mask) {
1825         // Set isThisReturn to false if the calling convention is not one that
1826         // allows 'returned' to be modeled in this way, so LowerCallResult does
1827         // not try to pass 'this' straight through
1828         isThisReturn = false;
1829         Mask = ARI->getCallPreservedMask(CallConv);
1830       }
1831     } else
1832       Mask = ARI->getCallPreservedMask(CallConv);
1833
1834     assert(Mask && "Missing call preserved mask for calling convention");
1835     Ops.push_back(DAG.getRegisterMask(Mask));
1836   }
1837
1838   if (InFlag.getNode())
1839     Ops.push_back(InFlag);
1840
1841   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1842   if (isTailCall)
1843     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1844
1845   // Returns a chain and a flag for retval copy to use.
1846   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1847   InFlag = Chain.getValue(1);
1848
1849   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1850                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1851   if (!Ins.empty())
1852     InFlag = Chain.getValue(1);
1853
1854   // Handle result values, copying them out of physregs into vregs that we
1855   // return.
1856   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1857                          InVals, isThisReturn,
1858                          isThisReturn ? OutVals[0] : SDValue());
1859 }
1860
1861 /// HandleByVal - Every parameter *after* a byval parameter is passed
1862 /// on the stack.  Remember the next parameter register to allocate,
1863 /// and then confiscate the rest of the parameter registers to insure
1864 /// this.
1865 void
1866 ARMTargetLowering::HandleByVal(
1867     CCState *State, unsigned &size, unsigned Align) const {
1868   unsigned reg = State->AllocateReg(GPRArgRegs);
1869   assert((State->getCallOrPrologue() == Prologue ||
1870           State->getCallOrPrologue() == Call) &&
1871          "unhandled ParmContext");
1872
1873   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1874     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1875       unsigned AlignInRegs = Align / 4;
1876       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1877       for (unsigned i = 0; i < Waste; ++i)
1878         reg = State->AllocateReg(GPRArgRegs);
1879     }
1880     if (reg != 0) {
1881       unsigned excess = 4 * (ARM::R4 - reg);
1882
1883       // Special case when NSAA != SP and parameter size greater than size of
1884       // all remained GPR regs. In that case we can't split parameter, we must
1885       // send it to stack. We also must set NCRN to R4, so waste all
1886       // remained registers.
1887       const unsigned NSAAOffset = State->getNextStackOffset();
1888       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1889         while (State->AllocateReg(GPRArgRegs))
1890           ;
1891         return;
1892       }
1893
1894       // First register for byval parameter is the first register that wasn't
1895       // allocated before this method call, so it would be "reg".
1896       // If parameter is small enough to be saved in range [reg, r4), then
1897       // the end (first after last) register would be reg + param-size-in-regs,
1898       // else parameter would be splitted between registers and stack,
1899       // end register would be r4 in this case.
1900       unsigned ByValRegBegin = reg;
1901       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1902       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1903       // Note, first register is allocated in the beginning of function already,
1904       // allocate remained amount of registers we need.
1905       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1906         State->AllocateReg(GPRArgRegs);
1907       // A byval parameter that is split between registers and memory needs its
1908       // size truncated here.
1909       // In the case where the entire structure fits in registers, we set the
1910       // size in memory to zero.
1911       if (size < excess)
1912         size = 0;
1913       else
1914         size -= excess;
1915     }
1916   }
1917 }
1918
1919 /// MatchingStackOffset - Return true if the given stack call argument is
1920 /// already available in the same position (relatively) of the caller's
1921 /// incoming argument stack.
1922 static
1923 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1924                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1925                          const TargetInstrInfo *TII) {
1926   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1927   int FI = INT_MAX;
1928   if (Arg.getOpcode() == ISD::CopyFromReg) {
1929     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1930     if (!TargetRegisterInfo::isVirtualRegister(VR))
1931       return false;
1932     MachineInstr *Def = MRI->getVRegDef(VR);
1933     if (!Def)
1934       return false;
1935     if (!Flags.isByVal()) {
1936       if (!TII->isLoadFromStackSlot(Def, FI))
1937         return false;
1938     } else {
1939       return false;
1940     }
1941   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1942     if (Flags.isByVal())
1943       // ByVal argument is passed in as a pointer but it's now being
1944       // dereferenced. e.g.
1945       // define @foo(%struct.X* %A) {
1946       //   tail call @bar(%struct.X* byval %A)
1947       // }
1948       return false;
1949     SDValue Ptr = Ld->getBasePtr();
1950     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1951     if (!FINode)
1952       return false;
1953     FI = FINode->getIndex();
1954   } else
1955     return false;
1956
1957   assert(FI != INT_MAX);
1958   if (!MFI->isFixedObjectIndex(FI))
1959     return false;
1960   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1961 }
1962
1963 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1964 /// for tail call optimization. Targets which want to do tail call
1965 /// optimization should implement this function.
1966 bool
1967 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1968                                                      CallingConv::ID CalleeCC,
1969                                                      bool isVarArg,
1970                                                      bool isCalleeStructRet,
1971                                                      bool isCallerStructRet,
1972                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1973                                     const SmallVectorImpl<SDValue> &OutVals,
1974                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1975                                                      SelectionDAG& DAG) const {
1976   const Function *CallerF = DAG.getMachineFunction().getFunction();
1977   CallingConv::ID CallerCC = CallerF->getCallingConv();
1978   bool CCMatch = CallerCC == CalleeCC;
1979
1980   // Look for obvious safe cases to perform tail call optimization that do not
1981   // require ABI changes. This is what gcc calls sibcall.
1982
1983   // Do not sibcall optimize vararg calls unless the call site is not passing
1984   // any arguments.
1985   if (isVarArg && !Outs.empty())
1986     return false;
1987
1988   // Exception-handling functions need a special set of instructions to indicate
1989   // a return to the hardware. Tail-calling another function would probably
1990   // break this.
1991   if (CallerF->hasFnAttribute("interrupt"))
1992     return false;
1993
1994   // Also avoid sibcall optimization if either caller or callee uses struct
1995   // return semantics.
1996   if (isCalleeStructRet || isCallerStructRet)
1997     return false;
1998
1999   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2000   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2001   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2002   // support in the assembler and linker to be used. This would need to be
2003   // fixed to fully support tail calls in Thumb1.
2004   //
2005   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2006   // LR.  This means if we need to reload LR, it takes an extra instructions,
2007   // which outweighs the value of the tail call; but here we don't know yet
2008   // whether LR is going to be used.  Probably the right approach is to
2009   // generate the tail call here and turn it back into CALL/RET in
2010   // emitEpilogue if LR is used.
2011
2012   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2013   // but we need to make sure there are enough registers; the only valid
2014   // registers are the 4 used for parameters.  We don't currently do this
2015   // case.
2016   if (Subtarget->isThumb1Only())
2017     return false;
2018
2019   // Externally-defined functions with weak linkage should not be
2020   // tail-called on ARM when the OS does not support dynamic
2021   // pre-emption of symbols, as the AAELF spec requires normal calls
2022   // to undefined weak functions to be replaced with a NOP or jump to the
2023   // next instruction. The behaviour of branch instructions in this
2024   // situation (as used for tail calls) is implementation-defined, so we
2025   // cannot rely on the linker replacing the tail call with a return.
2026   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2027     const GlobalValue *GV = G->getGlobal();
2028     const Triple TT(getTargetMachine().getTargetTriple());
2029     if (GV->hasExternalWeakLinkage() &&
2030         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2031       return false;
2032   }
2033
2034   // If the calling conventions do not match, then we'd better make sure the
2035   // results are returned in the same way as what the caller expects.
2036   if (!CCMatch) {
2037     SmallVector<CCValAssign, 16> RVLocs1;
2038     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2039                        *DAG.getContext(), Call);
2040     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2041
2042     SmallVector<CCValAssign, 16> RVLocs2;
2043     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2044                        *DAG.getContext(), Call);
2045     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2046
2047     if (RVLocs1.size() != RVLocs2.size())
2048       return false;
2049     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2050       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2051         return false;
2052       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2053         return false;
2054       if (RVLocs1[i].isRegLoc()) {
2055         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2056           return false;
2057       } else {
2058         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2059           return false;
2060       }
2061     }
2062   }
2063
2064   // If Caller's vararg or byval argument has been split between registers and
2065   // stack, do not perform tail call, since part of the argument is in caller's
2066   // local frame.
2067   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2068                                       getInfo<ARMFunctionInfo>();
2069   if (AFI_Caller->getArgRegsSaveSize())
2070     return false;
2071
2072   // If the callee takes no arguments then go on to check the results of the
2073   // call.
2074   if (!Outs.empty()) {
2075     // Check if stack adjustment is needed. For now, do not do this if any
2076     // argument is passed on the stack.
2077     SmallVector<CCValAssign, 16> ArgLocs;
2078     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2079                       *DAG.getContext(), Call);
2080     CCInfo.AnalyzeCallOperands(Outs,
2081                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2082     if (CCInfo.getNextStackOffset()) {
2083       MachineFunction &MF = DAG.getMachineFunction();
2084
2085       // Check if the arguments are already laid out in the right way as
2086       // the caller's fixed stack objects.
2087       MachineFrameInfo *MFI = MF.getFrameInfo();
2088       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2089       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2090       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2091            i != e;
2092            ++i, ++realArgIdx) {
2093         CCValAssign &VA = ArgLocs[i];
2094         EVT RegVT = VA.getLocVT();
2095         SDValue Arg = OutVals[realArgIdx];
2096         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2097         if (VA.getLocInfo() == CCValAssign::Indirect)
2098           return false;
2099         if (VA.needsCustom()) {
2100           // f64 and vector types are split into multiple registers or
2101           // register/stack-slot combinations.  The types will not match
2102           // the registers; give up on memory f64 refs until we figure
2103           // out what to do about this.
2104           if (!VA.isRegLoc())
2105             return false;
2106           if (!ArgLocs[++i].isRegLoc())
2107             return false;
2108           if (RegVT == MVT::v2f64) {
2109             if (!ArgLocs[++i].isRegLoc())
2110               return false;
2111             if (!ArgLocs[++i].isRegLoc())
2112               return false;
2113           }
2114         } else if (!VA.isRegLoc()) {
2115           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2116                                    MFI, MRI, TII))
2117             return false;
2118         }
2119       }
2120     }
2121   }
2122
2123   return true;
2124 }
2125
2126 bool
2127 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2128                                   MachineFunction &MF, bool isVarArg,
2129                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2130                                   LLVMContext &Context) const {
2131   SmallVector<CCValAssign, 16> RVLocs;
2132   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2133   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2134                                                     isVarArg));
2135 }
2136
2137 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2138                                     SDLoc DL, SelectionDAG &DAG) {
2139   const MachineFunction &MF = DAG.getMachineFunction();
2140   const Function *F = MF.getFunction();
2141
2142   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2143
2144   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2145   // version of the "preferred return address". These offsets affect the return
2146   // instruction if this is a return from PL1 without hypervisor extensions.
2147   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2148   //    SWI:     0      "subs pc, lr, #0"
2149   //    ABORT:   +4     "subs pc, lr, #4"
2150   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2151   // UNDEF varies depending on where the exception came from ARM or Thumb
2152   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2153
2154   int64_t LROffset;
2155   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2156       IntKind == "ABORT")
2157     LROffset = 4;
2158   else if (IntKind == "SWI" || IntKind == "UNDEF")
2159     LROffset = 0;
2160   else
2161     report_fatal_error("Unsupported interrupt attribute. If present, value "
2162                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2163
2164   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2165
2166   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2167 }
2168
2169 SDValue
2170 ARMTargetLowering::LowerReturn(SDValue Chain,
2171                                CallingConv::ID CallConv, bool isVarArg,
2172                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2173                                const SmallVectorImpl<SDValue> &OutVals,
2174                                SDLoc dl, SelectionDAG &DAG) const {
2175
2176   // CCValAssign - represent the assignment of the return value to a location.
2177   SmallVector<CCValAssign, 16> RVLocs;
2178
2179   // CCState - Info about the registers and stack slots.
2180   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2181                     *DAG.getContext(), Call);
2182
2183   // Analyze outgoing return values.
2184   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2185                                                isVarArg));
2186
2187   SDValue Flag;
2188   SmallVector<SDValue, 4> RetOps;
2189   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2190   bool isLittleEndian = Subtarget->isLittle();
2191
2192   MachineFunction &MF = DAG.getMachineFunction();
2193   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2194   AFI->setReturnRegsCount(RVLocs.size());
2195
2196   // Copy the result values into the output registers.
2197   for (unsigned i = 0, realRVLocIdx = 0;
2198        i != RVLocs.size();
2199        ++i, ++realRVLocIdx) {
2200     CCValAssign &VA = RVLocs[i];
2201     assert(VA.isRegLoc() && "Can only return in registers!");
2202
2203     SDValue Arg = OutVals[realRVLocIdx];
2204
2205     switch (VA.getLocInfo()) {
2206     default: llvm_unreachable("Unknown loc info!");
2207     case CCValAssign::Full: break;
2208     case CCValAssign::BCvt:
2209       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2210       break;
2211     }
2212
2213     if (VA.needsCustom()) {
2214       if (VA.getLocVT() == MVT::v2f64) {
2215         // Extract the first half and return it in two registers.
2216         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2217                                    DAG.getConstant(0, MVT::i32));
2218         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2219                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2220
2221         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2222                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2223                                  Flag);
2224         Flag = Chain.getValue(1);
2225         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2226         VA = RVLocs[++i]; // skip ahead to next loc
2227         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2228                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2229                                  Flag);
2230         Flag = Chain.getValue(1);
2231         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2232         VA = RVLocs[++i]; // skip ahead to next loc
2233
2234         // Extract the 2nd half and fall through to handle it as an f64 value.
2235         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2236                           DAG.getConstant(1, MVT::i32));
2237       }
2238       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2239       // available.
2240       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2241                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2242       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2243                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2244                                Flag);
2245       Flag = Chain.getValue(1);
2246       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2247       VA = RVLocs[++i]; // skip ahead to next loc
2248       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2249                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2250                                Flag);
2251     } else
2252       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2253
2254     // Guarantee that all emitted copies are
2255     // stuck together, avoiding something bad.
2256     Flag = Chain.getValue(1);
2257     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2258   }
2259
2260   // Update chain and glue.
2261   RetOps[0] = Chain;
2262   if (Flag.getNode())
2263     RetOps.push_back(Flag);
2264
2265   // CPUs which aren't M-class use a special sequence to return from
2266   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2267   // though we use "subs pc, lr, #N").
2268   //
2269   // M-class CPUs actually use a normal return sequence with a special
2270   // (hardware-provided) value in LR, so the normal code path works.
2271   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2272       !Subtarget->isMClass()) {
2273     if (Subtarget->isThumb1Only())
2274       report_fatal_error("interrupt attribute is not supported in Thumb1");
2275     return LowerInterruptReturn(RetOps, dl, DAG);
2276   }
2277
2278   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2279 }
2280
2281 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2282   if (N->getNumValues() != 1)
2283     return false;
2284   if (!N->hasNUsesOfValue(1, 0))
2285     return false;
2286
2287   SDValue TCChain = Chain;
2288   SDNode *Copy = *N->use_begin();
2289   if (Copy->getOpcode() == ISD::CopyToReg) {
2290     // If the copy has a glue operand, we conservatively assume it isn't safe to
2291     // perform a tail call.
2292     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2293       return false;
2294     TCChain = Copy->getOperand(0);
2295   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2296     SDNode *VMov = Copy;
2297     // f64 returned in a pair of GPRs.
2298     SmallPtrSet<SDNode*, 2> Copies;
2299     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2300          UI != UE; ++UI) {
2301       if (UI->getOpcode() != ISD::CopyToReg)
2302         return false;
2303       Copies.insert(*UI);
2304     }
2305     if (Copies.size() > 2)
2306       return false;
2307
2308     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2309          UI != UE; ++UI) {
2310       SDValue UseChain = UI->getOperand(0);
2311       if (Copies.count(UseChain.getNode()))
2312         // Second CopyToReg
2313         Copy = *UI;
2314       else {
2315         // We are at the top of this chain.
2316         // If the copy has a glue operand, we conservatively assume it
2317         // isn't safe to perform a tail call.
2318         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2319           return false;
2320         // First CopyToReg
2321         TCChain = UseChain;
2322       }
2323     }
2324   } else if (Copy->getOpcode() == ISD::BITCAST) {
2325     // f32 returned in a single GPR.
2326     if (!Copy->hasOneUse())
2327       return false;
2328     Copy = *Copy->use_begin();
2329     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2330       return false;
2331     // If the copy has a glue operand, we conservatively assume it isn't safe to
2332     // perform a tail call.
2333     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2334       return false;
2335     TCChain = Copy->getOperand(0);
2336   } else {
2337     return false;
2338   }
2339
2340   bool HasRet = false;
2341   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2342        UI != UE; ++UI) {
2343     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2344         UI->getOpcode() != ARMISD::INTRET_FLAG)
2345       return false;
2346     HasRet = true;
2347   }
2348
2349   if (!HasRet)
2350     return false;
2351
2352   Chain = TCChain;
2353   return true;
2354 }
2355
2356 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2357   if (!Subtarget->supportsTailCall())
2358     return false;
2359
2360   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2361     return false;
2362
2363   return !Subtarget->isThumb1Only();
2364 }
2365
2366 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2367 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2368 // one of the above mentioned nodes. It has to be wrapped because otherwise
2369 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2370 // be used to form addressing mode. These wrapped nodes will be selected
2371 // into MOVi.
2372 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2373   EVT PtrVT = Op.getValueType();
2374   // FIXME there is no actual debug info here
2375   SDLoc dl(Op);
2376   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2377   SDValue Res;
2378   if (CP->isMachineConstantPoolEntry())
2379     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2380                                     CP->getAlignment());
2381   else
2382     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2383                                     CP->getAlignment());
2384   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2385 }
2386
2387 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2388   return MachineJumpTableInfo::EK_Inline;
2389 }
2390
2391 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2392                                              SelectionDAG &DAG) const {
2393   MachineFunction &MF = DAG.getMachineFunction();
2394   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2395   unsigned ARMPCLabelIndex = 0;
2396   SDLoc DL(Op);
2397   EVT PtrVT = getPointerTy();
2398   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2399   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2400   SDValue CPAddr;
2401   if (RelocM == Reloc::Static) {
2402     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2403   } else {
2404     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2405     ARMPCLabelIndex = AFI->createPICLabelUId();
2406     ARMConstantPoolValue *CPV =
2407       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2408                                       ARMCP::CPBlockAddress, PCAdj);
2409     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2410   }
2411   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2412   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2413                                MachinePointerInfo::getConstantPool(),
2414                                false, false, false, 0);
2415   if (RelocM == Reloc::Static)
2416     return Result;
2417   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2418   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2419 }
2420
2421 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2422 SDValue
2423 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2424                                                  SelectionDAG &DAG) const {
2425   SDLoc dl(GA);
2426   EVT PtrVT = getPointerTy();
2427   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2428   MachineFunction &MF = DAG.getMachineFunction();
2429   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2430   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2431   ARMConstantPoolValue *CPV =
2432     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2433                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2434   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2435   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2436   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2437                          MachinePointerInfo::getConstantPool(),
2438                          false, false, false, 0);
2439   SDValue Chain = Argument.getValue(1);
2440
2441   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2442   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2443
2444   // call __tls_get_addr.
2445   ArgListTy Args;
2446   ArgListEntry Entry;
2447   Entry.Node = Argument;
2448   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2449   Args.push_back(Entry);
2450
2451   // FIXME: is there useful debug info available here?
2452   TargetLowering::CallLoweringInfo CLI(DAG);
2453   CLI.setDebugLoc(dl).setChain(Chain)
2454     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2455                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2456                0);
2457
2458   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2459   return CallResult.first;
2460 }
2461
2462 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2463 // "local exec" model.
2464 SDValue
2465 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2466                                         SelectionDAG &DAG,
2467                                         TLSModel::Model model) const {
2468   const GlobalValue *GV = GA->getGlobal();
2469   SDLoc dl(GA);
2470   SDValue Offset;
2471   SDValue Chain = DAG.getEntryNode();
2472   EVT PtrVT = getPointerTy();
2473   // Get the Thread Pointer
2474   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2475
2476   if (model == TLSModel::InitialExec) {
2477     MachineFunction &MF = DAG.getMachineFunction();
2478     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2479     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2480     // Initial exec model.
2481     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2482     ARMConstantPoolValue *CPV =
2483       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2484                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2485                                       true);
2486     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2487     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2488     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2489                          MachinePointerInfo::getConstantPool(),
2490                          false, false, false, 0);
2491     Chain = Offset.getValue(1);
2492
2493     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2494     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2495
2496     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2497                          MachinePointerInfo::getConstantPool(),
2498                          false, false, false, 0);
2499   } else {
2500     // local exec model
2501     assert(model == TLSModel::LocalExec);
2502     ARMConstantPoolValue *CPV =
2503       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2504     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2505     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2506     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2507                          MachinePointerInfo::getConstantPool(),
2508                          false, false, false, 0);
2509   }
2510
2511   // The address of the thread local variable is the add of the thread
2512   // pointer with the offset of the variable.
2513   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2514 }
2515
2516 SDValue
2517 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2518   // TODO: implement the "local dynamic" model
2519   assert(Subtarget->isTargetELF() &&
2520          "TLS not implemented for non-ELF targets");
2521   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2522
2523   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2524
2525   switch (model) {
2526     case TLSModel::GeneralDynamic:
2527     case TLSModel::LocalDynamic:
2528       return LowerToTLSGeneralDynamicModel(GA, DAG);
2529     case TLSModel::InitialExec:
2530     case TLSModel::LocalExec:
2531       return LowerToTLSExecModels(GA, DAG, model);
2532   }
2533   llvm_unreachable("bogus TLS model");
2534 }
2535
2536 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2537                                                  SelectionDAG &DAG) const {
2538   EVT PtrVT = getPointerTy();
2539   SDLoc dl(Op);
2540   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2542     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2543     ARMConstantPoolValue *CPV =
2544       ARMConstantPoolConstant::Create(GV,
2545                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2546     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2547     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2548     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2549                                  CPAddr,
2550                                  MachinePointerInfo::getConstantPool(),
2551                                  false, false, false, 0);
2552     SDValue Chain = Result.getValue(1);
2553     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2554     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2555     if (!UseGOTOFF)
2556       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2557                            MachinePointerInfo::getGOT(),
2558                            false, false, false, 0);
2559     return Result;
2560   }
2561
2562   // If we have T2 ops, we can materialize the address directly via movt/movw
2563   // pair. This is always cheaper.
2564   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2565     ++NumMovwMovt;
2566     // FIXME: Once remat is capable of dealing with instructions with register
2567     // operands, expand this into two nodes.
2568     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2569                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2570   } else {
2571     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2572     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2573     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2574                        MachinePointerInfo::getConstantPool(),
2575                        false, false, false, 0);
2576   }
2577 }
2578
2579 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2580                                                     SelectionDAG &DAG) const {
2581   EVT PtrVT = getPointerTy();
2582   SDLoc dl(Op);
2583   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2584   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2585
2586   if (Subtarget->useMovt(DAG.getMachineFunction()))
2587     ++NumMovwMovt;
2588
2589   // FIXME: Once remat is capable of dealing with instructions with register
2590   // operands, expand this into multiple nodes
2591   unsigned Wrapper =
2592       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2593
2594   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2595   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2596
2597   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2598     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2599                          MachinePointerInfo::getGOT(), false, false, false, 0);
2600   return Result;
2601 }
2602
2603 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2604                                                      SelectionDAG &DAG) const {
2605   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2606   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2607          "Windows on ARM expects to use movw/movt");
2608
2609   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2610   const ARMII::TOF TargetFlags =
2611     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2612   EVT PtrVT = getPointerTy();
2613   SDValue Result;
2614   SDLoc DL(Op);
2615
2616   ++NumMovwMovt;
2617
2618   // FIXME: Once remat is capable of dealing with instructions with register
2619   // operands, expand this into two nodes.
2620   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2621                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2622                                                   TargetFlags));
2623   if (GV->hasDLLImportStorageClass())
2624     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2625                          MachinePointerInfo::getGOT(), false, false, false, 0);
2626   return Result;
2627 }
2628
2629 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2630                                                     SelectionDAG &DAG) const {
2631   assert(Subtarget->isTargetELF() &&
2632          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2633   MachineFunction &MF = DAG.getMachineFunction();
2634   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2635   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2636   EVT PtrVT = getPointerTy();
2637   SDLoc dl(Op);
2638   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2639   ARMConstantPoolValue *CPV =
2640     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2641                                   ARMPCLabelIndex, PCAdj);
2642   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2643   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2644   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2645                                MachinePointerInfo::getConstantPool(),
2646                                false, false, false, 0);
2647   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2648   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2649 }
2650
2651 SDValue
2652 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2653   SDLoc dl(Op);
2654   SDValue Val = DAG.getConstant(0, MVT::i32);
2655   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2656                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2657                      Op.getOperand(1), Val);
2658 }
2659
2660 SDValue
2661 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2662   SDLoc dl(Op);
2663   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2664                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2665 }
2666
2667 SDValue
2668 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2669                                           const ARMSubtarget *Subtarget) const {
2670   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2671   SDLoc dl(Op);
2672   switch (IntNo) {
2673   default: return SDValue();    // Don't custom lower most intrinsics.
2674   case Intrinsic::arm_rbit: {
2675     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2676            "RBIT intrinsic must have i32 type!");
2677     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2678   }
2679   case Intrinsic::arm_thread_pointer: {
2680     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2681     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2682   }
2683   case Intrinsic::eh_sjlj_lsda: {
2684     MachineFunction &MF = DAG.getMachineFunction();
2685     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2686     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2687     EVT PtrVT = getPointerTy();
2688     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2689     SDValue CPAddr;
2690     unsigned PCAdj = (RelocM != Reloc::PIC_)
2691       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2692     ARMConstantPoolValue *CPV =
2693       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2694                                       ARMCP::CPLSDA, PCAdj);
2695     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2696     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2697     SDValue Result =
2698       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2699                   MachinePointerInfo::getConstantPool(),
2700                   false, false, false, 0);
2701
2702     if (RelocM == Reloc::PIC_) {
2703       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2704       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2705     }
2706     return Result;
2707   }
2708   case Intrinsic::arm_neon_vmulls:
2709   case Intrinsic::arm_neon_vmullu: {
2710     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2711       ? ARMISD::VMULLs : ARMISD::VMULLu;
2712     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2713                        Op.getOperand(1), Op.getOperand(2));
2714   }
2715   }
2716 }
2717
2718 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2719                                  const ARMSubtarget *Subtarget) {
2720   // FIXME: handle "fence singlethread" more efficiently.
2721   SDLoc dl(Op);
2722   if (!Subtarget->hasDataBarrier()) {
2723     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2724     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2725     // here.
2726     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2727            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2728     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2729                        DAG.getConstant(0, MVT::i32));
2730   }
2731
2732   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2733   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2734   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2735   if (Subtarget->isMClass()) {
2736     // Only a full system barrier exists in the M-class architectures.
2737     Domain = ARM_MB::SY;
2738   } else if (Subtarget->isSwift() && Ord == Release) {
2739     // Swift happens to implement ISHST barriers in a way that's compatible with
2740     // Release semantics but weaker than ISH so we'd be fools not to use
2741     // it. Beware: other processors probably don't!
2742     Domain = ARM_MB::ISHST;
2743   }
2744
2745   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2746                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2747                      DAG.getConstant(Domain, MVT::i32));
2748 }
2749
2750 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2751                              const ARMSubtarget *Subtarget) {
2752   // ARM pre v5TE and Thumb1 does not have preload instructions.
2753   if (!(Subtarget->isThumb2() ||
2754         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2755     // Just preserve the chain.
2756     return Op.getOperand(0);
2757
2758   SDLoc dl(Op);
2759   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2760   if (!isRead &&
2761       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2762     // ARMv7 with MP extension has PLDW.
2763     return Op.getOperand(0);
2764
2765   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2766   if (Subtarget->isThumb()) {
2767     // Invert the bits.
2768     isRead = ~isRead & 1;
2769     isData = ~isData & 1;
2770   }
2771
2772   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2773                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2774                      DAG.getConstant(isData, MVT::i32));
2775 }
2776
2777 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2778   MachineFunction &MF = DAG.getMachineFunction();
2779   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2780
2781   // vastart just stores the address of the VarArgsFrameIndex slot into the
2782   // memory location argument.
2783   SDLoc dl(Op);
2784   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2785   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2786   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2787   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2788                       MachinePointerInfo(SV), false, false, 0);
2789 }
2790
2791 SDValue
2792 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2793                                         SDValue &Root, SelectionDAG &DAG,
2794                                         SDLoc dl) const {
2795   MachineFunction &MF = DAG.getMachineFunction();
2796   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2797
2798   const TargetRegisterClass *RC;
2799   if (AFI->isThumb1OnlyFunction())
2800     RC = &ARM::tGPRRegClass;
2801   else
2802     RC = &ARM::GPRRegClass;
2803
2804   // Transform the arguments stored in physical registers into virtual ones.
2805   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2806   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2807
2808   SDValue ArgValue2;
2809   if (NextVA.isMemLoc()) {
2810     MachineFrameInfo *MFI = MF.getFrameInfo();
2811     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2812
2813     // Create load node to retrieve arguments from the stack.
2814     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2815     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2816                             MachinePointerInfo::getFixedStack(FI),
2817                             false, false, false, 0);
2818   } else {
2819     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2820     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2821   }
2822   if (!Subtarget->isLittle())
2823     std::swap (ArgValue, ArgValue2);
2824   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2825 }
2826
2827 void
2828 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2829                                   unsigned InRegsParamRecordIdx,
2830                                   unsigned ArgSize,
2831                                   unsigned &ArgRegsSize,
2832                                   unsigned &ArgRegsSaveSize)
2833   const {
2834   unsigned NumGPRs;
2835   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2836     unsigned RBegin, REnd;
2837     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2838     NumGPRs = REnd - RBegin;
2839   } else {
2840     unsigned int firstUnalloced;
2841     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs);
2842     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2843   }
2844
2845   unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2846   ArgRegsSize = NumGPRs * 4;
2847
2848   // If parameter is split between stack and GPRs...
2849   if (NumGPRs && Align > 4 &&
2850       (ArgRegsSize < ArgSize ||
2851         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2852     // Add padding for part of param recovered from GPRs.  For example,
2853     // if Align == 8, its last byte must be at address K*8 - 1.
2854     // We need to do it, since remained (stack) part of parameter has
2855     // stack alignment, and we need to "attach" "GPRs head" without gaps
2856     // to it:
2857     // Stack:
2858     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2859     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2860     //
2861     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2862     unsigned Padding =
2863         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2864     ArgRegsSaveSize = ArgRegsSize + Padding;
2865   } else
2866     // We don't need to extend regs save size for byval parameters if they
2867     // are passed via GPRs only.
2868     ArgRegsSaveSize = ArgRegsSize;
2869 }
2870
2871 // The remaining GPRs hold either the beginning of variable-argument
2872 // data, or the beginning of an aggregate passed by value (usually
2873 // byval).  Either way, we allocate stack slots adjacent to the data
2874 // provided by our caller, and store the unallocated registers there.
2875 // If this is a variadic function, the va_list pointer will begin with
2876 // these values; otherwise, this reassembles a (byval) structure that
2877 // was split between registers and memory.
2878 // Return: The frame index registers were stored into.
2879 int
2880 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2881                                   SDLoc dl, SDValue &Chain,
2882                                   const Value *OrigArg,
2883                                   unsigned InRegsParamRecordIdx,
2884                                   unsigned OffsetFromOrigArg,
2885                                   unsigned ArgOffset,
2886                                   unsigned ArgSize,
2887                                   bool ForceMutable,
2888                                   unsigned ByValStoreOffset,
2889                                   unsigned TotalArgRegsSaveSize) const {
2890
2891   // Currently, two use-cases possible:
2892   // Case #1. Non-var-args function, and we meet first byval parameter.
2893   //          Setup first unallocated register as first byval register;
2894   //          eat all remained registers
2895   //          (these two actions are performed by HandleByVal method).
2896   //          Then, here, we initialize stack frame with
2897   //          "store-reg" instructions.
2898   // Case #2. Var-args function, that doesn't contain byval parameters.
2899   //          The same: eat all remained unallocated registers,
2900   //          initialize stack frame.
2901
2902   MachineFunction &MF = DAG.getMachineFunction();
2903   MachineFrameInfo *MFI = MF.getFrameInfo();
2904   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2905   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2906   unsigned RBegin, REnd;
2907   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2908     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2909     firstRegToSaveIndex = RBegin - ARM::R0;
2910     lastRegToSaveIndex = REnd - ARM::R0;
2911   } else {
2912     firstRegToSaveIndex = CCInfo.getFirstUnallocated(GPRArgRegs);
2913     lastRegToSaveIndex = 4;
2914   }
2915
2916   unsigned ArgRegsSize, ArgRegsSaveSize;
2917   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2918                  ArgRegsSize, ArgRegsSaveSize);
2919
2920   // Store any by-val regs to their spots on the stack so that they may be
2921   // loaded by deferencing the result of formal parameter pointer or va_next.
2922   // Note: once stack area for byval/varargs registers
2923   // was initialized, it can't be initialized again.
2924   if (ArgRegsSaveSize) {
2925     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2926
2927     if (Padding) {
2928       assert(AFI->getStoredByValParamsPadding() == 0 &&
2929              "The only parameter may be padded.");
2930       AFI->setStoredByValParamsPadding(Padding);
2931     }
2932
2933     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2934                                             Padding +
2935                                               ByValStoreOffset -
2936                                               (int64_t)TotalArgRegsSaveSize,
2937                                             false);
2938     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2939     if (Padding) {
2940        MFI->CreateFixedObject(Padding,
2941                               ArgOffset + ByValStoreOffset -
2942                                 (int64_t)ArgRegsSaveSize,
2943                               false);
2944     }
2945
2946     SmallVector<SDValue, 4> MemOps;
2947     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2948          ++firstRegToSaveIndex, ++i) {
2949       const TargetRegisterClass *RC;
2950       if (AFI->isThumb1OnlyFunction())
2951         RC = &ARM::tGPRRegClass;
2952       else
2953         RC = &ARM::GPRRegClass;
2954
2955       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2956       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2957       SDValue Store =
2958         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2959                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2960                      false, false, 0);
2961       MemOps.push_back(Store);
2962       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2963                         DAG.getConstant(4, getPointerTy()));
2964     }
2965
2966     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2967
2968     if (!MemOps.empty())
2969       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2970     return FrameIndex;
2971   } else {
2972     if (ArgSize == 0) {
2973       // We cannot allocate a zero-byte object for the first variadic argument,
2974       // so just make up a size.
2975       ArgSize = 4;
2976     }
2977     // This will point to the next argument passed via stack.
2978     return MFI->CreateFixedObject(
2979       ArgSize, ArgOffset, !ForceMutable);
2980   }
2981 }
2982
2983 // Setup stack frame, the va_list pointer will start from.
2984 void
2985 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2986                                         SDLoc dl, SDValue &Chain,
2987                                         unsigned ArgOffset,
2988                                         unsigned TotalArgRegsSaveSize,
2989                                         bool ForceMutable) const {
2990   MachineFunction &MF = DAG.getMachineFunction();
2991   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2992
2993   // Try to store any remaining integer argument regs
2994   // to their spots on the stack so that they may be loaded by deferencing
2995   // the result of va_next.
2996   // If there is no regs to be stored, just point address after last
2997   // argument passed via stack.
2998   int FrameIndex =
2999     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3000                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3001                    0, TotalArgRegsSaveSize);
3002
3003   AFI->setVarArgsFrameIndex(FrameIndex);
3004 }
3005
3006 SDValue
3007 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3008                                         CallingConv::ID CallConv, bool isVarArg,
3009                                         const SmallVectorImpl<ISD::InputArg>
3010                                           &Ins,
3011                                         SDLoc dl, SelectionDAG &DAG,
3012                                         SmallVectorImpl<SDValue> &InVals)
3013                                           const {
3014   MachineFunction &MF = DAG.getMachineFunction();
3015   MachineFrameInfo *MFI = MF.getFrameInfo();
3016
3017   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3018
3019   // Assign locations to all of the incoming arguments.
3020   SmallVector<CCValAssign, 16> ArgLocs;
3021   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3022                     *DAG.getContext(), Prologue);
3023   CCInfo.AnalyzeFormalArguments(Ins,
3024                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3025                                                   isVarArg));
3026
3027   SmallVector<SDValue, 16> ArgValues;
3028   int lastInsIndex = -1;
3029   SDValue ArgValue;
3030   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3031   unsigned CurArgIdx = 0;
3032
3033   // Initially ArgRegsSaveSize is zero.
3034   // Then we increase this value each time we meet byval parameter.
3035   // We also increase this value in case of varargs function.
3036   AFI->setArgRegsSaveSize(0);
3037
3038   unsigned ByValStoreOffset = 0;
3039   unsigned TotalArgRegsSaveSize = 0;
3040   unsigned ArgRegsSaveSizeMaxAlign = 4;
3041
3042   // Calculate the amount of stack space that we need to allocate to store
3043   // byval and variadic arguments that are passed in registers.
3044   // We need to know this before we allocate the first byval or variadic
3045   // argument, as they will be allocated a stack slot below the CFA (Canonical
3046   // Frame Address, the stack pointer at entry to the function).
3047   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3048     CCValAssign &VA = ArgLocs[i];
3049     if (VA.isMemLoc()) {
3050       int index = VA.getValNo();
3051       if (index != lastInsIndex) {
3052         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3053         if (Flags.isByVal()) {
3054           unsigned ExtraArgRegsSize;
3055           unsigned ExtraArgRegsSaveSize;
3056           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3057                          Flags.getByValSize(),
3058                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3059
3060           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3061           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3062               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3063           CCInfo.nextInRegsParam();
3064         }
3065         lastInsIndex = index;
3066       }
3067     }
3068   }
3069   CCInfo.rewindByValRegsInfo();
3070   lastInsIndex = -1;
3071   if (isVarArg && MFI->hasVAStart()) {
3072     unsigned ExtraArgRegsSize;
3073     unsigned ExtraArgRegsSaveSize;
3074     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3075                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3076     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3077   }
3078   // If the arg regs save area contains N-byte aligned values, the
3079   // bottom of it must be at least N-byte aligned.
3080   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3081   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3082
3083   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3084     CCValAssign &VA = ArgLocs[i];
3085     if (Ins[VA.getValNo()].isOrigArg()) {
3086       std::advance(CurOrigArg,
3087                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3088       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3089     }
3090     // Arguments stored in registers.
3091     if (VA.isRegLoc()) {
3092       EVT RegVT = VA.getLocVT();
3093
3094       if (VA.needsCustom()) {
3095         // f64 and vector types are split up into multiple registers or
3096         // combinations of registers and stack slots.
3097         if (VA.getLocVT() == MVT::v2f64) {
3098           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3099                                                    Chain, DAG, dl);
3100           VA = ArgLocs[++i]; // skip ahead to next loc
3101           SDValue ArgValue2;
3102           if (VA.isMemLoc()) {
3103             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3104             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3105             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3106                                     MachinePointerInfo::getFixedStack(FI),
3107                                     false, false, false, 0);
3108           } else {
3109             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3110                                              Chain, DAG, dl);
3111           }
3112           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3113           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3114                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3115           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3116                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3117         } else
3118           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3119
3120       } else {
3121         const TargetRegisterClass *RC;
3122
3123         if (RegVT == MVT::f32)
3124           RC = &ARM::SPRRegClass;
3125         else if (RegVT == MVT::f64)
3126           RC = &ARM::DPRRegClass;
3127         else if (RegVT == MVT::v2f64)
3128           RC = &ARM::QPRRegClass;
3129         else if (RegVT == MVT::i32)
3130           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3131                                            : &ARM::GPRRegClass;
3132         else
3133           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3134
3135         // Transform the arguments in physical registers into virtual ones.
3136         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3137         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3138       }
3139
3140       // If this is an 8 or 16-bit value, it is really passed promoted
3141       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3142       // truncate to the right size.
3143       switch (VA.getLocInfo()) {
3144       default: llvm_unreachable("Unknown loc info!");
3145       case CCValAssign::Full: break;
3146       case CCValAssign::BCvt:
3147         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3148         break;
3149       case CCValAssign::SExt:
3150         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3151                                DAG.getValueType(VA.getValVT()));
3152         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3153         break;
3154       case CCValAssign::ZExt:
3155         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3156                                DAG.getValueType(VA.getValVT()));
3157         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3158         break;
3159       }
3160
3161       InVals.push_back(ArgValue);
3162
3163     } else { // VA.isRegLoc()
3164
3165       // sanity check
3166       assert(VA.isMemLoc());
3167       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3168
3169       int index = VA.getValNo();
3170
3171       // Some Ins[] entries become multiple ArgLoc[] entries.
3172       // Process them only once.
3173       if (index != lastInsIndex)
3174         {
3175           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3176           // FIXME: For now, all byval parameter objects are marked mutable.
3177           // This can be changed with more analysis.
3178           // In case of tail call optimization mark all arguments mutable.
3179           // Since they could be overwritten by lowering of arguments in case of
3180           // a tail call.
3181           if (Flags.isByVal()) {
3182             assert(Ins[index].isOrigArg() &&
3183                    "Byval arguments cannot be implicit");
3184             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3185
3186             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3187             int FrameIndex = StoreByValRegs(
3188                 CCInfo, DAG, dl, Chain, CurOrigArg,
3189                 CurByValIndex,
3190                 Ins[VA.getValNo()].PartOffset,
3191                 VA.getLocMemOffset(),
3192                 Flags.getByValSize(),
3193                 true /*force mutable frames*/,
3194                 ByValStoreOffset,
3195                 TotalArgRegsSaveSize);
3196             ByValStoreOffset += Flags.getByValSize();
3197             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3198             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3199             CCInfo.nextInRegsParam();
3200           } else {
3201             unsigned FIOffset = VA.getLocMemOffset();
3202             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3203                                             FIOffset, true);
3204
3205             // Create load nodes to retrieve arguments from the stack.
3206             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3207             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3208                                          MachinePointerInfo::getFixedStack(FI),
3209                                          false, false, false, 0));
3210           }
3211           lastInsIndex = index;
3212         }
3213     }
3214   }
3215
3216   // varargs
3217   if (isVarArg && MFI->hasVAStart())
3218     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3219                          CCInfo.getNextStackOffset(),
3220                          TotalArgRegsSaveSize);
3221
3222   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3223
3224   return Chain;
3225 }
3226
3227 /// isFloatingPointZero - Return true if this is +0.0.
3228 static bool isFloatingPointZero(SDValue Op) {
3229   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3230     return CFP->getValueAPF().isPosZero();
3231   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3232     // Maybe this has already been legalized into the constant pool?
3233     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3234       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3235       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3236         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3237           return CFP->getValueAPF().isPosZero();
3238     }
3239   } else if (Op->getOpcode() == ISD::BITCAST &&
3240              Op->getValueType(0) == MVT::f64) {
3241     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3242     // created by LowerConstantFP().
3243     SDValue BitcastOp = Op->getOperand(0);
3244     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3245       SDValue MoveOp = BitcastOp->getOperand(0);
3246       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3247           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3248         return true;
3249       }
3250     }
3251   }
3252   return false;
3253 }
3254
3255 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3256 /// the given operands.
3257 SDValue
3258 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3259                              SDValue &ARMcc, SelectionDAG &DAG,
3260                              SDLoc dl) const {
3261   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3262     unsigned C = RHSC->getZExtValue();
3263     if (!isLegalICmpImmediate(C)) {
3264       // Constant does not fit, try adjusting it by one?
3265       switch (CC) {
3266       default: break;
3267       case ISD::SETLT:
3268       case ISD::SETGE:
3269         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3270           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3271           RHS = DAG.getConstant(C-1, MVT::i32);
3272         }
3273         break;
3274       case ISD::SETULT:
3275       case ISD::SETUGE:
3276         if (C != 0 && isLegalICmpImmediate(C-1)) {
3277           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3278           RHS = DAG.getConstant(C-1, MVT::i32);
3279         }
3280         break;
3281       case ISD::SETLE:
3282       case ISD::SETGT:
3283         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3284           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3285           RHS = DAG.getConstant(C+1, MVT::i32);
3286         }
3287         break;
3288       case ISD::SETULE:
3289       case ISD::SETUGT:
3290         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3291           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3292           RHS = DAG.getConstant(C+1, MVT::i32);
3293         }
3294         break;
3295       }
3296     }
3297   }
3298
3299   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3300   ARMISD::NodeType CompareType;
3301   switch (CondCode) {
3302   default:
3303     CompareType = ARMISD::CMP;
3304     break;
3305   case ARMCC::EQ:
3306   case ARMCC::NE:
3307     // Uses only Z Flag
3308     CompareType = ARMISD::CMPZ;
3309     break;
3310   }
3311   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3312   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3313 }
3314
3315 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3316 SDValue
3317 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3318                              SDLoc dl) const {
3319   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3320   SDValue Cmp;
3321   if (!isFloatingPointZero(RHS))
3322     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3323   else
3324     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3325   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3326 }
3327
3328 /// duplicateCmp - Glue values can have only one use, so this function
3329 /// duplicates a comparison node.
3330 SDValue
3331 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3332   unsigned Opc = Cmp.getOpcode();
3333   SDLoc DL(Cmp);
3334   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3335     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3336
3337   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3338   Cmp = Cmp.getOperand(0);
3339   Opc = Cmp.getOpcode();
3340   if (Opc == ARMISD::CMPFP)
3341     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3342   else {
3343     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3344     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3345   }
3346   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3347 }
3348
3349 std::pair<SDValue, SDValue>
3350 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3351                                  SDValue &ARMcc) const {
3352   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3353
3354   SDValue Value, OverflowCmp;
3355   SDValue LHS = Op.getOperand(0);
3356   SDValue RHS = Op.getOperand(1);
3357
3358
3359   // FIXME: We are currently always generating CMPs because we don't support
3360   // generating CMN through the backend. This is not as good as the natural
3361   // CMP case because it causes a register dependency and cannot be folded
3362   // later.
3363
3364   switch (Op.getOpcode()) {
3365   default:
3366     llvm_unreachable("Unknown overflow instruction!");
3367   case ISD::SADDO:
3368     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3369     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3370     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3371     break;
3372   case ISD::UADDO:
3373     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3374     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3375     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3376     break;
3377   case ISD::SSUBO:
3378     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3379     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3380     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3381     break;
3382   case ISD::USUBO:
3383     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3384     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3385     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3386     break;
3387   } // switch (...)
3388
3389   return std::make_pair(Value, OverflowCmp);
3390 }
3391
3392
3393 SDValue
3394 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3395   // Let legalize expand this if it isn't a legal type yet.
3396   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3397     return SDValue();
3398
3399   SDValue Value, OverflowCmp;
3400   SDValue ARMcc;
3401   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3402   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3403   // We use 0 and 1 as false and true values.
3404   SDValue TVal = DAG.getConstant(1, MVT::i32);
3405   SDValue FVal = DAG.getConstant(0, MVT::i32);
3406   EVT VT = Op.getValueType();
3407
3408   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3409                                  ARMcc, CCR, OverflowCmp);
3410
3411   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3412   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3413 }
3414
3415
3416 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3417   SDValue Cond = Op.getOperand(0);
3418   SDValue SelectTrue = Op.getOperand(1);
3419   SDValue SelectFalse = Op.getOperand(2);
3420   SDLoc dl(Op);
3421   unsigned Opc = Cond.getOpcode();
3422
3423   if (Cond.getResNo() == 1 &&
3424       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3425        Opc == ISD::USUBO)) {
3426     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3427       return SDValue();
3428
3429     SDValue Value, OverflowCmp;
3430     SDValue ARMcc;
3431     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3432     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3433     EVT VT = Op.getValueType();
3434
3435     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3436                    OverflowCmp, DAG);
3437   }
3438
3439   // Convert:
3440   //
3441   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3442   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3443   //
3444   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3445     const ConstantSDNode *CMOVTrue =
3446       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3447     const ConstantSDNode *CMOVFalse =
3448       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3449
3450     if (CMOVTrue && CMOVFalse) {
3451       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3452       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3453
3454       SDValue True;
3455       SDValue False;
3456       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3457         True = SelectTrue;
3458         False = SelectFalse;
3459       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3460         True = SelectFalse;
3461         False = SelectTrue;
3462       }
3463
3464       if (True.getNode() && False.getNode()) {
3465         EVT VT = Op.getValueType();
3466         SDValue ARMcc = Cond.getOperand(2);
3467         SDValue CCR = Cond.getOperand(3);
3468         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3469         assert(True.getValueType() == VT);
3470         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3471       }
3472     }
3473   }
3474
3475   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3476   // undefined bits before doing a full-word comparison with zero.
3477   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3478                      DAG.getConstant(1, Cond.getValueType()));
3479
3480   return DAG.getSelectCC(dl, Cond,
3481                          DAG.getConstant(0, Cond.getValueType()),
3482                          SelectTrue, SelectFalse, ISD::SETNE);
3483 }
3484
3485 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3486   if (CC == ISD::SETNE)
3487     return ISD::SETEQ;
3488   return ISD::getSetCCInverse(CC, true);
3489 }
3490
3491 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3492                                  bool &swpCmpOps, bool &swpVselOps) {
3493   // Start by selecting the GE condition code for opcodes that return true for
3494   // 'equality'
3495   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3496       CC == ISD::SETULE)
3497     CondCode = ARMCC::GE;
3498
3499   // and GT for opcodes that return false for 'equality'.
3500   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3501            CC == ISD::SETULT)
3502     CondCode = ARMCC::GT;
3503
3504   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3505   // to swap the compare operands.
3506   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3507       CC == ISD::SETULT)
3508     swpCmpOps = true;
3509
3510   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3511   // If we have an unordered opcode, we need to swap the operands to the VSEL
3512   // instruction (effectively negating the condition).
3513   //
3514   // This also has the effect of swapping which one of 'less' or 'greater'
3515   // returns true, so we also swap the compare operands. It also switches
3516   // whether we return true for 'equality', so we compensate by picking the
3517   // opposite condition code to our original choice.
3518   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3519       CC == ISD::SETUGT) {
3520     swpCmpOps = !swpCmpOps;
3521     swpVselOps = !swpVselOps;
3522     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3523   }
3524
3525   // 'ordered' is 'anything but unordered', so use the VS condition code and
3526   // swap the VSEL operands.
3527   if (CC == ISD::SETO) {
3528     CondCode = ARMCC::VS;
3529     swpVselOps = true;
3530   }
3531
3532   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3533   // code and swap the VSEL operands.
3534   if (CC == ISD::SETUNE) {
3535     CondCode = ARMCC::EQ;
3536     swpVselOps = true;
3537   }
3538 }
3539
3540 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3541                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3542                                    SDValue Cmp, SelectionDAG &DAG) const {
3543   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3544     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3545                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3546     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3547                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3548
3549     SDValue TrueLow = TrueVal.getValue(0);
3550     SDValue TrueHigh = TrueVal.getValue(1);
3551     SDValue FalseLow = FalseVal.getValue(0);
3552     SDValue FalseHigh = FalseVal.getValue(1);
3553
3554     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3555                               ARMcc, CCR, Cmp);
3556     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3557                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3558
3559     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3560   } else {
3561     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3562                        Cmp);
3563   }
3564 }
3565
3566 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3567   EVT VT = Op.getValueType();
3568   SDValue LHS = Op.getOperand(0);
3569   SDValue RHS = Op.getOperand(1);
3570   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3571   SDValue TrueVal = Op.getOperand(2);
3572   SDValue FalseVal = Op.getOperand(3);
3573   SDLoc dl(Op);
3574
3575   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3576     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3577                                                     dl);
3578
3579     // If softenSetCCOperands only returned one value, we should compare it to
3580     // zero.
3581     if (!RHS.getNode()) {
3582       RHS = DAG.getConstant(0, LHS.getValueType());
3583       CC = ISD::SETNE;
3584     }
3585   }
3586
3587   if (LHS.getValueType() == MVT::i32) {
3588     // Try to generate VSEL on ARMv8.
3589     // The VSEL instruction can't use all the usual ARM condition
3590     // codes: it only has two bits to select the condition code, so it's
3591     // constrained to use only GE, GT, VS and EQ.
3592     //
3593     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3594     // swap the operands of the previous compare instruction (effectively
3595     // inverting the compare condition, swapping 'less' and 'greater') and
3596     // sometimes need to swap the operands to the VSEL (which inverts the
3597     // condition in the sense of firing whenever the previous condition didn't)
3598     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3599                                     TrueVal.getValueType() == MVT::f64)) {
3600       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3601       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3602           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3603         CC = getInverseCCForVSEL(CC);
3604         std::swap(TrueVal, FalseVal);
3605       }
3606     }
3607
3608     SDValue ARMcc;
3609     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3610     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3611     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3612   }
3613
3614   ARMCC::CondCodes CondCode, CondCode2;
3615   FPCCToARMCC(CC, CondCode, CondCode2);
3616
3617   // Try to generate VSEL on ARMv8.
3618   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3619                                   TrueVal.getValueType() == MVT::f64)) {
3620     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3621     // same operands, as follows:
3622     //   c = fcmp [ogt, olt, ugt, ult] a, b
3623     //   select c, a, b
3624     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3625     // handled differently than the original code sequence.
3626     if (getTargetMachine().Options.UnsafeFPMath) {
3627       if (LHS == TrueVal && RHS == FalseVal) {
3628         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3629           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3630         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3631           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3632       } else if (LHS == FalseVal && RHS == TrueVal) {
3633         if (CC == ISD::SETOLT || CC == ISD::SETULT)
3634           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3635         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3636           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3637       }
3638     }
3639
3640     bool swpCmpOps = false;
3641     bool swpVselOps = false;
3642     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3643
3644     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3645         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3646       if (swpCmpOps)
3647         std::swap(LHS, RHS);
3648       if (swpVselOps)
3649         std::swap(TrueVal, FalseVal);
3650     }
3651   }
3652
3653   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3654   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3655   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3656   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3657   if (CondCode2 != ARMCC::AL) {
3658     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3659     // FIXME: Needs another CMP because flag can have but one use.
3660     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3661     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3662   }
3663   return Result;
3664 }
3665
3666 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3667 /// to morph to an integer compare sequence.
3668 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3669                            const ARMSubtarget *Subtarget) {
3670   SDNode *N = Op.getNode();
3671   if (!N->hasOneUse())
3672     // Otherwise it requires moving the value from fp to integer registers.
3673     return false;
3674   if (!N->getNumValues())
3675     return false;
3676   EVT VT = Op.getValueType();
3677   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3678     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3679     // vmrs are very slow, e.g. cortex-a8.
3680     return false;
3681
3682   if (isFloatingPointZero(Op)) {
3683     SeenZero = true;
3684     return true;
3685   }
3686   return ISD::isNormalLoad(N);
3687 }
3688
3689 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3690   if (isFloatingPointZero(Op))
3691     return DAG.getConstant(0, MVT::i32);
3692
3693   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3694     return DAG.getLoad(MVT::i32, SDLoc(Op),
3695                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3696                        Ld->isVolatile(), Ld->isNonTemporal(),
3697                        Ld->isInvariant(), Ld->getAlignment());
3698
3699   llvm_unreachable("Unknown VFP cmp argument!");
3700 }
3701
3702 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3703                            SDValue &RetVal1, SDValue &RetVal2) {
3704   if (isFloatingPointZero(Op)) {
3705     RetVal1 = DAG.getConstant(0, MVT::i32);
3706     RetVal2 = DAG.getConstant(0, MVT::i32);
3707     return;
3708   }
3709
3710   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3711     SDValue Ptr = Ld->getBasePtr();
3712     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3713                           Ld->getChain(), Ptr,
3714                           Ld->getPointerInfo(),
3715                           Ld->isVolatile(), Ld->isNonTemporal(),
3716                           Ld->isInvariant(), Ld->getAlignment());
3717
3718     EVT PtrType = Ptr.getValueType();
3719     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3720     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3721                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3722     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3723                           Ld->getChain(), NewPtr,
3724                           Ld->getPointerInfo().getWithOffset(4),
3725                           Ld->isVolatile(), Ld->isNonTemporal(),
3726                           Ld->isInvariant(), NewAlign);
3727     return;
3728   }
3729
3730   llvm_unreachable("Unknown VFP cmp argument!");
3731 }
3732
3733 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3734 /// f32 and even f64 comparisons to integer ones.
3735 SDValue
3736 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3737   SDValue Chain = Op.getOperand(0);
3738   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3739   SDValue LHS = Op.getOperand(2);
3740   SDValue RHS = Op.getOperand(3);
3741   SDValue Dest = Op.getOperand(4);
3742   SDLoc dl(Op);
3743
3744   bool LHSSeenZero = false;
3745   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3746   bool RHSSeenZero = false;
3747   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3748   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3749     // If unsafe fp math optimization is enabled and there are no other uses of
3750     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3751     // to an integer comparison.
3752     if (CC == ISD::SETOEQ)
3753       CC = ISD::SETEQ;
3754     else if (CC == ISD::SETUNE)
3755       CC = ISD::SETNE;
3756
3757     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3758     SDValue ARMcc;
3759     if (LHS.getValueType() == MVT::f32) {
3760       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3761                         bitcastf32Toi32(LHS, DAG), Mask);
3762       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3763                         bitcastf32Toi32(RHS, DAG), Mask);
3764       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3765       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3766       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3767                          Chain, Dest, ARMcc, CCR, Cmp);
3768     }
3769
3770     SDValue LHS1, LHS2;
3771     SDValue RHS1, RHS2;
3772     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3773     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3774     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3775     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3776     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3777     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3778     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3779     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3780     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3781   }
3782
3783   return SDValue();
3784 }
3785
3786 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3787   SDValue Chain = Op.getOperand(0);
3788   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3789   SDValue LHS = Op.getOperand(2);
3790   SDValue RHS = Op.getOperand(3);
3791   SDValue Dest = Op.getOperand(4);
3792   SDLoc dl(Op);
3793
3794   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3795     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3796                                                     dl);
3797
3798     // If softenSetCCOperands only returned one value, we should compare it to
3799     // zero.
3800     if (!RHS.getNode()) {
3801       RHS = DAG.getConstant(0, LHS.getValueType());
3802       CC = ISD::SETNE;
3803     }
3804   }
3805
3806   if (LHS.getValueType() == MVT::i32) {
3807     SDValue ARMcc;
3808     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811                        Chain, Dest, ARMcc, CCR, Cmp);
3812   }
3813
3814   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3815
3816   if (getTargetMachine().Options.UnsafeFPMath &&
3817       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3818        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3819     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3820     if (Result.getNode())
3821       return Result;
3822   }
3823
3824   ARMCC::CondCodes CondCode, CondCode2;
3825   FPCCToARMCC(CC, CondCode, CondCode2);
3826
3827   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3828   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3829   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3830   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3831   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3832   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3833   if (CondCode2 != ARMCC::AL) {
3834     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3835     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3836     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3837   }
3838   return Res;
3839 }
3840
3841 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3842   SDValue Chain = Op.getOperand(0);
3843   SDValue Table = Op.getOperand(1);
3844   SDValue Index = Op.getOperand(2);
3845   SDLoc dl(Op);
3846
3847   EVT PTy = getPointerTy();
3848   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3849   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3850   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3851   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3852   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3853   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3854   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3855   if (Subtarget->isThumb2()) {
3856     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3857     // which does another jump to the destination. This also makes it easier
3858     // to translate it to TBB / TBH later.
3859     // FIXME: This might not work if the function is extremely large.
3860     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3861                        Addr, Op.getOperand(2), JTI, UId);
3862   }
3863   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3864     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3865                        MachinePointerInfo::getJumpTable(),
3866                        false, false, false, 0);
3867     Chain = Addr.getValue(1);
3868     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3869     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3870   } else {
3871     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3872                        MachinePointerInfo::getJumpTable(),
3873                        false, false, false, 0);
3874     Chain = Addr.getValue(1);
3875     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3876   }
3877 }
3878
3879 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3880   EVT VT = Op.getValueType();
3881   SDLoc dl(Op);
3882
3883   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3884     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3885       return Op;
3886     return DAG.UnrollVectorOp(Op.getNode());
3887   }
3888
3889   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3890          "Invalid type for custom lowering!");
3891   if (VT != MVT::v4i16)
3892     return DAG.UnrollVectorOp(Op.getNode());
3893
3894   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3895   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3896 }
3897
3898 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3899   EVT VT = Op.getValueType();
3900   if (VT.isVector())
3901     return LowerVectorFP_TO_INT(Op, DAG);
3902
3903   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3904     RTLIB::Libcall LC;
3905     if (Op.getOpcode() == ISD::FP_TO_SINT)
3906       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3907                               Op.getValueType());
3908     else
3909       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3910                               Op.getValueType());
3911     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3912                        /*isSigned*/ false, SDLoc(Op)).first;
3913   }
3914
3915   SDLoc dl(Op);
3916   unsigned Opc;
3917
3918   switch (Op.getOpcode()) {
3919   default: llvm_unreachable("Invalid opcode!");
3920   case ISD::FP_TO_SINT:
3921     Opc = ARMISD::FTOSI;
3922     break;
3923   case ISD::FP_TO_UINT:
3924     Opc = ARMISD::FTOUI;
3925     break;
3926   }
3927   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3928   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3929 }
3930
3931 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3932   EVT VT = Op.getValueType();
3933   SDLoc dl(Op);
3934
3935   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3936     if (VT.getVectorElementType() == MVT::f32)
3937       return Op;
3938     return DAG.UnrollVectorOp(Op.getNode());
3939   }
3940
3941   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3942          "Invalid type for custom lowering!");
3943   if (VT != MVT::v4f32)
3944     return DAG.UnrollVectorOp(Op.getNode());
3945
3946   unsigned CastOpc;
3947   unsigned Opc;
3948   switch (Op.getOpcode()) {
3949   default: llvm_unreachable("Invalid opcode!");
3950   case ISD::SINT_TO_FP:
3951     CastOpc = ISD::SIGN_EXTEND;
3952     Opc = ISD::SINT_TO_FP;
3953     break;
3954   case ISD::UINT_TO_FP:
3955     CastOpc = ISD::ZERO_EXTEND;
3956     Opc = ISD::UINT_TO_FP;
3957     break;
3958   }
3959
3960   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3961   return DAG.getNode(Opc, dl, VT, Op);
3962 }
3963
3964 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3965   EVT VT = Op.getValueType();
3966   if (VT.isVector())
3967     return LowerVectorINT_TO_FP(Op, DAG);
3968
3969   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3970     RTLIB::Libcall LC;
3971     if (Op.getOpcode() == ISD::SINT_TO_FP)
3972       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3973                               Op.getValueType());
3974     else
3975       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3976                               Op.getValueType());
3977     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3978                        /*isSigned*/ false, SDLoc(Op)).first;
3979   }
3980
3981   SDLoc dl(Op);
3982   unsigned Opc;
3983
3984   switch (Op.getOpcode()) {
3985   default: llvm_unreachable("Invalid opcode!");
3986   case ISD::SINT_TO_FP:
3987     Opc = ARMISD::SITOF;
3988     break;
3989   case ISD::UINT_TO_FP:
3990     Opc = ARMISD::UITOF;
3991     break;
3992   }
3993
3994   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3995   return DAG.getNode(Opc, dl, VT, Op);
3996 }
3997
3998 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3999   // Implement fcopysign with a fabs and a conditional fneg.
4000   SDValue Tmp0 = Op.getOperand(0);
4001   SDValue Tmp1 = Op.getOperand(1);
4002   SDLoc dl(Op);
4003   EVT VT = Op.getValueType();
4004   EVT SrcVT = Tmp1.getValueType();
4005   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4006     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4007   bool UseNEON = !InGPR && Subtarget->hasNEON();
4008
4009   if (UseNEON) {
4010     // Use VBSL to copy the sign bit.
4011     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4012     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4013                                DAG.getTargetConstant(EncodedVal, MVT::i32));
4014     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4015     if (VT == MVT::f64)
4016       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4017                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4018                          DAG.getConstant(32, MVT::i32));
4019     else /*if (VT == MVT::f32)*/
4020       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4021     if (SrcVT == MVT::f32) {
4022       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4023       if (VT == MVT::f64)
4024         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4025                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4026                            DAG.getConstant(32, MVT::i32));
4027     } else if (VT == MVT::f32)
4028       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4029                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4030                          DAG.getConstant(32, MVT::i32));
4031     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4032     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4033
4034     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4035                                             MVT::i32);
4036     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4037     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4038                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4039
4040     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4041                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4042                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4043     if (VT == MVT::f32) {
4044       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4045       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4046                         DAG.getConstant(0, MVT::i32));
4047     } else {
4048       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4049     }
4050
4051     return Res;
4052   }
4053
4054   // Bitcast operand 1 to i32.
4055   if (SrcVT == MVT::f64)
4056     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4057                        Tmp1).getValue(1);
4058   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4059
4060   // Or in the signbit with integer operations.
4061   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4062   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4063   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4064   if (VT == MVT::f32) {
4065     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4066                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4067     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4068                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4069   }
4070
4071   // f64: Or the high part with signbit and then combine two parts.
4072   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4073                      Tmp0);
4074   SDValue Lo = Tmp0.getValue(0);
4075   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4076   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4077   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4078 }
4079
4080 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4081   MachineFunction &MF = DAG.getMachineFunction();
4082   MachineFrameInfo *MFI = MF.getFrameInfo();
4083   MFI->setReturnAddressIsTaken(true);
4084
4085   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4086     return SDValue();
4087
4088   EVT VT = Op.getValueType();
4089   SDLoc dl(Op);
4090   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4091   if (Depth) {
4092     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4093     SDValue Offset = DAG.getConstant(4, MVT::i32);
4094     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4095                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4096                        MachinePointerInfo(), false, false, false, 0);
4097   }
4098
4099   // Return LR, which contains the return address. Mark it an implicit live-in.
4100   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4101   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4102 }
4103
4104 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4105   const ARMBaseRegisterInfo &ARI =
4106     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4107   MachineFunction &MF = DAG.getMachineFunction();
4108   MachineFrameInfo *MFI = MF.getFrameInfo();
4109   MFI->setFrameAddressIsTaken(true);
4110
4111   EVT VT = Op.getValueType();
4112   SDLoc dl(Op);  // FIXME probably not meaningful
4113   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4114   unsigned FrameReg = ARI.getFrameRegister(MF);
4115   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4116   while (Depth--)
4117     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4118                             MachinePointerInfo(),
4119                             false, false, false, 0);
4120   return FrameAddr;
4121 }
4122
4123 // FIXME? Maybe this could be a TableGen attribute on some registers and
4124 // this table could be generated automatically from RegInfo.
4125 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4126                                               EVT VT) const {
4127   unsigned Reg = StringSwitch<unsigned>(RegName)
4128                        .Case("sp", ARM::SP)
4129                        .Default(0);
4130   if (Reg)
4131     return Reg;
4132   report_fatal_error("Invalid register name global variable");
4133 }
4134
4135 /// ExpandBITCAST - If the target supports VFP, this function is called to
4136 /// expand a bit convert where either the source or destination type is i64 to
4137 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4138 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4139 /// vectors), since the legalizer won't know what to do with that.
4140 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4142   SDLoc dl(N);
4143   SDValue Op = N->getOperand(0);
4144
4145   // This function is only supposed to be called for i64 types, either as the
4146   // source or destination of the bit convert.
4147   EVT SrcVT = Op.getValueType();
4148   EVT DstVT = N->getValueType(0);
4149   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4150          "ExpandBITCAST called for non-i64 type");
4151
4152   // Turn i64->f64 into VMOVDRR.
4153   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4154     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4155                              DAG.getConstant(0, MVT::i32));
4156     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4157                              DAG.getConstant(1, MVT::i32));
4158     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4159                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4160   }
4161
4162   // Turn f64->i64 into VMOVRRD.
4163   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4164     SDValue Cvt;
4165     if (TLI.isBigEndian() && SrcVT.isVector() &&
4166         SrcVT.getVectorNumElements() > 1)
4167       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4168                         DAG.getVTList(MVT::i32, MVT::i32),
4169                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4170     else
4171       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4172                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4173     // Merge the pieces into a single i64 value.
4174     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4175   }
4176
4177   return SDValue();
4178 }
4179
4180 /// getZeroVector - Returns a vector of specified type with all zero elements.
4181 /// Zero vectors are used to represent vector negation and in those cases
4182 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4183 /// not support i64 elements, so sometimes the zero vectors will need to be
4184 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4185 /// zero vector.
4186 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4187   assert(VT.isVector() && "Expected a vector type");
4188   // The canonical modified immediate encoding of a zero vector is....0!
4189   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4190   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4191   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4192   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4193 }
4194
4195 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4196 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4197 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4198                                                 SelectionDAG &DAG) const {
4199   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4200   EVT VT = Op.getValueType();
4201   unsigned VTBits = VT.getSizeInBits();
4202   SDLoc dl(Op);
4203   SDValue ShOpLo = Op.getOperand(0);
4204   SDValue ShOpHi = Op.getOperand(1);
4205   SDValue ShAmt  = Op.getOperand(2);
4206   SDValue ARMcc;
4207   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4208
4209   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4210
4211   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4212                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4213   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4214   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4215                                    DAG.getConstant(VTBits, MVT::i32));
4216   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4217   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4218   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4219
4220   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4221   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4222                           ARMcc, DAG, dl);
4223   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4224   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4225                            CCR, Cmp);
4226
4227   SDValue Ops[2] = { Lo, Hi };
4228   return DAG.getMergeValues(Ops, dl);
4229 }
4230
4231 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4232 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4233 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4234                                                SelectionDAG &DAG) const {
4235   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4236   EVT VT = Op.getValueType();
4237   unsigned VTBits = VT.getSizeInBits();
4238   SDLoc dl(Op);
4239   SDValue ShOpLo = Op.getOperand(0);
4240   SDValue ShOpHi = Op.getOperand(1);
4241   SDValue ShAmt  = Op.getOperand(2);
4242   SDValue ARMcc;
4243
4244   assert(Op.getOpcode() == ISD::SHL_PARTS);
4245   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4247   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4248   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249                                    DAG.getConstant(VTBits, MVT::i32));
4250   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4251   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4252
4253   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4254   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4256                           ARMcc, DAG, dl);
4257   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4258   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4259                            CCR, Cmp);
4260
4261   SDValue Ops[2] = { Lo, Hi };
4262   return DAG.getMergeValues(Ops, dl);
4263 }
4264
4265 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4266                                             SelectionDAG &DAG) const {
4267   // The rounding mode is in bits 23:22 of the FPSCR.
4268   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4269   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4270   // so that the shift + and get folded into a bitfield extract.
4271   SDLoc dl(Op);
4272   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4273                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4274                                               MVT::i32));
4275   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4276                                   DAG.getConstant(1U << 22, MVT::i32));
4277   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4278                               DAG.getConstant(22, MVT::i32));
4279   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4280                      DAG.getConstant(3, MVT::i32));
4281 }
4282
4283 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4284                          const ARMSubtarget *ST) {
4285   EVT VT = N->getValueType(0);
4286   SDLoc dl(N);
4287
4288   if (!ST->hasV6T2Ops())
4289     return SDValue();
4290
4291   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4292   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4293 }
4294
4295 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4296 /// for each 16-bit element from operand, repeated.  The basic idea is to
4297 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4298 ///
4299 /// Trace for v4i16:
4300 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4301 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4302 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4303 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4304 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4305 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4306 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4307 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4308 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4309   EVT VT = N->getValueType(0);
4310   SDLoc DL(N);
4311
4312   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4313   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4314   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4315   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4316   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4317   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4318 }
4319
4320 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4321 /// bit-count for each 16-bit element from the operand.  We need slightly
4322 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4323 /// 64/128-bit registers.
4324 ///
4325 /// Trace for v4i16:
4326 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4327 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4328 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4329 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4330 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4331   EVT VT = N->getValueType(0);
4332   SDLoc DL(N);
4333
4334   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4335   if (VT.is64BitVector()) {
4336     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4337     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4338                        DAG.getIntPtrConstant(0));
4339   } else {
4340     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4341                                     BitCounts, DAG.getIntPtrConstant(0));
4342     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4343   }
4344 }
4345
4346 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4347 /// bit-count for each 32-bit element from the operand.  The idea here is
4348 /// to split the vector into 16-bit elements, leverage the 16-bit count
4349 /// routine, and then combine the results.
4350 ///
4351 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4352 /// input    = [v0    v1    ] (vi: 32-bit elements)
4353 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4354 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4355 /// vrev: N0 = [k1 k0 k3 k2 ]
4356 ///            [k0 k1 k2 k3 ]
4357 ///       N1 =+[k1 k0 k3 k2 ]
4358 ///            [k0 k2 k1 k3 ]
4359 ///       N2 =+[k1 k3 k0 k2 ]
4360 ///            [k0    k2    k1    k3    ]
4361 /// Extended =+[k1    k3    k0    k2    ]
4362 ///            [k0    k2    ]
4363 /// Extracted=+[k1    k3    ]
4364 ///
4365 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4366   EVT VT = N->getValueType(0);
4367   SDLoc DL(N);
4368
4369   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4370
4371   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4372   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4373   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4374   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4375   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4376
4377   if (VT.is64BitVector()) {
4378     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4379     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4380                        DAG.getIntPtrConstant(0));
4381   } else {
4382     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4383                                     DAG.getIntPtrConstant(0));
4384     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4385   }
4386 }
4387
4388 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4389                           const ARMSubtarget *ST) {
4390   EVT VT = N->getValueType(0);
4391
4392   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4393   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4394           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4395          "Unexpected type for custom ctpop lowering");
4396
4397   if (VT.getVectorElementType() == MVT::i32)
4398     return lowerCTPOP32BitElements(N, DAG);
4399   else
4400     return lowerCTPOP16BitElements(N, DAG);
4401 }
4402
4403 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4404                           const ARMSubtarget *ST) {
4405   EVT VT = N->getValueType(0);
4406   SDLoc dl(N);
4407
4408   if (!VT.isVector())
4409     return SDValue();
4410
4411   // Lower vector shifts on NEON to use VSHL.
4412   assert(ST->hasNEON() && "unexpected vector shift");
4413
4414   // Left shifts translate directly to the vshiftu intrinsic.
4415   if (N->getOpcode() == ISD::SHL)
4416     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4417                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4418                        N->getOperand(0), N->getOperand(1));
4419
4420   assert((N->getOpcode() == ISD::SRA ||
4421           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4422
4423   // NEON uses the same intrinsics for both left and right shifts.  For
4424   // right shifts, the shift amounts are negative, so negate the vector of
4425   // shift amounts.
4426   EVT ShiftVT = N->getOperand(1).getValueType();
4427   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4428                                      getZeroVector(ShiftVT, DAG, dl),
4429                                      N->getOperand(1));
4430   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4431                              Intrinsic::arm_neon_vshifts :
4432                              Intrinsic::arm_neon_vshiftu);
4433   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4434                      DAG.getConstant(vshiftInt, MVT::i32),
4435                      N->getOperand(0), NegatedCount);
4436 }
4437
4438 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4439                                 const ARMSubtarget *ST) {
4440   EVT VT = N->getValueType(0);
4441   SDLoc dl(N);
4442
4443   // We can get here for a node like i32 = ISD::SHL i32, i64
4444   if (VT != MVT::i64)
4445     return SDValue();
4446
4447   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4448          "Unknown shift to lower!");
4449
4450   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4451   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4452       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4453     return SDValue();
4454
4455   // If we are in thumb mode, we don't have RRX.
4456   if (ST->isThumb1Only()) return SDValue();
4457
4458   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4459   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4460                            DAG.getConstant(0, MVT::i32));
4461   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4462                            DAG.getConstant(1, MVT::i32));
4463
4464   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4465   // captures the result into a carry flag.
4466   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4467   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4468
4469   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4470   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4471
4472   // Merge the pieces into a single i64 value.
4473  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4474 }
4475
4476 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4477   SDValue TmpOp0, TmpOp1;
4478   bool Invert = false;
4479   bool Swap = false;
4480   unsigned Opc = 0;
4481
4482   SDValue Op0 = Op.getOperand(0);
4483   SDValue Op1 = Op.getOperand(1);
4484   SDValue CC = Op.getOperand(2);
4485   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4486   EVT VT = Op.getValueType();
4487   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4488   SDLoc dl(Op);
4489
4490   if (Op1.getValueType().isFloatingPoint()) {
4491     switch (SetCCOpcode) {
4492     default: llvm_unreachable("Illegal FP comparison");
4493     case ISD::SETUNE:
4494     case ISD::SETNE:  Invert = true; // Fallthrough
4495     case ISD::SETOEQ:
4496     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4497     case ISD::SETOLT:
4498     case ISD::SETLT: Swap = true; // Fallthrough
4499     case ISD::SETOGT:
4500     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4501     case ISD::SETOLE:
4502     case ISD::SETLE:  Swap = true; // Fallthrough
4503     case ISD::SETOGE:
4504     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4505     case ISD::SETUGE: Swap = true; // Fallthrough
4506     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4507     case ISD::SETUGT: Swap = true; // Fallthrough
4508     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4509     case ISD::SETUEQ: Invert = true; // Fallthrough
4510     case ISD::SETONE:
4511       // Expand this to (OLT | OGT).
4512       TmpOp0 = Op0;
4513       TmpOp1 = Op1;
4514       Opc = ISD::OR;
4515       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4516       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4517       break;
4518     case ISD::SETUO: Invert = true; // Fallthrough
4519     case ISD::SETO:
4520       // Expand this to (OLT | OGE).
4521       TmpOp0 = Op0;
4522       TmpOp1 = Op1;
4523       Opc = ISD::OR;
4524       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4525       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4526       break;
4527     }
4528   } else {
4529     // Integer comparisons.
4530     switch (SetCCOpcode) {
4531     default: llvm_unreachable("Illegal integer comparison");
4532     case ISD::SETNE:  Invert = true;
4533     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4534     case ISD::SETLT:  Swap = true;
4535     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4536     case ISD::SETLE:  Swap = true;
4537     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4538     case ISD::SETULT: Swap = true;
4539     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4540     case ISD::SETULE: Swap = true;
4541     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4542     }
4543
4544     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4545     if (Opc == ARMISD::VCEQ) {
4546
4547       SDValue AndOp;
4548       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4549         AndOp = Op0;
4550       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4551         AndOp = Op1;
4552
4553       // Ignore bitconvert.
4554       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4555         AndOp = AndOp.getOperand(0);
4556
4557       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4558         Opc = ARMISD::VTST;
4559         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4560         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4561         Invert = !Invert;
4562       }
4563     }
4564   }
4565
4566   if (Swap)
4567     std::swap(Op0, Op1);
4568
4569   // If one of the operands is a constant vector zero, attempt to fold the
4570   // comparison to a specialized compare-against-zero form.
4571   SDValue SingleOp;
4572   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4573     SingleOp = Op0;
4574   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4575     if (Opc == ARMISD::VCGE)
4576       Opc = ARMISD::VCLEZ;
4577     else if (Opc == ARMISD::VCGT)
4578       Opc = ARMISD::VCLTZ;
4579     SingleOp = Op1;
4580   }
4581
4582   SDValue Result;
4583   if (SingleOp.getNode()) {
4584     switch (Opc) {
4585     case ARMISD::VCEQ:
4586       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4587     case ARMISD::VCGE:
4588       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4589     case ARMISD::VCLEZ:
4590       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4591     case ARMISD::VCGT:
4592       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4593     case ARMISD::VCLTZ:
4594       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4595     default:
4596       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4597     }
4598   } else {
4599      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4600   }
4601
4602   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4603
4604   if (Invert)
4605     Result = DAG.getNOT(dl, Result, VT);
4606
4607   return Result;
4608 }
4609
4610 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4611 /// valid vector constant for a NEON instruction with a "modified immediate"
4612 /// operand (e.g., VMOV).  If so, return the encoded value.
4613 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4614                                  unsigned SplatBitSize, SelectionDAG &DAG,
4615                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4616   unsigned OpCmode, Imm;
4617
4618   // SplatBitSize is set to the smallest size that splats the vector, so a
4619   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4620   // immediate instructions others than VMOV do not support the 8-bit encoding
4621   // of a zero vector, and the default encoding of zero is supposed to be the
4622   // 32-bit version.
4623   if (SplatBits == 0)
4624     SplatBitSize = 32;
4625
4626   switch (SplatBitSize) {
4627   case 8:
4628     if (type != VMOVModImm)
4629       return SDValue();
4630     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4631     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4632     OpCmode = 0xe;
4633     Imm = SplatBits;
4634     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4635     break;
4636
4637   case 16:
4638     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4639     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4640     if ((SplatBits & ~0xff) == 0) {
4641       // Value = 0x00nn: Op=x, Cmode=100x.
4642       OpCmode = 0x8;
4643       Imm = SplatBits;
4644       break;
4645     }
4646     if ((SplatBits & ~0xff00) == 0) {
4647       // Value = 0xnn00: Op=x, Cmode=101x.
4648       OpCmode = 0xa;
4649       Imm = SplatBits >> 8;
4650       break;
4651     }
4652     return SDValue();
4653
4654   case 32:
4655     // NEON's 32-bit VMOV supports splat values where:
4656     // * only one byte is nonzero, or
4657     // * the least significant byte is 0xff and the second byte is nonzero, or
4658     // * the least significant 2 bytes are 0xff and the third is nonzero.
4659     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4660     if ((SplatBits & ~0xff) == 0) {
4661       // Value = 0x000000nn: Op=x, Cmode=000x.
4662       OpCmode = 0;
4663       Imm = SplatBits;
4664       break;
4665     }
4666     if ((SplatBits & ~0xff00) == 0) {
4667       // Value = 0x0000nn00: Op=x, Cmode=001x.
4668       OpCmode = 0x2;
4669       Imm = SplatBits >> 8;
4670       break;
4671     }
4672     if ((SplatBits & ~0xff0000) == 0) {
4673       // Value = 0x00nn0000: Op=x, Cmode=010x.
4674       OpCmode = 0x4;
4675       Imm = SplatBits >> 16;
4676       break;
4677     }
4678     if ((SplatBits & ~0xff000000) == 0) {
4679       // Value = 0xnn000000: Op=x, Cmode=011x.
4680       OpCmode = 0x6;
4681       Imm = SplatBits >> 24;
4682       break;
4683     }
4684
4685     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4686     if (type == OtherModImm) return SDValue();
4687
4688     if ((SplatBits & ~0xffff) == 0 &&
4689         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4690       // Value = 0x0000nnff: Op=x, Cmode=1100.
4691       OpCmode = 0xc;
4692       Imm = SplatBits >> 8;
4693       break;
4694     }
4695
4696     if ((SplatBits & ~0xffffff) == 0 &&
4697         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4698       // Value = 0x00nnffff: Op=x, Cmode=1101.
4699       OpCmode = 0xd;
4700       Imm = SplatBits >> 16;
4701       break;
4702     }
4703
4704     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4705     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4706     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4707     // and fall through here to test for a valid 64-bit splat.  But, then the
4708     // caller would also need to check and handle the change in size.
4709     return SDValue();
4710
4711   case 64: {
4712     if (type != VMOVModImm)
4713       return SDValue();
4714     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4715     uint64_t BitMask = 0xff;
4716     uint64_t Val = 0;
4717     unsigned ImmMask = 1;
4718     Imm = 0;
4719     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4720       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4721         Val |= BitMask;
4722         Imm |= ImmMask;
4723       } else if ((SplatBits & BitMask) != 0) {
4724         return SDValue();
4725       }
4726       BitMask <<= 8;
4727       ImmMask <<= 1;
4728     }
4729
4730     if (DAG.getTargetLoweringInfo().isBigEndian())
4731       // swap higher and lower 32 bit word
4732       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4733
4734     // Op=1, Cmode=1110.
4735     OpCmode = 0x1e;
4736     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4737     break;
4738   }
4739
4740   default:
4741     llvm_unreachable("unexpected size for isNEONModifiedImm");
4742   }
4743
4744   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4745   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4746 }
4747
4748 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4749                                            const ARMSubtarget *ST) const {
4750   if (!ST->hasVFP3())
4751     return SDValue();
4752
4753   bool IsDouble = Op.getValueType() == MVT::f64;
4754   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4755
4756   // Use the default (constant pool) lowering for double constants when we have
4757   // an SP-only FPU
4758   if (IsDouble && Subtarget->isFPOnlySP())
4759     return SDValue();
4760
4761   // Try splatting with a VMOV.f32...
4762   APFloat FPVal = CFP->getValueAPF();
4763   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4764
4765   if (ImmVal != -1) {
4766     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4767       // We have code in place to select a valid ConstantFP already, no need to
4768       // do any mangling.
4769       return Op;
4770     }
4771
4772     // It's a float and we are trying to use NEON operations where
4773     // possible. Lower it to a splat followed by an extract.
4774     SDLoc DL(Op);
4775     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4776     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4777                                       NewVal);
4778     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4779                        DAG.getConstant(0, MVT::i32));
4780   }
4781
4782   // The rest of our options are NEON only, make sure that's allowed before
4783   // proceeding..
4784   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4785     return SDValue();
4786
4787   EVT VMovVT;
4788   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4789
4790   // It wouldn't really be worth bothering for doubles except for one very
4791   // important value, which does happen to match: 0.0. So make sure we don't do
4792   // anything stupid.
4793   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4794     return SDValue();
4795
4796   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4797   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4798                                      false, VMOVModImm);
4799   if (NewVal != SDValue()) {
4800     SDLoc DL(Op);
4801     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4802                                       NewVal);
4803     if (IsDouble)
4804       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4805
4806     // It's a float: cast and extract a vector element.
4807     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4808                                        VecConstant);
4809     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4810                        DAG.getConstant(0, MVT::i32));
4811   }
4812
4813   // Finally, try a VMVN.i32
4814   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4815                              false, VMVNModImm);
4816   if (NewVal != SDValue()) {
4817     SDLoc DL(Op);
4818     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4819
4820     if (IsDouble)
4821       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4822
4823     // It's a float: cast and extract a vector element.
4824     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4825                                        VecConstant);
4826     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4827                        DAG.getConstant(0, MVT::i32));
4828   }
4829
4830   return SDValue();
4831 }
4832
4833 // check if an VEXT instruction can handle the shuffle mask when the
4834 // vector sources of the shuffle are the same.
4835 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4836   unsigned NumElts = VT.getVectorNumElements();
4837
4838   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4839   if (M[0] < 0)
4840     return false;
4841
4842   Imm = M[0];
4843
4844   // If this is a VEXT shuffle, the immediate value is the index of the first
4845   // element.  The other shuffle indices must be the successive elements after
4846   // the first one.
4847   unsigned ExpectedElt = Imm;
4848   for (unsigned i = 1; i < NumElts; ++i) {
4849     // Increment the expected index.  If it wraps around, just follow it
4850     // back to index zero and keep going.
4851     ++ExpectedElt;
4852     if (ExpectedElt == NumElts)
4853       ExpectedElt = 0;
4854
4855     if (M[i] < 0) continue; // ignore UNDEF indices
4856     if (ExpectedElt != static_cast<unsigned>(M[i]))
4857       return false;
4858   }
4859
4860   return true;
4861 }
4862
4863
4864 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4865                        bool &ReverseVEXT, unsigned &Imm) {
4866   unsigned NumElts = VT.getVectorNumElements();
4867   ReverseVEXT = false;
4868
4869   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4870   if (M[0] < 0)
4871     return false;
4872
4873   Imm = M[0];
4874
4875   // If this is a VEXT shuffle, the immediate value is the index of the first
4876   // element.  The other shuffle indices must be the successive elements after
4877   // the first one.
4878   unsigned ExpectedElt = Imm;
4879   for (unsigned i = 1; i < NumElts; ++i) {
4880     // Increment the expected index.  If it wraps around, it may still be
4881     // a VEXT but the source vectors must be swapped.
4882     ExpectedElt += 1;
4883     if (ExpectedElt == NumElts * 2) {
4884       ExpectedElt = 0;
4885       ReverseVEXT = true;
4886     }
4887
4888     if (M[i] < 0) continue; // ignore UNDEF indices
4889     if (ExpectedElt != static_cast<unsigned>(M[i]))
4890       return false;
4891   }
4892
4893   // Adjust the index value if the source operands will be swapped.
4894   if (ReverseVEXT)
4895     Imm -= NumElts;
4896
4897   return true;
4898 }
4899
4900 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4901 /// instruction with the specified blocksize.  (The order of the elements
4902 /// within each block of the vector is reversed.)
4903 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4904   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4905          "Only possible block sizes for VREV are: 16, 32, 64");
4906
4907   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4908   if (EltSz == 64)
4909     return false;
4910
4911   unsigned NumElts = VT.getVectorNumElements();
4912   unsigned BlockElts = M[0] + 1;
4913   // If the first shuffle index is UNDEF, be optimistic.
4914   if (M[0] < 0)
4915     BlockElts = BlockSize / EltSz;
4916
4917   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4918     return false;
4919
4920   for (unsigned i = 0; i < NumElts; ++i) {
4921     if (M[i] < 0) continue; // ignore UNDEF indices
4922     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4923       return false;
4924   }
4925
4926   return true;
4927 }
4928
4929 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4930   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4931   // range, then 0 is placed into the resulting vector. So pretty much any mask
4932   // of 8 elements can work here.
4933   return VT == MVT::v8i8 && M.size() == 8;
4934 }
4935
4936 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4937   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4938   if (EltSz == 64)
4939     return false;
4940
4941   unsigned NumElts = VT.getVectorNumElements();
4942   WhichResult = (M[0] == 0 ? 0 : 1);
4943   for (unsigned i = 0; i < NumElts; i += 2) {
4944     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4945         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4946       return false;
4947   }
4948   return true;
4949 }
4950
4951 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4952 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4953 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4954 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4955   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4956   if (EltSz == 64)
4957     return false;
4958
4959   unsigned NumElts = VT.getVectorNumElements();
4960   WhichResult = (M[0] == 0 ? 0 : 1);
4961   for (unsigned i = 0; i < NumElts; i += 2) {
4962     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4963         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4964       return false;
4965   }
4966   return true;
4967 }
4968
4969 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4970   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4971   if (EltSz == 64)
4972     return false;
4973
4974   unsigned NumElts = VT.getVectorNumElements();
4975   WhichResult = (M[0] == 0 ? 0 : 1);
4976   for (unsigned i = 0; i != NumElts; ++i) {
4977     if (M[i] < 0) continue; // ignore UNDEF indices
4978     if ((unsigned) M[i] != 2 * i + WhichResult)
4979       return false;
4980   }
4981
4982   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4983   if (VT.is64BitVector() && EltSz == 32)
4984     return false;
4985
4986   return true;
4987 }
4988
4989 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4990 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4991 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4992 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4993   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4994   if (EltSz == 64)
4995     return false;
4996
4997   unsigned Half = VT.getVectorNumElements() / 2;
4998   WhichResult = (M[0] == 0 ? 0 : 1);
4999   for (unsigned j = 0; j != 2; ++j) {
5000     unsigned Idx = WhichResult;
5001     for (unsigned i = 0; i != Half; ++i) {
5002       int MIdx = M[i + j * Half];
5003       if (MIdx >= 0 && (unsigned) MIdx != Idx)
5004         return false;
5005       Idx += 2;
5006     }
5007   }
5008
5009   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5010   if (VT.is64BitVector() && EltSz == 32)
5011     return false;
5012
5013   return true;
5014 }
5015
5016 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5017   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5018   if (EltSz == 64)
5019     return false;
5020
5021   unsigned NumElts = VT.getVectorNumElements();
5022   WhichResult = (M[0] == 0 ? 0 : 1);
5023   unsigned Idx = WhichResult * NumElts / 2;
5024   for (unsigned i = 0; i != NumElts; i += 2) {
5025     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5026         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5027       return false;
5028     Idx += 1;
5029   }
5030
5031   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5032   if (VT.is64BitVector() && EltSz == 32)
5033     return false;
5034
5035   return true;
5036 }
5037
5038 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5039 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5040 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5041 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5042   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5043   if (EltSz == 64)
5044     return false;
5045
5046   unsigned NumElts = VT.getVectorNumElements();
5047   WhichResult = (M[0] == 0 ? 0 : 1);
5048   unsigned Idx = WhichResult * NumElts / 2;
5049   for (unsigned i = 0; i != NumElts; i += 2) {
5050     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5051         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5052       return false;
5053     Idx += 1;
5054   }
5055
5056   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5057   if (VT.is64BitVector() && EltSz == 32)
5058     return false;
5059
5060   return true;
5061 }
5062
5063 /// \return true if this is a reverse operation on an vector.
5064 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5065   unsigned NumElts = VT.getVectorNumElements();
5066   // Make sure the mask has the right size.
5067   if (NumElts != M.size())
5068       return false;
5069
5070   // Look for <15, ..., 3, -1, 1, 0>.
5071   for (unsigned i = 0; i != NumElts; ++i)
5072     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5073       return false;
5074
5075   return true;
5076 }
5077
5078 // If N is an integer constant that can be moved into a register in one
5079 // instruction, return an SDValue of such a constant (will become a MOV
5080 // instruction).  Otherwise return null.
5081 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5082                                      const ARMSubtarget *ST, SDLoc dl) {
5083   uint64_t Val;
5084   if (!isa<ConstantSDNode>(N))
5085     return SDValue();
5086   Val = cast<ConstantSDNode>(N)->getZExtValue();
5087
5088   if (ST->isThumb1Only()) {
5089     if (Val <= 255 || ~Val <= 255)
5090       return DAG.getConstant(Val, MVT::i32);
5091   } else {
5092     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5093       return DAG.getConstant(Val, MVT::i32);
5094   }
5095   return SDValue();
5096 }
5097
5098 // If this is a case we can't handle, return null and let the default
5099 // expansion code take care of it.
5100 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5101                                              const ARMSubtarget *ST) const {
5102   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5103   SDLoc dl(Op);
5104   EVT VT = Op.getValueType();
5105
5106   APInt SplatBits, SplatUndef;
5107   unsigned SplatBitSize;
5108   bool HasAnyUndefs;
5109   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5110     if (SplatBitSize <= 64) {
5111       // Check if an immediate VMOV works.
5112       EVT VmovVT;
5113       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5114                                       SplatUndef.getZExtValue(), SplatBitSize,
5115                                       DAG, VmovVT, VT.is128BitVector(),
5116                                       VMOVModImm);
5117       if (Val.getNode()) {
5118         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5119         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5120       }
5121
5122       // Try an immediate VMVN.
5123       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5124       Val = isNEONModifiedImm(NegatedImm,
5125                                       SplatUndef.getZExtValue(), SplatBitSize,
5126                                       DAG, VmovVT, VT.is128BitVector(),
5127                                       VMVNModImm);
5128       if (Val.getNode()) {
5129         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5130         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5131       }
5132
5133       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5134       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5135         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5136         if (ImmVal != -1) {
5137           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5138           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5139         }
5140       }
5141     }
5142   }
5143
5144   // Scan through the operands to see if only one value is used.
5145   //
5146   // As an optimisation, even if more than one value is used it may be more
5147   // profitable to splat with one value then change some lanes.
5148   //
5149   // Heuristically we decide to do this if the vector has a "dominant" value,
5150   // defined as splatted to more than half of the lanes.
5151   unsigned NumElts = VT.getVectorNumElements();
5152   bool isOnlyLowElement = true;
5153   bool usesOnlyOneValue = true;
5154   bool hasDominantValue = false;
5155   bool isConstant = true;
5156
5157   // Map of the number of times a particular SDValue appears in the
5158   // element list.
5159   DenseMap<SDValue, unsigned> ValueCounts;
5160   SDValue Value;
5161   for (unsigned i = 0; i < NumElts; ++i) {
5162     SDValue V = Op.getOperand(i);
5163     if (V.getOpcode() == ISD::UNDEF)
5164       continue;
5165     if (i > 0)
5166       isOnlyLowElement = false;
5167     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5168       isConstant = false;
5169
5170     ValueCounts.insert(std::make_pair(V, 0));
5171     unsigned &Count = ValueCounts[V];
5172
5173     // Is this value dominant? (takes up more than half of the lanes)
5174     if (++Count > (NumElts / 2)) {
5175       hasDominantValue = true;
5176       Value = V;
5177     }
5178   }
5179   if (ValueCounts.size() != 1)
5180     usesOnlyOneValue = false;
5181   if (!Value.getNode() && ValueCounts.size() > 0)
5182     Value = ValueCounts.begin()->first;
5183
5184   if (ValueCounts.size() == 0)
5185     return DAG.getUNDEF(VT);
5186
5187   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5188   // Keep going if we are hitting this case.
5189   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5190     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5191
5192   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5193
5194   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5195   // i32 and try again.
5196   if (hasDominantValue && EltSize <= 32) {
5197     if (!isConstant) {
5198       SDValue N;
5199
5200       // If we are VDUPing a value that comes directly from a vector, that will
5201       // cause an unnecessary move to and from a GPR, where instead we could
5202       // just use VDUPLANE. We can only do this if the lane being extracted
5203       // is at a constant index, as the VDUP from lane instructions only have
5204       // constant-index forms.
5205       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5206           isa<ConstantSDNode>(Value->getOperand(1))) {
5207         // We need to create a new undef vector to use for the VDUPLANE if the
5208         // size of the vector from which we get the value is different than the
5209         // size of the vector that we need to create. We will insert the element
5210         // such that the register coalescer will remove unnecessary copies.
5211         if (VT != Value->getOperand(0).getValueType()) {
5212           ConstantSDNode *constIndex;
5213           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5214           assert(constIndex && "The index is not a constant!");
5215           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5216                              VT.getVectorNumElements();
5217           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5218                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5219                         Value, DAG.getConstant(index, MVT::i32)),
5220                            DAG.getConstant(index, MVT::i32));
5221         } else
5222           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5223                         Value->getOperand(0), Value->getOperand(1));
5224       } else
5225         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5226
5227       if (!usesOnlyOneValue) {
5228         // The dominant value was splatted as 'N', but we now have to insert
5229         // all differing elements.
5230         for (unsigned I = 0; I < NumElts; ++I) {
5231           if (Op.getOperand(I) == Value)
5232             continue;
5233           SmallVector<SDValue, 3> Ops;
5234           Ops.push_back(N);
5235           Ops.push_back(Op.getOperand(I));
5236           Ops.push_back(DAG.getConstant(I, MVT::i32));
5237           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5238         }
5239       }
5240       return N;
5241     }
5242     if (VT.getVectorElementType().isFloatingPoint()) {
5243       SmallVector<SDValue, 8> Ops;
5244       for (unsigned i = 0; i < NumElts; ++i)
5245         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5246                                   Op.getOperand(i)));
5247       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5248       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5249       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5250       if (Val.getNode())
5251         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5252     }
5253     if (usesOnlyOneValue) {
5254       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5255       if (isConstant && Val.getNode())
5256         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5257     }
5258   }
5259
5260   // If all elements are constants and the case above didn't get hit, fall back
5261   // to the default expansion, which will generate a load from the constant
5262   // pool.
5263   if (isConstant)
5264     return SDValue();
5265
5266   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5267   if (NumElts >= 4) {
5268     SDValue shuffle = ReconstructShuffle(Op, DAG);
5269     if (shuffle != SDValue())
5270       return shuffle;
5271   }
5272
5273   // Vectors with 32- or 64-bit elements can be built by directly assigning
5274   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5275   // will be legalized.
5276   if (EltSize >= 32) {
5277     // Do the expansion with floating-point types, since that is what the VFP
5278     // registers are defined to use, and since i64 is not legal.
5279     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5280     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5281     SmallVector<SDValue, 8> Ops;
5282     for (unsigned i = 0; i < NumElts; ++i)
5283       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5284     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5285     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5286   }
5287
5288   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5289   // know the default expansion would otherwise fall back on something even
5290   // worse. For a vector with one or two non-undef values, that's
5291   // scalar_to_vector for the elements followed by a shuffle (provided the
5292   // shuffle is valid for the target) and materialization element by element
5293   // on the stack followed by a load for everything else.
5294   if (!isConstant && !usesOnlyOneValue) {
5295     SDValue Vec = DAG.getUNDEF(VT);
5296     for (unsigned i = 0 ; i < NumElts; ++i) {
5297       SDValue V = Op.getOperand(i);
5298       if (V.getOpcode() == ISD::UNDEF)
5299         continue;
5300       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5301       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5302     }
5303     return Vec;
5304   }
5305
5306   return SDValue();
5307 }
5308
5309 // Gather data to see if the operation can be modelled as a
5310 // shuffle in combination with VEXTs.
5311 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5312                                               SelectionDAG &DAG) const {
5313   SDLoc dl(Op);
5314   EVT VT = Op.getValueType();
5315   unsigned NumElts = VT.getVectorNumElements();
5316
5317   SmallVector<SDValue, 2> SourceVecs;
5318   SmallVector<unsigned, 2> MinElts;
5319   SmallVector<unsigned, 2> MaxElts;
5320
5321   for (unsigned i = 0; i < NumElts; ++i) {
5322     SDValue V = Op.getOperand(i);
5323     if (V.getOpcode() == ISD::UNDEF)
5324       continue;
5325     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5326       // A shuffle can only come from building a vector from various
5327       // elements of other vectors.
5328       return SDValue();
5329     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5330                VT.getVectorElementType()) {
5331       // This code doesn't know how to handle shuffles where the vector
5332       // element types do not match (this happens because type legalization
5333       // promotes the return type of EXTRACT_VECTOR_ELT).
5334       // FIXME: It might be appropriate to extend this code to handle
5335       // mismatched types.
5336       return SDValue();
5337     }
5338
5339     // Record this extraction against the appropriate vector if possible...
5340     SDValue SourceVec = V.getOperand(0);
5341     // If the element number isn't a constant, we can't effectively
5342     // analyze what's going on.
5343     if (!isa<ConstantSDNode>(V.getOperand(1)))
5344       return SDValue();
5345     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5346     bool FoundSource = false;
5347     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5348       if (SourceVecs[j] == SourceVec) {
5349         if (MinElts[j] > EltNo)
5350           MinElts[j] = EltNo;
5351         if (MaxElts[j] < EltNo)
5352           MaxElts[j] = EltNo;
5353         FoundSource = true;
5354         break;
5355       }
5356     }
5357
5358     // Or record a new source if not...
5359     if (!FoundSource) {
5360       SourceVecs.push_back(SourceVec);
5361       MinElts.push_back(EltNo);
5362       MaxElts.push_back(EltNo);
5363     }
5364   }
5365
5366   // Currently only do something sane when at most two source vectors
5367   // involved.
5368   if (SourceVecs.size() > 2)
5369     return SDValue();
5370
5371   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5372   int VEXTOffsets[2] = {0, 0};
5373
5374   // This loop extracts the usage patterns of the source vectors
5375   // and prepares appropriate SDValues for a shuffle if possible.
5376   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5377     if (SourceVecs[i].getValueType() == VT) {
5378       // No VEXT necessary
5379       ShuffleSrcs[i] = SourceVecs[i];
5380       VEXTOffsets[i] = 0;
5381       continue;
5382     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5383       // It probably isn't worth padding out a smaller vector just to
5384       // break it down again in a shuffle.
5385       return SDValue();
5386     }
5387
5388     // Since only 64-bit and 128-bit vectors are legal on ARM and
5389     // we've eliminated the other cases...
5390     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5391            "unexpected vector sizes in ReconstructShuffle");
5392
5393     if (MaxElts[i] - MinElts[i] >= NumElts) {
5394       // Span too large for a VEXT to cope
5395       return SDValue();
5396     }
5397
5398     if (MinElts[i] >= NumElts) {
5399       // The extraction can just take the second half
5400       VEXTOffsets[i] = NumElts;
5401       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5402                                    SourceVecs[i],
5403                                    DAG.getIntPtrConstant(NumElts));
5404     } else if (MaxElts[i] < NumElts) {
5405       // The extraction can just take the first half
5406       VEXTOffsets[i] = 0;
5407       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5408                                    SourceVecs[i],
5409                                    DAG.getIntPtrConstant(0));
5410     } else {
5411       // An actual VEXT is needed
5412       VEXTOffsets[i] = MinElts[i];
5413       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5414                                      SourceVecs[i],
5415                                      DAG.getIntPtrConstant(0));
5416       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5417                                      SourceVecs[i],
5418                                      DAG.getIntPtrConstant(NumElts));
5419       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5420                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5421     }
5422   }
5423
5424   SmallVector<int, 8> Mask;
5425
5426   for (unsigned i = 0; i < NumElts; ++i) {
5427     SDValue Entry = Op.getOperand(i);
5428     if (Entry.getOpcode() == ISD::UNDEF) {
5429       Mask.push_back(-1);
5430       continue;
5431     }
5432
5433     SDValue ExtractVec = Entry.getOperand(0);
5434     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5435                                           .getOperand(1))->getSExtValue();
5436     if (ExtractVec == SourceVecs[0]) {
5437       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5438     } else {
5439       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5440     }
5441   }
5442
5443   // Final check before we try to produce nonsense...
5444   if (isShuffleMaskLegal(Mask, VT))
5445     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5446                                 &Mask[0]);
5447
5448   return SDValue();
5449 }
5450
5451 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5452 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5453 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5454 /// are assumed to be legal.
5455 bool
5456 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5457                                       EVT VT) const {
5458   if (VT.getVectorNumElements() == 4 &&
5459       (VT.is128BitVector() || VT.is64BitVector())) {
5460     unsigned PFIndexes[4];
5461     for (unsigned i = 0; i != 4; ++i) {
5462       if (M[i] < 0)
5463         PFIndexes[i] = 8;
5464       else
5465         PFIndexes[i] = M[i];
5466     }
5467
5468     // Compute the index in the perfect shuffle table.
5469     unsigned PFTableIndex =
5470       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5471     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5472     unsigned Cost = (PFEntry >> 30);
5473
5474     if (Cost <= 4)
5475       return true;
5476   }
5477
5478   bool ReverseVEXT;
5479   unsigned Imm, WhichResult;
5480
5481   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5482   return (EltSize >= 32 ||
5483           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5484           isVREVMask(M, VT, 64) ||
5485           isVREVMask(M, VT, 32) ||
5486           isVREVMask(M, VT, 16) ||
5487           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5488           isVTBLMask(M, VT) ||
5489           isVTRNMask(M, VT, WhichResult) ||
5490           isVUZPMask(M, VT, WhichResult) ||
5491           isVZIPMask(M, VT, WhichResult) ||
5492           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5493           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5494           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5495           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5496 }
5497
5498 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5499 /// the specified operations to build the shuffle.
5500 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5501                                       SDValue RHS, SelectionDAG &DAG,
5502                                       SDLoc dl) {
5503   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5504   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5505   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5506
5507   enum {
5508     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5509     OP_VREV,
5510     OP_VDUP0,
5511     OP_VDUP1,
5512     OP_VDUP2,
5513     OP_VDUP3,
5514     OP_VEXT1,
5515     OP_VEXT2,
5516     OP_VEXT3,
5517     OP_VUZPL, // VUZP, left result
5518     OP_VUZPR, // VUZP, right result
5519     OP_VZIPL, // VZIP, left result
5520     OP_VZIPR, // VZIP, right result
5521     OP_VTRNL, // VTRN, left result
5522     OP_VTRNR  // VTRN, right result
5523   };
5524
5525   if (OpNum == OP_COPY) {
5526     if (LHSID == (1*9+2)*9+3) return LHS;
5527     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5528     return RHS;
5529   }
5530
5531   SDValue OpLHS, OpRHS;
5532   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5533   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5534   EVT VT = OpLHS.getValueType();
5535
5536   switch (OpNum) {
5537   default: llvm_unreachable("Unknown shuffle opcode!");
5538   case OP_VREV:
5539     // VREV divides the vector in half and swaps within the half.
5540     if (VT.getVectorElementType() == MVT::i32 ||
5541         VT.getVectorElementType() == MVT::f32)
5542       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5543     // vrev <4 x i16> -> VREV32
5544     if (VT.getVectorElementType() == MVT::i16)
5545       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5546     // vrev <4 x i8> -> VREV16
5547     assert(VT.getVectorElementType() == MVT::i8);
5548     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5549   case OP_VDUP0:
5550   case OP_VDUP1:
5551   case OP_VDUP2:
5552   case OP_VDUP3:
5553     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5554                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5555   case OP_VEXT1:
5556   case OP_VEXT2:
5557   case OP_VEXT3:
5558     return DAG.getNode(ARMISD::VEXT, dl, VT,
5559                        OpLHS, OpRHS,
5560                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5561   case OP_VUZPL:
5562   case OP_VUZPR:
5563     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5564                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5565   case OP_VZIPL:
5566   case OP_VZIPR:
5567     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5568                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5569   case OP_VTRNL:
5570   case OP_VTRNR:
5571     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5572                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5573   }
5574 }
5575
5576 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5577                                        ArrayRef<int> ShuffleMask,
5578                                        SelectionDAG &DAG) {
5579   // Check to see if we can use the VTBL instruction.
5580   SDValue V1 = Op.getOperand(0);
5581   SDValue V2 = Op.getOperand(1);
5582   SDLoc DL(Op);
5583
5584   SmallVector<SDValue, 8> VTBLMask;
5585   for (ArrayRef<int>::iterator
5586          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5587     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5588
5589   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5590     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5591                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5592
5593   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5594                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5595 }
5596
5597 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5598                                                       SelectionDAG &DAG) {
5599   SDLoc DL(Op);
5600   SDValue OpLHS = Op.getOperand(0);
5601   EVT VT = OpLHS.getValueType();
5602
5603   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5604          "Expect an v8i16/v16i8 type");
5605   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5606   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5607   // extract the first 8 bytes into the top double word and the last 8 bytes
5608   // into the bottom double word. The v8i16 case is similar.
5609   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5610   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5611                      DAG.getConstant(ExtractNum, MVT::i32));
5612 }
5613
5614 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5615   SDValue V1 = Op.getOperand(0);
5616   SDValue V2 = Op.getOperand(1);
5617   SDLoc dl(Op);
5618   EVT VT = Op.getValueType();
5619   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5620
5621   // Convert shuffles that are directly supported on NEON to target-specific
5622   // DAG nodes, instead of keeping them as shuffles and matching them again
5623   // during code selection.  This is more efficient and avoids the possibility
5624   // of inconsistencies between legalization and selection.
5625   // FIXME: floating-point vectors should be canonicalized to integer vectors
5626   // of the same time so that they get CSEd properly.
5627   ArrayRef<int> ShuffleMask = SVN->getMask();
5628
5629   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5630   if (EltSize <= 32) {
5631     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5632       int Lane = SVN->getSplatIndex();
5633       // If this is undef splat, generate it via "just" vdup, if possible.
5634       if (Lane == -1) Lane = 0;
5635
5636       // Test if V1 is a SCALAR_TO_VECTOR.
5637       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5638         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5639       }
5640       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5641       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5642       // reaches it).
5643       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5644           !isa<ConstantSDNode>(V1.getOperand(0))) {
5645         bool IsScalarToVector = true;
5646         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5647           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5648             IsScalarToVector = false;
5649             break;
5650           }
5651         if (IsScalarToVector)
5652           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5653       }
5654       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5655                          DAG.getConstant(Lane, MVT::i32));
5656     }
5657
5658     bool ReverseVEXT;
5659     unsigned Imm;
5660     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5661       if (ReverseVEXT)
5662         std::swap(V1, V2);
5663       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5664                          DAG.getConstant(Imm, MVT::i32));
5665     }
5666
5667     if (isVREVMask(ShuffleMask, VT, 64))
5668       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5669     if (isVREVMask(ShuffleMask, VT, 32))
5670       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5671     if (isVREVMask(ShuffleMask, VT, 16))
5672       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5673
5674     if (V2->getOpcode() == ISD::UNDEF &&
5675         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5676       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5677                          DAG.getConstant(Imm, MVT::i32));
5678     }
5679
5680     // Check for Neon shuffles that modify both input vectors in place.
5681     // If both results are used, i.e., if there are two shuffles with the same
5682     // source operands and with masks corresponding to both results of one of
5683     // these operations, DAG memoization will ensure that a single node is
5684     // used for both shuffles.
5685     unsigned WhichResult;
5686     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5687       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5688                          V1, V2).getValue(WhichResult);
5689     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5690       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5691                          V1, V2).getValue(WhichResult);
5692     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5693       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5694                          V1, V2).getValue(WhichResult);
5695
5696     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5697       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5698                          V1, V1).getValue(WhichResult);
5699     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5700       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5701                          V1, V1).getValue(WhichResult);
5702     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5703       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5704                          V1, V1).getValue(WhichResult);
5705   }
5706
5707   // If the shuffle is not directly supported and it has 4 elements, use
5708   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5709   unsigned NumElts = VT.getVectorNumElements();
5710   if (NumElts == 4) {
5711     unsigned PFIndexes[4];
5712     for (unsigned i = 0; i != 4; ++i) {
5713       if (ShuffleMask[i] < 0)
5714         PFIndexes[i] = 8;
5715       else
5716         PFIndexes[i] = ShuffleMask[i];
5717     }
5718
5719     // Compute the index in the perfect shuffle table.
5720     unsigned PFTableIndex =
5721       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5722     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5723     unsigned Cost = (PFEntry >> 30);
5724
5725     if (Cost <= 4)
5726       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5727   }
5728
5729   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5730   if (EltSize >= 32) {
5731     // Do the expansion with floating-point types, since that is what the VFP
5732     // registers are defined to use, and since i64 is not legal.
5733     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5734     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5735     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5736     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5737     SmallVector<SDValue, 8> Ops;
5738     for (unsigned i = 0; i < NumElts; ++i) {
5739       if (ShuffleMask[i] < 0)
5740         Ops.push_back(DAG.getUNDEF(EltVT));
5741       else
5742         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5743                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5744                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5745                                                   MVT::i32)));
5746     }
5747     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5748     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5749   }
5750
5751   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5752     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5753
5754   if (VT == MVT::v8i8) {
5755     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5756     if (NewOp.getNode())
5757       return NewOp;
5758   }
5759
5760   return SDValue();
5761 }
5762
5763 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5764   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5765   SDValue Lane = Op.getOperand(2);
5766   if (!isa<ConstantSDNode>(Lane))
5767     return SDValue();
5768
5769   return Op;
5770 }
5771
5772 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5773   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5774   SDValue Lane = Op.getOperand(1);
5775   if (!isa<ConstantSDNode>(Lane))
5776     return SDValue();
5777
5778   SDValue Vec = Op.getOperand(0);
5779   if (Op.getValueType() == MVT::i32 &&
5780       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5781     SDLoc dl(Op);
5782     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5783   }
5784
5785   return Op;
5786 }
5787
5788 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5789   // The only time a CONCAT_VECTORS operation can have legal types is when
5790   // two 64-bit vectors are concatenated to a 128-bit vector.
5791   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5792          "unexpected CONCAT_VECTORS");
5793   SDLoc dl(Op);
5794   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5795   SDValue Op0 = Op.getOperand(0);
5796   SDValue Op1 = Op.getOperand(1);
5797   if (Op0.getOpcode() != ISD::UNDEF)
5798     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5799                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5800                       DAG.getIntPtrConstant(0));
5801   if (Op1.getOpcode() != ISD::UNDEF)
5802     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5803                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5804                       DAG.getIntPtrConstant(1));
5805   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5806 }
5807
5808 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5809 /// element has been zero/sign-extended, depending on the isSigned parameter,
5810 /// from an integer type half its size.
5811 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5812                                    bool isSigned) {
5813   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5814   EVT VT = N->getValueType(0);
5815   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5816     SDNode *BVN = N->getOperand(0).getNode();
5817     if (BVN->getValueType(0) != MVT::v4i32 ||
5818         BVN->getOpcode() != ISD::BUILD_VECTOR)
5819       return false;
5820     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5821     unsigned HiElt = 1 - LoElt;
5822     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5823     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5824     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5825     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5826     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5827       return false;
5828     if (isSigned) {
5829       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5830           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5831         return true;
5832     } else {
5833       if (Hi0->isNullValue() && Hi1->isNullValue())
5834         return true;
5835     }
5836     return false;
5837   }
5838
5839   if (N->getOpcode() != ISD::BUILD_VECTOR)
5840     return false;
5841
5842   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5843     SDNode *Elt = N->getOperand(i).getNode();
5844     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5845       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5846       unsigned HalfSize = EltSize / 2;
5847       if (isSigned) {
5848         if (!isIntN(HalfSize, C->getSExtValue()))
5849           return false;
5850       } else {
5851         if (!isUIntN(HalfSize, C->getZExtValue()))
5852           return false;
5853       }
5854       continue;
5855     }
5856     return false;
5857   }
5858
5859   return true;
5860 }
5861
5862 /// isSignExtended - Check if a node is a vector value that is sign-extended
5863 /// or a constant BUILD_VECTOR with sign-extended elements.
5864 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5865   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5866     return true;
5867   if (isExtendedBUILD_VECTOR(N, DAG, true))
5868     return true;
5869   return false;
5870 }
5871
5872 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5873 /// or a constant BUILD_VECTOR with zero-extended elements.
5874 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5875   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5876     return true;
5877   if (isExtendedBUILD_VECTOR(N, DAG, false))
5878     return true;
5879   return false;
5880 }
5881
5882 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5883   if (OrigVT.getSizeInBits() >= 64)
5884     return OrigVT;
5885
5886   assert(OrigVT.isSimple() && "Expecting a simple value type");
5887
5888   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5889   switch (OrigSimpleTy) {
5890   default: llvm_unreachable("Unexpected Vector Type");
5891   case MVT::v2i8:
5892   case MVT::v2i16:
5893      return MVT::v2i32;
5894   case MVT::v4i8:
5895     return  MVT::v4i16;
5896   }
5897 }
5898
5899 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5900 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5901 /// We insert the required extension here to get the vector to fill a D register.
5902 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5903                                             const EVT &OrigTy,
5904                                             const EVT &ExtTy,
5905                                             unsigned ExtOpcode) {
5906   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5907   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5908   // 64-bits we need to insert a new extension so that it will be 64-bits.
5909   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5910   if (OrigTy.getSizeInBits() >= 64)
5911     return N;
5912
5913   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5914   EVT NewVT = getExtensionTo64Bits(OrigTy);
5915
5916   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5917 }
5918
5919 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5920 /// does not do any sign/zero extension. If the original vector is less
5921 /// than 64 bits, an appropriate extension will be added after the load to
5922 /// reach a total size of 64 bits. We have to add the extension separately
5923 /// because ARM does not have a sign/zero extending load for vectors.
5924 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5925   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5926
5927   // The load already has the right type.
5928   if (ExtendedTy == LD->getMemoryVT())
5929     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5930                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5931                 LD->isNonTemporal(), LD->isInvariant(),
5932                 LD->getAlignment());
5933
5934   // We need to create a zextload/sextload. We cannot just create a load
5935   // followed by a zext/zext node because LowerMUL is also run during normal
5936   // operation legalization where we can't create illegal types.
5937   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5938                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5939                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5940                         LD->isNonTemporal(), LD->getAlignment());
5941 }
5942
5943 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5944 /// extending load, or BUILD_VECTOR with extended elements, return the
5945 /// unextended value. The unextended vector should be 64 bits so that it can
5946 /// be used as an operand to a VMULL instruction. If the original vector size
5947 /// before extension is less than 64 bits we add a an extension to resize
5948 /// the vector to 64 bits.
5949 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5950   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5951     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5952                                         N->getOperand(0)->getValueType(0),
5953                                         N->getValueType(0),
5954                                         N->getOpcode());
5955
5956   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5957     return SkipLoadExtensionForVMULL(LD, DAG);
5958
5959   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5960   // have been legalized as a BITCAST from v4i32.
5961   if (N->getOpcode() == ISD::BITCAST) {
5962     SDNode *BVN = N->getOperand(0).getNode();
5963     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5964            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5965     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5966     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5967                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5968   }
5969   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5970   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5971   EVT VT = N->getValueType(0);
5972   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5973   unsigned NumElts = VT.getVectorNumElements();
5974   MVT TruncVT = MVT::getIntegerVT(EltSize);
5975   SmallVector<SDValue, 8> Ops;
5976   for (unsigned i = 0; i != NumElts; ++i) {
5977     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5978     const APInt &CInt = C->getAPIntValue();
5979     // Element types smaller than 32 bits are not legal, so use i32 elements.
5980     // The values are implicitly truncated so sext vs. zext doesn't matter.
5981     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5982   }
5983   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5984                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5985 }
5986
5987 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5988   unsigned Opcode = N->getOpcode();
5989   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5990     SDNode *N0 = N->getOperand(0).getNode();
5991     SDNode *N1 = N->getOperand(1).getNode();
5992     return N0->hasOneUse() && N1->hasOneUse() &&
5993       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5994   }
5995   return false;
5996 }
5997
5998 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5999   unsigned Opcode = N->getOpcode();
6000   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6001     SDNode *N0 = N->getOperand(0).getNode();
6002     SDNode *N1 = N->getOperand(1).getNode();
6003     return N0->hasOneUse() && N1->hasOneUse() &&
6004       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6005   }
6006   return false;
6007 }
6008
6009 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6010   // Multiplications are only custom-lowered for 128-bit vectors so that
6011   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6012   EVT VT = Op.getValueType();
6013   assert(VT.is128BitVector() && VT.isInteger() &&
6014          "unexpected type for custom-lowering ISD::MUL");
6015   SDNode *N0 = Op.getOperand(0).getNode();
6016   SDNode *N1 = Op.getOperand(1).getNode();
6017   unsigned NewOpc = 0;
6018   bool isMLA = false;
6019   bool isN0SExt = isSignExtended(N0, DAG);
6020   bool isN1SExt = isSignExtended(N1, DAG);
6021   if (isN0SExt && isN1SExt)
6022     NewOpc = ARMISD::VMULLs;
6023   else {
6024     bool isN0ZExt = isZeroExtended(N0, DAG);
6025     bool isN1ZExt = isZeroExtended(N1, DAG);
6026     if (isN0ZExt && isN1ZExt)
6027       NewOpc = ARMISD::VMULLu;
6028     else if (isN1SExt || isN1ZExt) {
6029       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6030       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6031       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6032         NewOpc = ARMISD::VMULLs;
6033         isMLA = true;
6034       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6035         NewOpc = ARMISD::VMULLu;
6036         isMLA = true;
6037       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6038         std::swap(N0, N1);
6039         NewOpc = ARMISD::VMULLu;
6040         isMLA = true;
6041       }
6042     }
6043
6044     if (!NewOpc) {
6045       if (VT == MVT::v2i64)
6046         // Fall through to expand this.  It is not legal.
6047         return SDValue();
6048       else
6049         // Other vector multiplications are legal.
6050         return Op;
6051     }
6052   }
6053
6054   // Legalize to a VMULL instruction.
6055   SDLoc DL(Op);
6056   SDValue Op0;
6057   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6058   if (!isMLA) {
6059     Op0 = SkipExtensionForVMULL(N0, DAG);
6060     assert(Op0.getValueType().is64BitVector() &&
6061            Op1.getValueType().is64BitVector() &&
6062            "unexpected types for extended operands to VMULL");
6063     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6064   }
6065
6066   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6067   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6068   //   vmull q0, d4, d6
6069   //   vmlal q0, d5, d6
6070   // is faster than
6071   //   vaddl q0, d4, d5
6072   //   vmovl q1, d6
6073   //   vmul  q0, q0, q1
6074   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6075   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6076   EVT Op1VT = Op1.getValueType();
6077   return DAG.getNode(N0->getOpcode(), DL, VT,
6078                      DAG.getNode(NewOpc, DL, VT,
6079                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6080                      DAG.getNode(NewOpc, DL, VT,
6081                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6082 }
6083
6084 static SDValue
6085 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6086   // Convert to float
6087   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6088   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6089   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6090   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6091   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6092   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6093   // Get reciprocal estimate.
6094   // float4 recip = vrecpeq_f32(yf);
6095   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6096                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6097   // Because char has a smaller range than uchar, we can actually get away
6098   // without any newton steps.  This requires that we use a weird bias
6099   // of 0xb000, however (again, this has been exhaustively tested).
6100   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6101   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6102   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6103   Y = DAG.getConstant(0xb000, MVT::i32);
6104   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6105   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6106   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6107   // Convert back to short.
6108   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6109   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6110   return X;
6111 }
6112
6113 static SDValue
6114 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6115   SDValue N2;
6116   // Convert to float.
6117   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6118   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6119   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6120   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6121   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6122   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6123
6124   // Use reciprocal estimate and one refinement step.
6125   // float4 recip = vrecpeq_f32(yf);
6126   // recip *= vrecpsq_f32(yf, recip);
6127   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6128                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6129   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6130                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6131                    N1, N2);
6132   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6133   // Because short has a smaller range than ushort, we can actually get away
6134   // with only a single newton step.  This requires that we use a weird bias
6135   // of 89, however (again, this has been exhaustively tested).
6136   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6137   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6138   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6139   N1 = DAG.getConstant(0x89, MVT::i32);
6140   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6141   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6142   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6143   // Convert back to integer and return.
6144   // return vmovn_s32(vcvt_s32_f32(result));
6145   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6146   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6147   return N0;
6148 }
6149
6150 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6151   EVT VT = Op.getValueType();
6152   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6153          "unexpected type for custom-lowering ISD::SDIV");
6154
6155   SDLoc dl(Op);
6156   SDValue N0 = Op.getOperand(0);
6157   SDValue N1 = Op.getOperand(1);
6158   SDValue N2, N3;
6159
6160   if (VT == MVT::v8i8) {
6161     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6162     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6163
6164     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6165                      DAG.getIntPtrConstant(4));
6166     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6167                      DAG.getIntPtrConstant(4));
6168     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6169                      DAG.getIntPtrConstant(0));
6170     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6171                      DAG.getIntPtrConstant(0));
6172
6173     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6174     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6175
6176     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6177     N0 = LowerCONCAT_VECTORS(N0, DAG);
6178
6179     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6180     return N0;
6181   }
6182   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6183 }
6184
6185 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6186   EVT VT = Op.getValueType();
6187   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6188          "unexpected type for custom-lowering ISD::UDIV");
6189
6190   SDLoc dl(Op);
6191   SDValue N0 = Op.getOperand(0);
6192   SDValue N1 = Op.getOperand(1);
6193   SDValue N2, N3;
6194
6195   if (VT == MVT::v8i8) {
6196     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6197     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6198
6199     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6200                      DAG.getIntPtrConstant(4));
6201     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6202                      DAG.getIntPtrConstant(4));
6203     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6204                      DAG.getIntPtrConstant(0));
6205     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6206                      DAG.getIntPtrConstant(0));
6207
6208     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6209     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6210
6211     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6212     N0 = LowerCONCAT_VECTORS(N0, DAG);
6213
6214     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6215                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6216                      N0);
6217     return N0;
6218   }
6219
6220   // v4i16 sdiv ... Convert to float.
6221   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6222   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6223   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6224   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6225   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6226   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6227
6228   // Use reciprocal estimate and two refinement steps.
6229   // float4 recip = vrecpeq_f32(yf);
6230   // recip *= vrecpsq_f32(yf, recip);
6231   // recip *= vrecpsq_f32(yf, recip);
6232   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6233                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6234   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6235                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6236                    BN1, N2);
6237   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6238   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6239                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6240                    BN1, N2);
6241   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6242   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6243   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6244   // and that it will never cause us to return an answer too large).
6245   // float4 result = as_float4(as_int4(xf*recip) + 2);
6246   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6247   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6248   N1 = DAG.getConstant(2, MVT::i32);
6249   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6250   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6251   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6252   // Convert back to integer and return.
6253   // return vmovn_u32(vcvt_s32_f32(result));
6254   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6255   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6256   return N0;
6257 }
6258
6259 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6260   EVT VT = Op.getNode()->getValueType(0);
6261   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6262
6263   unsigned Opc;
6264   bool ExtraOp = false;
6265   switch (Op.getOpcode()) {
6266   default: llvm_unreachable("Invalid code");
6267   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6268   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6269   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6270   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6271   }
6272
6273   if (!ExtraOp)
6274     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6275                        Op.getOperand(1));
6276   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6277                      Op.getOperand(1), Op.getOperand(2));
6278 }
6279
6280 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6281   assert(Subtarget->isTargetDarwin());
6282
6283   // For iOS, we want to call an alternative entry point: __sincos_stret,
6284   // return values are passed via sret.
6285   SDLoc dl(Op);
6286   SDValue Arg = Op.getOperand(0);
6287   EVT ArgVT = Arg.getValueType();
6288   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6289
6290   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6291   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6292
6293   // Pair of floats / doubles used to pass the result.
6294   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6295
6296   // Create stack object for sret.
6297   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6298   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6299   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6300   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6301
6302   ArgListTy Args;
6303   ArgListEntry Entry;
6304
6305   Entry.Node = SRet;
6306   Entry.Ty = RetTy->getPointerTo();
6307   Entry.isSExt = false;
6308   Entry.isZExt = false;
6309   Entry.isSRet = true;
6310   Args.push_back(Entry);
6311
6312   Entry.Node = Arg;
6313   Entry.Ty = ArgTy;
6314   Entry.isSExt = false;
6315   Entry.isZExt = false;
6316   Args.push_back(Entry);
6317
6318   const char *LibcallName  = (ArgVT == MVT::f64)
6319   ? "__sincos_stret" : "__sincosf_stret";
6320   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6321
6322   TargetLowering::CallLoweringInfo CLI(DAG);
6323   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6324     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6325                std::move(Args), 0)
6326     .setDiscardResult();
6327
6328   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6329
6330   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6331                                 MachinePointerInfo(), false, false, false, 0);
6332
6333   // Address of cos field.
6334   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6335                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6336   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6337                                 MachinePointerInfo(), false, false, false, 0);
6338
6339   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6340   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6341                      LoadSin.getValue(0), LoadCos.getValue(0));
6342 }
6343
6344 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6345   // Monotonic load/store is legal for all targets
6346   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6347     return Op;
6348
6349   // Acquire/Release load/store is not legal for targets without a
6350   // dmb or equivalent available.
6351   return SDValue();
6352 }
6353
6354 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6355                                     SmallVectorImpl<SDValue> &Results,
6356                                     SelectionDAG &DAG,
6357                                     const ARMSubtarget *Subtarget) {
6358   SDLoc DL(N);
6359   SDValue Cycles32, OutChain;
6360
6361   if (Subtarget->hasPerfMon()) {
6362     // Under Power Management extensions, the cycle-count is:
6363     //    mrc p15, #0, <Rt>, c9, c13, #0
6364     SDValue Ops[] = { N->getOperand(0), // Chain
6365                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6366                       DAG.getConstant(15, MVT::i32),
6367                       DAG.getConstant(0, MVT::i32),
6368                       DAG.getConstant(9, MVT::i32),
6369                       DAG.getConstant(13, MVT::i32),
6370                       DAG.getConstant(0, MVT::i32)
6371     };
6372
6373     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6374                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6375     OutChain = Cycles32.getValue(1);
6376   } else {
6377     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6378     // there are older ARM CPUs that have implementation-specific ways of
6379     // obtaining this information (FIXME!).
6380     Cycles32 = DAG.getConstant(0, MVT::i32);
6381     OutChain = DAG.getEntryNode();
6382   }
6383
6384
6385   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6386                                  Cycles32, DAG.getConstant(0, MVT::i32));
6387   Results.push_back(Cycles64);
6388   Results.push_back(OutChain);
6389 }
6390
6391 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6392   switch (Op.getOpcode()) {
6393   default: llvm_unreachable("Don't know how to custom lower this!");
6394   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6395   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6396   case ISD::GlobalAddress:
6397     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6398     default: llvm_unreachable("unknown object format");
6399     case Triple::COFF:
6400       return LowerGlobalAddressWindows(Op, DAG);
6401     case Triple::ELF:
6402       return LowerGlobalAddressELF(Op, DAG);
6403     case Triple::MachO:
6404       return LowerGlobalAddressDarwin(Op, DAG);
6405     }
6406   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6407   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6408   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6409   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6410   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6411   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6412   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6413   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6414   case ISD::SINT_TO_FP:
6415   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6416   case ISD::FP_TO_SINT:
6417   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6418   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6419   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6420   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6421   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6422   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6423   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6424   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6425                                                                Subtarget);
6426   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6427   case ISD::SHL:
6428   case ISD::SRL:
6429   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6430   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6431   case ISD::SRL_PARTS:
6432   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6433   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6434   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6435   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6436   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6437   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6438   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6439   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6440   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6441   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6442   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6443   case ISD::MUL:           return LowerMUL(Op, DAG);
6444   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6445   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6446   case ISD::ADDC:
6447   case ISD::ADDE:
6448   case ISD::SUBC:
6449   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6450   case ISD::SADDO:
6451   case ISD::UADDO:
6452   case ISD::SSUBO:
6453   case ISD::USUBO:
6454     return LowerXALUO(Op, DAG);
6455   case ISD::ATOMIC_LOAD:
6456   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6457   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6458   case ISD::SDIVREM:
6459   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6460   case ISD::DYNAMIC_STACKALLOC:
6461     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6462       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6463     llvm_unreachable("Don't know how to custom lower this!");
6464   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6465   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6466   }
6467 }
6468
6469 /// ReplaceNodeResults - Replace the results of node with an illegal result
6470 /// type with new values built out of custom code.
6471 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6472                                            SmallVectorImpl<SDValue>&Results,
6473                                            SelectionDAG &DAG) const {
6474   SDValue Res;
6475   switch (N->getOpcode()) {
6476   default:
6477     llvm_unreachable("Don't know how to custom expand this!");
6478   case ISD::BITCAST:
6479     Res = ExpandBITCAST(N, DAG);
6480     break;
6481   case ISD::SRL:
6482   case ISD::SRA:
6483     Res = Expand64BitShift(N, DAG, Subtarget);
6484     break;
6485   case ISD::READCYCLECOUNTER:
6486     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6487     return;
6488   }
6489   if (Res.getNode())
6490     Results.push_back(Res);
6491 }
6492
6493 //===----------------------------------------------------------------------===//
6494 //                           ARM Scheduler Hooks
6495 //===----------------------------------------------------------------------===//
6496
6497 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6498 /// registers the function context.
6499 void ARMTargetLowering::
6500 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6501                        MachineBasicBlock *DispatchBB, int FI) const {
6502   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6503   DebugLoc dl = MI->getDebugLoc();
6504   MachineFunction *MF = MBB->getParent();
6505   MachineRegisterInfo *MRI = &MF->getRegInfo();
6506   MachineConstantPool *MCP = MF->getConstantPool();
6507   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6508   const Function *F = MF->getFunction();
6509
6510   bool isThumb = Subtarget->isThumb();
6511   bool isThumb2 = Subtarget->isThumb2();
6512
6513   unsigned PCLabelId = AFI->createPICLabelUId();
6514   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6515   ARMConstantPoolValue *CPV =
6516     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6517   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6518
6519   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6520                                            : &ARM::GPRRegClass;
6521
6522   // Grab constant pool and fixed stack memory operands.
6523   MachineMemOperand *CPMMO =
6524     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6525                              MachineMemOperand::MOLoad, 4, 4);
6526
6527   MachineMemOperand *FIMMOSt =
6528     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6529                              MachineMemOperand::MOStore, 4, 4);
6530
6531   // Load the address of the dispatch MBB into the jump buffer.
6532   if (isThumb2) {
6533     // Incoming value: jbuf
6534     //   ldr.n  r5, LCPI1_1
6535     //   orr    r5, r5, #1
6536     //   add    r5, pc
6537     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6538     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6539     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6540                    .addConstantPoolIndex(CPI)
6541                    .addMemOperand(CPMMO));
6542     // Set the low bit because of thumb mode.
6543     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6544     AddDefaultCC(
6545       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6546                      .addReg(NewVReg1, RegState::Kill)
6547                      .addImm(0x01)));
6548     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6549     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6550       .addReg(NewVReg2, RegState::Kill)
6551       .addImm(PCLabelId);
6552     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6553                    .addReg(NewVReg3, RegState::Kill)
6554                    .addFrameIndex(FI)
6555                    .addImm(36)  // &jbuf[1] :: pc
6556                    .addMemOperand(FIMMOSt));
6557   } else if (isThumb) {
6558     // Incoming value: jbuf
6559     //   ldr.n  r1, LCPI1_4
6560     //   add    r1, pc
6561     //   mov    r2, #1
6562     //   orrs   r1, r2
6563     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6564     //   str    r1, [r2]
6565     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6566     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6567                    .addConstantPoolIndex(CPI)
6568                    .addMemOperand(CPMMO));
6569     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6570     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6571       .addReg(NewVReg1, RegState::Kill)
6572       .addImm(PCLabelId);
6573     // Set the low bit because of thumb mode.
6574     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6575     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6576                    .addReg(ARM::CPSR, RegState::Define)
6577                    .addImm(1));
6578     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6579     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6580                    .addReg(ARM::CPSR, RegState::Define)
6581                    .addReg(NewVReg2, RegState::Kill)
6582                    .addReg(NewVReg3, RegState::Kill));
6583     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6584     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6585             .addFrameIndex(FI)
6586             .addImm(36); // &jbuf[1] :: pc
6587     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6588                    .addReg(NewVReg4, RegState::Kill)
6589                    .addReg(NewVReg5, RegState::Kill)
6590                    .addImm(0)
6591                    .addMemOperand(FIMMOSt));
6592   } else {
6593     // Incoming value: jbuf
6594     //   ldr  r1, LCPI1_1
6595     //   add  r1, pc, r1
6596     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6597     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6598     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6599                    .addConstantPoolIndex(CPI)
6600                    .addImm(0)
6601                    .addMemOperand(CPMMO));
6602     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6603     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6604                    .addReg(NewVReg1, RegState::Kill)
6605                    .addImm(PCLabelId));
6606     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6607                    .addReg(NewVReg2, RegState::Kill)
6608                    .addFrameIndex(FI)
6609                    .addImm(36)  // &jbuf[1] :: pc
6610                    .addMemOperand(FIMMOSt));
6611   }
6612 }
6613
6614 MachineBasicBlock *ARMTargetLowering::
6615 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6616   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6617   DebugLoc dl = MI->getDebugLoc();
6618   MachineFunction *MF = MBB->getParent();
6619   MachineRegisterInfo *MRI = &MF->getRegInfo();
6620   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6621   MachineFrameInfo *MFI = MF->getFrameInfo();
6622   int FI = MFI->getFunctionContextIndex();
6623
6624   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6625                                                         : &ARM::GPRnopcRegClass;
6626
6627   // Get a mapping of the call site numbers to all of the landing pads they're
6628   // associated with.
6629   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6630   unsigned MaxCSNum = 0;
6631   MachineModuleInfo &MMI = MF->getMMI();
6632   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6633        ++BB) {
6634     if (!BB->isLandingPad()) continue;
6635
6636     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6637     // pad.
6638     for (MachineBasicBlock::iterator
6639            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6640       if (!II->isEHLabel()) continue;
6641
6642       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6643       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6644
6645       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6646       for (SmallVectorImpl<unsigned>::iterator
6647              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6648            CSI != CSE; ++CSI) {
6649         CallSiteNumToLPad[*CSI].push_back(BB);
6650         MaxCSNum = std::max(MaxCSNum, *CSI);
6651       }
6652       break;
6653     }
6654   }
6655
6656   // Get an ordered list of the machine basic blocks for the jump table.
6657   std::vector<MachineBasicBlock*> LPadList;
6658   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6659   LPadList.reserve(CallSiteNumToLPad.size());
6660   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6661     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6662     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6663            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6664       LPadList.push_back(*II);
6665       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6666     }
6667   }
6668
6669   assert(!LPadList.empty() &&
6670          "No landing pad destinations for the dispatch jump table!");
6671
6672   // Create the jump table and associated information.
6673   MachineJumpTableInfo *JTI =
6674     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6675   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6676   unsigned UId = AFI->createJumpTableUId();
6677   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6678
6679   // Create the MBBs for the dispatch code.
6680
6681   // Shove the dispatch's address into the return slot in the function context.
6682   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6683   DispatchBB->setIsLandingPad();
6684
6685   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6686   unsigned trap_opcode;
6687   if (Subtarget->isThumb())
6688     trap_opcode = ARM::tTRAP;
6689   else
6690     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6691
6692   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6693   DispatchBB->addSuccessor(TrapBB);
6694
6695   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6696   DispatchBB->addSuccessor(DispContBB);
6697
6698   // Insert and MBBs.
6699   MF->insert(MF->end(), DispatchBB);
6700   MF->insert(MF->end(), DispContBB);
6701   MF->insert(MF->end(), TrapBB);
6702
6703   // Insert code into the entry block that creates and registers the function
6704   // context.
6705   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6706
6707   MachineMemOperand *FIMMOLd =
6708     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6709                              MachineMemOperand::MOLoad |
6710                              MachineMemOperand::MOVolatile, 4, 4);
6711
6712   MachineInstrBuilder MIB;
6713   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6714
6715   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6716   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6717
6718   // Add a register mask with no preserved registers.  This results in all
6719   // registers being marked as clobbered.
6720   MIB.addRegMask(RI.getNoPreservedMask());
6721
6722   unsigned NumLPads = LPadList.size();
6723   if (Subtarget->isThumb2()) {
6724     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6725     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6726                    .addFrameIndex(FI)
6727                    .addImm(4)
6728                    .addMemOperand(FIMMOLd));
6729
6730     if (NumLPads < 256) {
6731       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6732                      .addReg(NewVReg1)
6733                      .addImm(LPadList.size()));
6734     } else {
6735       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6736       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6737                      .addImm(NumLPads & 0xFFFF));
6738
6739       unsigned VReg2 = VReg1;
6740       if ((NumLPads & 0xFFFF0000) != 0) {
6741         VReg2 = MRI->createVirtualRegister(TRC);
6742         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6743                        .addReg(VReg1)
6744                        .addImm(NumLPads >> 16));
6745       }
6746
6747       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6748                      .addReg(NewVReg1)
6749                      .addReg(VReg2));
6750     }
6751
6752     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6753       .addMBB(TrapBB)
6754       .addImm(ARMCC::HI)
6755       .addReg(ARM::CPSR);
6756
6757     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6758     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6759                    .addJumpTableIndex(MJTI)
6760                    .addImm(UId));
6761
6762     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6763     AddDefaultCC(
6764       AddDefaultPred(
6765         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6766         .addReg(NewVReg3, RegState::Kill)
6767         .addReg(NewVReg1)
6768         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6769
6770     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6771       .addReg(NewVReg4, RegState::Kill)
6772       .addReg(NewVReg1)
6773       .addJumpTableIndex(MJTI)
6774       .addImm(UId);
6775   } else if (Subtarget->isThumb()) {
6776     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6777     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6778                    .addFrameIndex(FI)
6779                    .addImm(1)
6780                    .addMemOperand(FIMMOLd));
6781
6782     if (NumLPads < 256) {
6783       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6784                      .addReg(NewVReg1)
6785                      .addImm(NumLPads));
6786     } else {
6787       MachineConstantPool *ConstantPool = MF->getConstantPool();
6788       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6789       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6790
6791       // MachineConstantPool wants an explicit alignment.
6792       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6793       if (Align == 0)
6794         Align = getDataLayout()->getTypeAllocSize(C->getType());
6795       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6796
6797       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6798       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6799                      .addReg(VReg1, RegState::Define)
6800                      .addConstantPoolIndex(Idx));
6801       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6802                      .addReg(NewVReg1)
6803                      .addReg(VReg1));
6804     }
6805
6806     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6807       .addMBB(TrapBB)
6808       .addImm(ARMCC::HI)
6809       .addReg(ARM::CPSR);
6810
6811     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6812     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6813                    .addReg(ARM::CPSR, RegState::Define)
6814                    .addReg(NewVReg1)
6815                    .addImm(2));
6816
6817     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6818     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6819                    .addJumpTableIndex(MJTI)
6820                    .addImm(UId));
6821
6822     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6823     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6824                    .addReg(ARM::CPSR, RegState::Define)
6825                    .addReg(NewVReg2, RegState::Kill)
6826                    .addReg(NewVReg3));
6827
6828     MachineMemOperand *JTMMOLd =
6829       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6830                                MachineMemOperand::MOLoad, 4, 4);
6831
6832     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6833     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6834                    .addReg(NewVReg4, RegState::Kill)
6835                    .addImm(0)
6836                    .addMemOperand(JTMMOLd));
6837
6838     unsigned NewVReg6 = NewVReg5;
6839     if (RelocM == Reloc::PIC_) {
6840       NewVReg6 = MRI->createVirtualRegister(TRC);
6841       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6842                      .addReg(ARM::CPSR, RegState::Define)
6843                      .addReg(NewVReg5, RegState::Kill)
6844                      .addReg(NewVReg3));
6845     }
6846
6847     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6848       .addReg(NewVReg6, RegState::Kill)
6849       .addJumpTableIndex(MJTI)
6850       .addImm(UId);
6851   } else {
6852     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6853     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6854                    .addFrameIndex(FI)
6855                    .addImm(4)
6856                    .addMemOperand(FIMMOLd));
6857
6858     if (NumLPads < 256) {
6859       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6860                      .addReg(NewVReg1)
6861                      .addImm(NumLPads));
6862     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6863       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6864       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6865                      .addImm(NumLPads & 0xFFFF));
6866
6867       unsigned VReg2 = VReg1;
6868       if ((NumLPads & 0xFFFF0000) != 0) {
6869         VReg2 = MRI->createVirtualRegister(TRC);
6870         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6871                        .addReg(VReg1)
6872                        .addImm(NumLPads >> 16));
6873       }
6874
6875       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6876                      .addReg(NewVReg1)
6877                      .addReg(VReg2));
6878     } else {
6879       MachineConstantPool *ConstantPool = MF->getConstantPool();
6880       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6881       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6882
6883       // MachineConstantPool wants an explicit alignment.
6884       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6885       if (Align == 0)
6886         Align = getDataLayout()->getTypeAllocSize(C->getType());
6887       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6888
6889       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6890       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6891                      .addReg(VReg1, RegState::Define)
6892                      .addConstantPoolIndex(Idx)
6893                      .addImm(0));
6894       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6895                      .addReg(NewVReg1)
6896                      .addReg(VReg1, RegState::Kill));
6897     }
6898
6899     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6900       .addMBB(TrapBB)
6901       .addImm(ARMCC::HI)
6902       .addReg(ARM::CPSR);
6903
6904     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6905     AddDefaultCC(
6906       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6907                      .addReg(NewVReg1)
6908                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6909     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6910     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6911                    .addJumpTableIndex(MJTI)
6912                    .addImm(UId));
6913
6914     MachineMemOperand *JTMMOLd =
6915       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6916                                MachineMemOperand::MOLoad, 4, 4);
6917     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6918     AddDefaultPred(
6919       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6920       .addReg(NewVReg3, RegState::Kill)
6921       .addReg(NewVReg4)
6922       .addImm(0)
6923       .addMemOperand(JTMMOLd));
6924
6925     if (RelocM == Reloc::PIC_) {
6926       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6927         .addReg(NewVReg5, RegState::Kill)
6928         .addReg(NewVReg4)
6929         .addJumpTableIndex(MJTI)
6930         .addImm(UId);
6931     } else {
6932       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6933         .addReg(NewVReg5, RegState::Kill)
6934         .addJumpTableIndex(MJTI)
6935         .addImm(UId);
6936     }
6937   }
6938
6939   // Add the jump table entries as successors to the MBB.
6940   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6941   for (std::vector<MachineBasicBlock*>::iterator
6942          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6943     MachineBasicBlock *CurMBB = *I;
6944     if (SeenMBBs.insert(CurMBB).second)
6945       DispContBB->addSuccessor(CurMBB);
6946   }
6947
6948   // N.B. the order the invoke BBs are processed in doesn't matter here.
6949   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6950   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6951   for (MachineBasicBlock *BB : InvokeBBs) {
6952
6953     // Remove the landing pad successor from the invoke block and replace it
6954     // with the new dispatch block.
6955     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6956                                                   BB->succ_end());
6957     while (!Successors.empty()) {
6958       MachineBasicBlock *SMBB = Successors.pop_back_val();
6959       if (SMBB->isLandingPad()) {
6960         BB->removeSuccessor(SMBB);
6961         MBBLPads.push_back(SMBB);
6962       }
6963     }
6964
6965     BB->addSuccessor(DispatchBB);
6966
6967     // Find the invoke call and mark all of the callee-saved registers as
6968     // 'implicit defined' so that they're spilled. This prevents code from
6969     // moving instructions to before the EH block, where they will never be
6970     // executed.
6971     for (MachineBasicBlock::reverse_iterator
6972            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6973       if (!II->isCall()) continue;
6974
6975       DenseMap<unsigned, bool> DefRegs;
6976       for (MachineInstr::mop_iterator
6977              OI = II->operands_begin(), OE = II->operands_end();
6978            OI != OE; ++OI) {
6979         if (!OI->isReg()) continue;
6980         DefRegs[OI->getReg()] = true;
6981       }
6982
6983       MachineInstrBuilder MIB(*MF, &*II);
6984
6985       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6986         unsigned Reg = SavedRegs[i];
6987         if (Subtarget->isThumb2() &&
6988             !ARM::tGPRRegClass.contains(Reg) &&
6989             !ARM::hGPRRegClass.contains(Reg))
6990           continue;
6991         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6992           continue;
6993         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6994           continue;
6995         if (!DefRegs[Reg])
6996           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6997       }
6998
6999       break;
7000     }
7001   }
7002
7003   // Mark all former landing pads as non-landing pads. The dispatch is the only
7004   // landing pad now.
7005   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7006          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7007     (*I)->setIsLandingPad(false);
7008
7009   // The instruction is gone now.
7010   MI->eraseFromParent();
7011
7012   return MBB;
7013 }
7014
7015 static
7016 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7017   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7018        E = MBB->succ_end(); I != E; ++I)
7019     if (*I != Succ)
7020       return *I;
7021   llvm_unreachable("Expecting a BB with two successors!");
7022 }
7023
7024 /// Return the load opcode for a given load size. If load size >= 8,
7025 /// neon opcode will be returned.
7026 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7027   if (LdSize >= 8)
7028     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7029                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7030   if (IsThumb1)
7031     return LdSize == 4 ? ARM::tLDRi
7032                        : LdSize == 2 ? ARM::tLDRHi
7033                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7034   if (IsThumb2)
7035     return LdSize == 4 ? ARM::t2LDR_POST
7036                        : LdSize == 2 ? ARM::t2LDRH_POST
7037                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7038   return LdSize == 4 ? ARM::LDR_POST_IMM
7039                      : LdSize == 2 ? ARM::LDRH_POST
7040                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7041 }
7042
7043 /// Return the store opcode for a given store size. If store size >= 8,
7044 /// neon opcode will be returned.
7045 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7046   if (StSize >= 8)
7047     return StSize == 16 ? ARM::VST1q32wb_fixed
7048                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7049   if (IsThumb1)
7050     return StSize == 4 ? ARM::tSTRi
7051                        : StSize == 2 ? ARM::tSTRHi
7052                                      : StSize == 1 ? ARM::tSTRBi : 0;
7053   if (IsThumb2)
7054     return StSize == 4 ? ARM::t2STR_POST
7055                        : StSize == 2 ? ARM::t2STRH_POST
7056                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7057   return StSize == 4 ? ARM::STR_POST_IMM
7058                      : StSize == 2 ? ARM::STRH_POST
7059                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7060 }
7061
7062 /// Emit a post-increment load operation with given size. The instructions
7063 /// will be added to BB at Pos.
7064 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7065                        const TargetInstrInfo *TII, DebugLoc dl,
7066                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7067                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7068   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7069   assert(LdOpc != 0 && "Should have a load opcode");
7070   if (LdSize >= 8) {
7071     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7072                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7073                        .addImm(0));
7074   } else if (IsThumb1) {
7075     // load + update AddrIn
7076     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7077                        .addReg(AddrIn).addImm(0));
7078     MachineInstrBuilder MIB =
7079         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7080     MIB = AddDefaultT1CC(MIB);
7081     MIB.addReg(AddrIn).addImm(LdSize);
7082     AddDefaultPred(MIB);
7083   } else if (IsThumb2) {
7084     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7085                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7086                        .addImm(LdSize));
7087   } else { // arm
7088     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7089                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7090                        .addReg(0).addImm(LdSize));
7091   }
7092 }
7093
7094 /// Emit a post-increment store operation with given size. The instructions
7095 /// will be added to BB at Pos.
7096 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7097                        const TargetInstrInfo *TII, DebugLoc dl,
7098                        unsigned StSize, unsigned Data, unsigned AddrIn,
7099                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7100   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7101   assert(StOpc != 0 && "Should have a store opcode");
7102   if (StSize >= 8) {
7103     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7104                        .addReg(AddrIn).addImm(0).addReg(Data));
7105   } else if (IsThumb1) {
7106     // store + update AddrIn
7107     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7108                        .addReg(AddrIn).addImm(0));
7109     MachineInstrBuilder MIB =
7110         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7111     MIB = AddDefaultT1CC(MIB);
7112     MIB.addReg(AddrIn).addImm(StSize);
7113     AddDefaultPred(MIB);
7114   } else if (IsThumb2) {
7115     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7116                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7117   } else { // arm
7118     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7119                        .addReg(Data).addReg(AddrIn).addReg(0)
7120                        .addImm(StSize));
7121   }
7122 }
7123
7124 MachineBasicBlock *
7125 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7126                                    MachineBasicBlock *BB) const {
7127   // This pseudo instruction has 3 operands: dst, src, size
7128   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7129   // Otherwise, we will generate unrolled scalar copies.
7130   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7131   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7132   MachineFunction::iterator It = BB;
7133   ++It;
7134
7135   unsigned dest = MI->getOperand(0).getReg();
7136   unsigned src = MI->getOperand(1).getReg();
7137   unsigned SizeVal = MI->getOperand(2).getImm();
7138   unsigned Align = MI->getOperand(3).getImm();
7139   DebugLoc dl = MI->getDebugLoc();
7140
7141   MachineFunction *MF = BB->getParent();
7142   MachineRegisterInfo &MRI = MF->getRegInfo();
7143   unsigned UnitSize = 0;
7144   const TargetRegisterClass *TRC = nullptr;
7145   const TargetRegisterClass *VecTRC = nullptr;
7146
7147   bool IsThumb1 = Subtarget->isThumb1Only();
7148   bool IsThumb2 = Subtarget->isThumb2();
7149
7150   if (Align & 1) {
7151     UnitSize = 1;
7152   } else if (Align & 2) {
7153     UnitSize = 2;
7154   } else {
7155     // Check whether we can use NEON instructions.
7156     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7157         Subtarget->hasNEON()) {
7158       if ((Align % 16 == 0) && SizeVal >= 16)
7159         UnitSize = 16;
7160       else if ((Align % 8 == 0) && SizeVal >= 8)
7161         UnitSize = 8;
7162     }
7163     // Can't use NEON instructions.
7164     if (UnitSize == 0)
7165       UnitSize = 4;
7166   }
7167
7168   // Select the correct opcode and register class for unit size load/store
7169   bool IsNeon = UnitSize >= 8;
7170   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7171   if (IsNeon)
7172     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7173                             : UnitSize == 8 ? &ARM::DPRRegClass
7174                                             : nullptr;
7175
7176   unsigned BytesLeft = SizeVal % UnitSize;
7177   unsigned LoopSize = SizeVal - BytesLeft;
7178
7179   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7180     // Use LDR and STR to copy.
7181     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7182     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7183     unsigned srcIn = src;
7184     unsigned destIn = dest;
7185     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7186       unsigned srcOut = MRI.createVirtualRegister(TRC);
7187       unsigned destOut = MRI.createVirtualRegister(TRC);
7188       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7189       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7190                  IsThumb1, IsThumb2);
7191       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7192                  IsThumb1, IsThumb2);
7193       srcIn = srcOut;
7194       destIn = destOut;
7195     }
7196
7197     // Handle the leftover bytes with LDRB and STRB.
7198     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7199     // [destOut] = STRB_POST(scratch, destIn, 1)
7200     for (unsigned i = 0; i < BytesLeft; i++) {
7201       unsigned srcOut = MRI.createVirtualRegister(TRC);
7202       unsigned destOut = MRI.createVirtualRegister(TRC);
7203       unsigned scratch = MRI.createVirtualRegister(TRC);
7204       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7205                  IsThumb1, IsThumb2);
7206       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7207                  IsThumb1, IsThumb2);
7208       srcIn = srcOut;
7209       destIn = destOut;
7210     }
7211     MI->eraseFromParent();   // The instruction is gone now.
7212     return BB;
7213   }
7214
7215   // Expand the pseudo op to a loop.
7216   // thisMBB:
7217   //   ...
7218   //   movw varEnd, # --> with thumb2
7219   //   movt varEnd, #
7220   //   ldrcp varEnd, idx --> without thumb2
7221   //   fallthrough --> loopMBB
7222   // loopMBB:
7223   //   PHI varPhi, varEnd, varLoop
7224   //   PHI srcPhi, src, srcLoop
7225   //   PHI destPhi, dst, destLoop
7226   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7227   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7228   //   subs varLoop, varPhi, #UnitSize
7229   //   bne loopMBB
7230   //   fallthrough --> exitMBB
7231   // exitMBB:
7232   //   epilogue to handle left-over bytes
7233   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7234   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7235   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7236   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7237   MF->insert(It, loopMBB);
7238   MF->insert(It, exitMBB);
7239
7240   // Transfer the remainder of BB and its successor edges to exitMBB.
7241   exitMBB->splice(exitMBB->begin(), BB,
7242                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7243   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7244
7245   // Load an immediate to varEnd.
7246   unsigned varEnd = MRI.createVirtualRegister(TRC);
7247   if (IsThumb2) {
7248     unsigned Vtmp = varEnd;
7249     if ((LoopSize & 0xFFFF0000) != 0)
7250       Vtmp = MRI.createVirtualRegister(TRC);
7251     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7252                        .addImm(LoopSize & 0xFFFF));
7253
7254     if ((LoopSize & 0xFFFF0000) != 0)
7255       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7256                          .addReg(Vtmp).addImm(LoopSize >> 16));
7257   } else {
7258     MachineConstantPool *ConstantPool = MF->getConstantPool();
7259     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7260     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7261
7262     // MachineConstantPool wants an explicit alignment.
7263     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7264     if (Align == 0)
7265       Align = getDataLayout()->getTypeAllocSize(C->getType());
7266     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7267
7268     if (IsThumb1)
7269       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7270           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7271     else
7272       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7273           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7274   }
7275   BB->addSuccessor(loopMBB);
7276
7277   // Generate the loop body:
7278   //   varPhi = PHI(varLoop, varEnd)
7279   //   srcPhi = PHI(srcLoop, src)
7280   //   destPhi = PHI(destLoop, dst)
7281   MachineBasicBlock *entryBB = BB;
7282   BB = loopMBB;
7283   unsigned varLoop = MRI.createVirtualRegister(TRC);
7284   unsigned varPhi = MRI.createVirtualRegister(TRC);
7285   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7286   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7287   unsigned destLoop = MRI.createVirtualRegister(TRC);
7288   unsigned destPhi = MRI.createVirtualRegister(TRC);
7289
7290   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7291     .addReg(varLoop).addMBB(loopMBB)
7292     .addReg(varEnd).addMBB(entryBB);
7293   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7294     .addReg(srcLoop).addMBB(loopMBB)
7295     .addReg(src).addMBB(entryBB);
7296   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7297     .addReg(destLoop).addMBB(loopMBB)
7298     .addReg(dest).addMBB(entryBB);
7299
7300   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7301   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7302   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7303   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7304              IsThumb1, IsThumb2);
7305   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7306              IsThumb1, IsThumb2);
7307
7308   // Decrement loop variable by UnitSize.
7309   if (IsThumb1) {
7310     MachineInstrBuilder MIB =
7311         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7312     MIB = AddDefaultT1CC(MIB);
7313     MIB.addReg(varPhi).addImm(UnitSize);
7314     AddDefaultPred(MIB);
7315   } else {
7316     MachineInstrBuilder MIB =
7317         BuildMI(*BB, BB->end(), dl,
7318                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7319     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7320     MIB->getOperand(5).setReg(ARM::CPSR);
7321     MIB->getOperand(5).setIsDef(true);
7322   }
7323   BuildMI(*BB, BB->end(), dl,
7324           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7325       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7326
7327   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7328   BB->addSuccessor(loopMBB);
7329   BB->addSuccessor(exitMBB);
7330
7331   // Add epilogue to handle BytesLeft.
7332   BB = exitMBB;
7333   MachineInstr *StartOfExit = exitMBB->begin();
7334
7335   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7336   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7337   unsigned srcIn = srcLoop;
7338   unsigned destIn = destLoop;
7339   for (unsigned i = 0; i < BytesLeft; i++) {
7340     unsigned srcOut = MRI.createVirtualRegister(TRC);
7341     unsigned destOut = MRI.createVirtualRegister(TRC);
7342     unsigned scratch = MRI.createVirtualRegister(TRC);
7343     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7344                IsThumb1, IsThumb2);
7345     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7346                IsThumb1, IsThumb2);
7347     srcIn = srcOut;
7348     destIn = destOut;
7349   }
7350
7351   MI->eraseFromParent();   // The instruction is gone now.
7352   return BB;
7353 }
7354
7355 MachineBasicBlock *
7356 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7357                                        MachineBasicBlock *MBB) const {
7358   const TargetMachine &TM = getTargetMachine();
7359   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7360   DebugLoc DL = MI->getDebugLoc();
7361
7362   assert(Subtarget->isTargetWindows() &&
7363          "__chkstk is only supported on Windows");
7364   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7365
7366   // __chkstk takes the number of words to allocate on the stack in R4, and
7367   // returns the stack adjustment in number of bytes in R4.  This will not
7368   // clober any other registers (other than the obvious lr).
7369   //
7370   // Although, technically, IP should be considered a register which may be
7371   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7372   // thumb-2 environment, so there is no interworking required.  As a result, we
7373   // do not expect a veneer to be emitted by the linker, clobbering IP.
7374   //
7375   // Each module receives its own copy of __chkstk, so no import thunk is
7376   // required, again, ensuring that IP is not clobbered.
7377   //
7378   // Finally, although some linkers may theoretically provide a trampoline for
7379   // out of range calls (which is quite common due to a 32M range limitation of
7380   // branches for Thumb), we can generate the long-call version via
7381   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7382   // IP.
7383
7384   switch (TM.getCodeModel()) {
7385   case CodeModel::Small:
7386   case CodeModel::Medium:
7387   case CodeModel::Default:
7388   case CodeModel::Kernel:
7389     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7390       .addImm((unsigned)ARMCC::AL).addReg(0)
7391       .addExternalSymbol("__chkstk")
7392       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7393       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7394       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7395     break;
7396   case CodeModel::Large:
7397   case CodeModel::JITDefault: {
7398     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7399     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7400
7401     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7402       .addExternalSymbol("__chkstk");
7403     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7404       .addImm((unsigned)ARMCC::AL).addReg(0)
7405       .addReg(Reg, RegState::Kill)
7406       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7407       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7408       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7409     break;
7410   }
7411   }
7412
7413   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7414                                       ARM::SP)
7415                               .addReg(ARM::SP).addReg(ARM::R4)));
7416
7417   MI->eraseFromParent();
7418   return MBB;
7419 }
7420
7421 MachineBasicBlock *
7422 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7423                                                MachineBasicBlock *BB) const {
7424   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7425   DebugLoc dl = MI->getDebugLoc();
7426   bool isThumb2 = Subtarget->isThumb2();
7427   switch (MI->getOpcode()) {
7428   default: {
7429     MI->dump();
7430     llvm_unreachable("Unexpected instr type to insert");
7431   }
7432   // The Thumb2 pre-indexed stores have the same MI operands, they just
7433   // define them differently in the .td files from the isel patterns, so
7434   // they need pseudos.
7435   case ARM::t2STR_preidx:
7436     MI->setDesc(TII->get(ARM::t2STR_PRE));
7437     return BB;
7438   case ARM::t2STRB_preidx:
7439     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7440     return BB;
7441   case ARM::t2STRH_preidx:
7442     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7443     return BB;
7444
7445   case ARM::STRi_preidx:
7446   case ARM::STRBi_preidx: {
7447     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7448       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7449     // Decode the offset.
7450     unsigned Offset = MI->getOperand(4).getImm();
7451     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7452     Offset = ARM_AM::getAM2Offset(Offset);
7453     if (isSub)
7454       Offset = -Offset;
7455
7456     MachineMemOperand *MMO = *MI->memoperands_begin();
7457     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7458       .addOperand(MI->getOperand(0))  // Rn_wb
7459       .addOperand(MI->getOperand(1))  // Rt
7460       .addOperand(MI->getOperand(2))  // Rn
7461       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7462       .addOperand(MI->getOperand(5))  // pred
7463       .addOperand(MI->getOperand(6))
7464       .addMemOperand(MMO);
7465     MI->eraseFromParent();
7466     return BB;
7467   }
7468   case ARM::STRr_preidx:
7469   case ARM::STRBr_preidx:
7470   case ARM::STRH_preidx: {
7471     unsigned NewOpc;
7472     switch (MI->getOpcode()) {
7473     default: llvm_unreachable("unexpected opcode!");
7474     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7475     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7476     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7477     }
7478     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7479     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7480       MIB.addOperand(MI->getOperand(i));
7481     MI->eraseFromParent();
7482     return BB;
7483   }
7484
7485   case ARM::tMOVCCr_pseudo: {
7486     // To "insert" a SELECT_CC instruction, we actually have to insert the
7487     // diamond control-flow pattern.  The incoming instruction knows the
7488     // destination vreg to set, the condition code register to branch on, the
7489     // true/false values to select between, and a branch opcode to use.
7490     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7491     MachineFunction::iterator It = BB;
7492     ++It;
7493
7494     //  thisMBB:
7495     //  ...
7496     //   TrueVal = ...
7497     //   cmpTY ccX, r1, r2
7498     //   bCC copy1MBB
7499     //   fallthrough --> copy0MBB
7500     MachineBasicBlock *thisMBB  = BB;
7501     MachineFunction *F = BB->getParent();
7502     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7503     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7504     F->insert(It, copy0MBB);
7505     F->insert(It, sinkMBB);
7506
7507     // Transfer the remainder of BB and its successor edges to sinkMBB.
7508     sinkMBB->splice(sinkMBB->begin(), BB,
7509                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7510     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7511
7512     BB->addSuccessor(copy0MBB);
7513     BB->addSuccessor(sinkMBB);
7514
7515     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7516       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7517
7518     //  copy0MBB:
7519     //   %FalseValue = ...
7520     //   # fallthrough to sinkMBB
7521     BB = copy0MBB;
7522
7523     // Update machine-CFG edges
7524     BB->addSuccessor(sinkMBB);
7525
7526     //  sinkMBB:
7527     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7528     //  ...
7529     BB = sinkMBB;
7530     BuildMI(*BB, BB->begin(), dl,
7531             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7532       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7533       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7534
7535     MI->eraseFromParent();   // The pseudo instruction is gone now.
7536     return BB;
7537   }
7538
7539   case ARM::BCCi64:
7540   case ARM::BCCZi64: {
7541     // If there is an unconditional branch to the other successor, remove it.
7542     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7543
7544     // Compare both parts that make up the double comparison separately for
7545     // equality.
7546     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7547
7548     unsigned LHS1 = MI->getOperand(1).getReg();
7549     unsigned LHS2 = MI->getOperand(2).getReg();
7550     if (RHSisZero) {
7551       AddDefaultPred(BuildMI(BB, dl,
7552                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7553                      .addReg(LHS1).addImm(0));
7554       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7555         .addReg(LHS2).addImm(0)
7556         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7557     } else {
7558       unsigned RHS1 = MI->getOperand(3).getReg();
7559       unsigned RHS2 = MI->getOperand(4).getReg();
7560       AddDefaultPred(BuildMI(BB, dl,
7561                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7562                      .addReg(LHS1).addReg(RHS1));
7563       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7564         .addReg(LHS2).addReg(RHS2)
7565         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7566     }
7567
7568     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7569     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7570     if (MI->getOperand(0).getImm() == ARMCC::NE)
7571       std::swap(destMBB, exitMBB);
7572
7573     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7574       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7575     if (isThumb2)
7576       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7577     else
7578       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7579
7580     MI->eraseFromParent();   // The pseudo instruction is gone now.
7581     return BB;
7582   }
7583
7584   case ARM::Int_eh_sjlj_setjmp:
7585   case ARM::Int_eh_sjlj_setjmp_nofp:
7586   case ARM::tInt_eh_sjlj_setjmp:
7587   case ARM::t2Int_eh_sjlj_setjmp:
7588   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7589     EmitSjLjDispatchBlock(MI, BB);
7590     return BB;
7591
7592   case ARM::ABS:
7593   case ARM::t2ABS: {
7594     // To insert an ABS instruction, we have to insert the
7595     // diamond control-flow pattern.  The incoming instruction knows the
7596     // source vreg to test against 0, the destination vreg to set,
7597     // the condition code register to branch on, the
7598     // true/false values to select between, and a branch opcode to use.
7599     // It transforms
7600     //     V1 = ABS V0
7601     // into
7602     //     V2 = MOVS V0
7603     //     BCC                      (branch to SinkBB if V0 >= 0)
7604     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7605     //     SinkBB: V1 = PHI(V2, V3)
7606     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7607     MachineFunction::iterator BBI = BB;
7608     ++BBI;
7609     MachineFunction *Fn = BB->getParent();
7610     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7611     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7612     Fn->insert(BBI, RSBBB);
7613     Fn->insert(BBI, SinkBB);
7614
7615     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7616     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7617     bool isThumb2 = Subtarget->isThumb2();
7618     MachineRegisterInfo &MRI = Fn->getRegInfo();
7619     // In Thumb mode S must not be specified if source register is the SP or
7620     // PC and if destination register is the SP, so restrict register class
7621     unsigned NewRsbDstReg =
7622       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7623
7624     // Transfer the remainder of BB and its successor edges to sinkMBB.
7625     SinkBB->splice(SinkBB->begin(), BB,
7626                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7627     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7628
7629     BB->addSuccessor(RSBBB);
7630     BB->addSuccessor(SinkBB);
7631
7632     // fall through to SinkMBB
7633     RSBBB->addSuccessor(SinkBB);
7634
7635     // insert a cmp at the end of BB
7636     AddDefaultPred(BuildMI(BB, dl,
7637                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7638                    .addReg(ABSSrcReg).addImm(0));
7639
7640     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7641     BuildMI(BB, dl,
7642       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7643       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7644
7645     // insert rsbri in RSBBB
7646     // Note: BCC and rsbri will be converted into predicated rsbmi
7647     // by if-conversion pass
7648     BuildMI(*RSBBB, RSBBB->begin(), dl,
7649       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7650       .addReg(ABSSrcReg, RegState::Kill)
7651       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7652
7653     // insert PHI in SinkBB,
7654     // reuse ABSDstReg to not change uses of ABS instruction
7655     BuildMI(*SinkBB, SinkBB->begin(), dl,
7656       TII->get(ARM::PHI), ABSDstReg)
7657       .addReg(NewRsbDstReg).addMBB(RSBBB)
7658       .addReg(ABSSrcReg).addMBB(BB);
7659
7660     // remove ABS instruction
7661     MI->eraseFromParent();
7662
7663     // return last added BB
7664     return SinkBB;
7665   }
7666   case ARM::COPY_STRUCT_BYVAL_I32:
7667     ++NumLoopByVals;
7668     return EmitStructByval(MI, BB);
7669   case ARM::WIN__CHKSTK:
7670     return EmitLowered__chkstk(MI, BB);
7671   }
7672 }
7673
7674 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7675                                                       SDNode *Node) const {
7676   const MCInstrDesc *MCID = &MI->getDesc();
7677   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7678   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7679   // operand is still set to noreg. If needed, set the optional operand's
7680   // register to CPSR, and remove the redundant implicit def.
7681   //
7682   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7683
7684   // Rename pseudo opcodes.
7685   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7686   if (NewOpc) {
7687     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7688     MCID = &TII->get(NewOpc);
7689
7690     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7691            "converted opcode should be the same except for cc_out");
7692
7693     MI->setDesc(*MCID);
7694
7695     // Add the optional cc_out operand
7696     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7697   }
7698   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7699
7700   // Any ARM instruction that sets the 's' bit should specify an optional
7701   // "cc_out" operand in the last operand position.
7702   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7703     assert(!NewOpc && "Optional cc_out operand required");
7704     return;
7705   }
7706   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7707   // since we already have an optional CPSR def.
7708   bool definesCPSR = false;
7709   bool deadCPSR = false;
7710   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7711        i != e; ++i) {
7712     const MachineOperand &MO = MI->getOperand(i);
7713     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7714       definesCPSR = true;
7715       if (MO.isDead())
7716         deadCPSR = true;
7717       MI->RemoveOperand(i);
7718       break;
7719     }
7720   }
7721   if (!definesCPSR) {
7722     assert(!NewOpc && "Optional cc_out operand required");
7723     return;
7724   }
7725   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7726   if (deadCPSR) {
7727     assert(!MI->getOperand(ccOutIdx).getReg() &&
7728            "expect uninitialized optional cc_out operand");
7729     return;
7730   }
7731
7732   // If this instruction was defined with an optional CPSR def and its dag node
7733   // had a live implicit CPSR def, then activate the optional CPSR def.
7734   MachineOperand &MO = MI->getOperand(ccOutIdx);
7735   MO.setReg(ARM::CPSR);
7736   MO.setIsDef(true);
7737 }
7738
7739 //===----------------------------------------------------------------------===//
7740 //                           ARM Optimization Hooks
7741 //===----------------------------------------------------------------------===//
7742
7743 // Helper function that checks if N is a null or all ones constant.
7744 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7745   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7746   if (!C)
7747     return false;
7748   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7749 }
7750
7751 // Return true if N is conditionally 0 or all ones.
7752 // Detects these expressions where cc is an i1 value:
7753 //
7754 //   (select cc 0, y)   [AllOnes=0]
7755 //   (select cc y, 0)   [AllOnes=0]
7756 //   (zext cc)          [AllOnes=0]
7757 //   (sext cc)          [AllOnes=0/1]
7758 //   (select cc -1, y)  [AllOnes=1]
7759 //   (select cc y, -1)  [AllOnes=1]
7760 //
7761 // Invert is set when N is the null/all ones constant when CC is false.
7762 // OtherOp is set to the alternative value of N.
7763 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7764                                        SDValue &CC, bool &Invert,
7765                                        SDValue &OtherOp,
7766                                        SelectionDAG &DAG) {
7767   switch (N->getOpcode()) {
7768   default: return false;
7769   case ISD::SELECT: {
7770     CC = N->getOperand(0);
7771     SDValue N1 = N->getOperand(1);
7772     SDValue N2 = N->getOperand(2);
7773     if (isZeroOrAllOnes(N1, AllOnes)) {
7774       Invert = false;
7775       OtherOp = N2;
7776       return true;
7777     }
7778     if (isZeroOrAllOnes(N2, AllOnes)) {
7779       Invert = true;
7780       OtherOp = N1;
7781       return true;
7782     }
7783     return false;
7784   }
7785   case ISD::ZERO_EXTEND:
7786     // (zext cc) can never be the all ones value.
7787     if (AllOnes)
7788       return false;
7789     // Fall through.
7790   case ISD::SIGN_EXTEND: {
7791     EVT VT = N->getValueType(0);
7792     CC = N->getOperand(0);
7793     if (CC.getValueType() != MVT::i1)
7794       return false;
7795     Invert = !AllOnes;
7796     if (AllOnes)
7797       // When looking for an AllOnes constant, N is an sext, and the 'other'
7798       // value is 0.
7799       OtherOp = DAG.getConstant(0, VT);
7800     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7801       // When looking for a 0 constant, N can be zext or sext.
7802       OtherOp = DAG.getConstant(1, VT);
7803     else
7804       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7805     return true;
7806   }
7807   }
7808 }
7809
7810 // Combine a constant select operand into its use:
7811 //
7812 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7813 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7814 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7815 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7816 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7817 //
7818 // The transform is rejected if the select doesn't have a constant operand that
7819 // is null, or all ones when AllOnes is set.
7820 //
7821 // Also recognize sext/zext from i1:
7822 //
7823 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7824 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7825 //
7826 // These transformations eventually create predicated instructions.
7827 //
7828 // @param N       The node to transform.
7829 // @param Slct    The N operand that is a select.
7830 // @param OtherOp The other N operand (x above).
7831 // @param DCI     Context.
7832 // @param AllOnes Require the select constant to be all ones instead of null.
7833 // @returns The new node, or SDValue() on failure.
7834 static
7835 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7836                             TargetLowering::DAGCombinerInfo &DCI,
7837                             bool AllOnes = false) {
7838   SelectionDAG &DAG = DCI.DAG;
7839   EVT VT = N->getValueType(0);
7840   SDValue NonConstantVal;
7841   SDValue CCOp;
7842   bool SwapSelectOps;
7843   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7844                                   NonConstantVal, DAG))
7845     return SDValue();
7846
7847   // Slct is now know to be the desired identity constant when CC is true.
7848   SDValue TrueVal = OtherOp;
7849   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7850                                  OtherOp, NonConstantVal);
7851   // Unless SwapSelectOps says CC should be false.
7852   if (SwapSelectOps)
7853     std::swap(TrueVal, FalseVal);
7854
7855   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7856                      CCOp, TrueVal, FalseVal);
7857 }
7858
7859 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7860 static
7861 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7862                                        TargetLowering::DAGCombinerInfo &DCI) {
7863   SDValue N0 = N->getOperand(0);
7864   SDValue N1 = N->getOperand(1);
7865   if (N0.getNode()->hasOneUse()) {
7866     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7867     if (Result.getNode())
7868       return Result;
7869   }
7870   if (N1.getNode()->hasOneUse()) {
7871     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7872     if (Result.getNode())
7873       return Result;
7874   }
7875   return SDValue();
7876 }
7877
7878 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7879 // (only after legalization).
7880 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7881                                  TargetLowering::DAGCombinerInfo &DCI,
7882                                  const ARMSubtarget *Subtarget) {
7883
7884   // Only perform optimization if after legalize, and if NEON is available. We
7885   // also expected both operands to be BUILD_VECTORs.
7886   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7887       || N0.getOpcode() != ISD::BUILD_VECTOR
7888       || N1.getOpcode() != ISD::BUILD_VECTOR)
7889     return SDValue();
7890
7891   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7892   EVT VT = N->getValueType(0);
7893   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7894     return SDValue();
7895
7896   // Check that the vector operands are of the right form.
7897   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7898   // operands, where N is the size of the formed vector.
7899   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7900   // index such that we have a pair wise add pattern.
7901
7902   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7903   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7904     return SDValue();
7905   SDValue Vec = N0->getOperand(0)->getOperand(0);
7906   SDNode *V = Vec.getNode();
7907   unsigned nextIndex = 0;
7908
7909   // For each operands to the ADD which are BUILD_VECTORs,
7910   // check to see if each of their operands are an EXTRACT_VECTOR with
7911   // the same vector and appropriate index.
7912   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7913     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7914         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7915
7916       SDValue ExtVec0 = N0->getOperand(i);
7917       SDValue ExtVec1 = N1->getOperand(i);
7918
7919       // First operand is the vector, verify its the same.
7920       if (V != ExtVec0->getOperand(0).getNode() ||
7921           V != ExtVec1->getOperand(0).getNode())
7922         return SDValue();
7923
7924       // Second is the constant, verify its correct.
7925       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7926       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7927
7928       // For the constant, we want to see all the even or all the odd.
7929       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7930           || C1->getZExtValue() != nextIndex+1)
7931         return SDValue();
7932
7933       // Increment index.
7934       nextIndex+=2;
7935     } else
7936       return SDValue();
7937   }
7938
7939   // Create VPADDL node.
7940   SelectionDAG &DAG = DCI.DAG;
7941   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7942
7943   // Build operand list.
7944   SmallVector<SDValue, 8> Ops;
7945   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7946                                 TLI.getPointerTy()));
7947
7948   // Input is the vector.
7949   Ops.push_back(Vec);
7950
7951   // Get widened type and narrowed type.
7952   MVT widenType;
7953   unsigned numElem = VT.getVectorNumElements();
7954   
7955   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7956   switch (inputLaneType.getSimpleVT().SimpleTy) {
7957     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7958     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7959     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7960     default:
7961       llvm_unreachable("Invalid vector element type for padd optimization.");
7962   }
7963
7964   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7965   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7966   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7967 }
7968
7969 static SDValue findMUL_LOHI(SDValue V) {
7970   if (V->getOpcode() == ISD::UMUL_LOHI ||
7971       V->getOpcode() == ISD::SMUL_LOHI)
7972     return V;
7973   return SDValue();
7974 }
7975
7976 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7977                                      TargetLowering::DAGCombinerInfo &DCI,
7978                                      const ARMSubtarget *Subtarget) {
7979
7980   if (Subtarget->isThumb1Only()) return SDValue();
7981
7982   // Only perform the checks after legalize when the pattern is available.
7983   if (DCI.isBeforeLegalize()) return SDValue();
7984
7985   // Look for multiply add opportunities.
7986   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7987   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7988   // a glue link from the first add to the second add.
7989   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7990   // a S/UMLAL instruction.
7991   //          loAdd   UMUL_LOHI
7992   //            \    / :lo    \ :hi
7993   //             \  /          \          [no multiline comment]
7994   //              ADDC         |  hiAdd
7995   //                 \ :glue  /  /
7996   //                  \      /  /
7997   //                    ADDE
7998   //
7999   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8000   SDValue AddcOp0 = AddcNode->getOperand(0);
8001   SDValue AddcOp1 = AddcNode->getOperand(1);
8002
8003   // Check if the two operands are from the same mul_lohi node.
8004   if (AddcOp0.getNode() == AddcOp1.getNode())
8005     return SDValue();
8006
8007   assert(AddcNode->getNumValues() == 2 &&
8008          AddcNode->getValueType(0) == MVT::i32 &&
8009          "Expect ADDC with two result values. First: i32");
8010
8011   // Check that we have a glued ADDC node.
8012   if (AddcNode->getValueType(1) != MVT::Glue)
8013     return SDValue();
8014
8015   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8016   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8017       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8018       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8019       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8020     return SDValue();
8021
8022   // Look for the glued ADDE.
8023   SDNode* AddeNode = AddcNode->getGluedUser();
8024   if (!AddeNode)
8025     return SDValue();
8026
8027   // Make sure it is really an ADDE.
8028   if (AddeNode->getOpcode() != ISD::ADDE)
8029     return SDValue();
8030
8031   assert(AddeNode->getNumOperands() == 3 &&
8032          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8033          "ADDE node has the wrong inputs");
8034
8035   // Check for the triangle shape.
8036   SDValue AddeOp0 = AddeNode->getOperand(0);
8037   SDValue AddeOp1 = AddeNode->getOperand(1);
8038
8039   // Make sure that the ADDE operands are not coming from the same node.
8040   if (AddeOp0.getNode() == AddeOp1.getNode())
8041     return SDValue();
8042
8043   // Find the MUL_LOHI node walking up ADDE's operands.
8044   bool IsLeftOperandMUL = false;
8045   SDValue MULOp = findMUL_LOHI(AddeOp0);
8046   if (MULOp == SDValue())
8047    MULOp = findMUL_LOHI(AddeOp1);
8048   else
8049     IsLeftOperandMUL = true;
8050   if (MULOp == SDValue())
8051     return SDValue();
8052
8053   // Figure out the right opcode.
8054   unsigned Opc = MULOp->getOpcode();
8055   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8056
8057   // Figure out the high and low input values to the MLAL node.
8058   SDValue* HiAdd = nullptr;
8059   SDValue* LoMul = nullptr;
8060   SDValue* LowAdd = nullptr;
8061
8062   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8063   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8064     return SDValue();
8065
8066   if (IsLeftOperandMUL)
8067     HiAdd = &AddeOp1;
8068   else
8069     HiAdd = &AddeOp0;
8070
8071
8072   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8073   // whose low result is fed to the ADDC we are checking.
8074
8075   if (AddcOp0 == MULOp.getValue(0)) {
8076     LoMul = &AddcOp0;
8077     LowAdd = &AddcOp1;
8078   }
8079   if (AddcOp1 == MULOp.getValue(0)) {
8080     LoMul = &AddcOp1;
8081     LowAdd = &AddcOp0;
8082   }
8083
8084   if (!LoMul)
8085     return SDValue();
8086
8087   // Create the merged node.
8088   SelectionDAG &DAG = DCI.DAG;
8089
8090   // Build operand list.
8091   SmallVector<SDValue, 8> Ops;
8092   Ops.push_back(LoMul->getOperand(0));
8093   Ops.push_back(LoMul->getOperand(1));
8094   Ops.push_back(*LowAdd);
8095   Ops.push_back(*HiAdd);
8096
8097   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8098                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8099
8100   // Replace the ADDs' nodes uses by the MLA node's values.
8101   SDValue HiMLALResult(MLALNode.getNode(), 1);
8102   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8103
8104   SDValue LoMLALResult(MLALNode.getNode(), 0);
8105   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8106
8107   // Return original node to notify the driver to stop replacing.
8108   SDValue resNode(AddcNode, 0);
8109   return resNode;
8110 }
8111
8112 /// PerformADDCCombine - Target-specific dag combine transform from
8113 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8114 static SDValue PerformADDCCombine(SDNode *N,
8115                                  TargetLowering::DAGCombinerInfo &DCI,
8116                                  const ARMSubtarget *Subtarget) {
8117
8118   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8119
8120 }
8121
8122 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8123 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8124 /// called with the default operands, and if that fails, with commuted
8125 /// operands.
8126 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8127                                           TargetLowering::DAGCombinerInfo &DCI,
8128                                           const ARMSubtarget *Subtarget){
8129
8130   // Attempt to create vpaddl for this add.
8131   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8132   if (Result.getNode())
8133     return Result;
8134
8135   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8136   if (N0.getNode()->hasOneUse()) {
8137     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8138     if (Result.getNode()) return Result;
8139   }
8140   return SDValue();
8141 }
8142
8143 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8144 ///
8145 static SDValue PerformADDCombine(SDNode *N,
8146                                  TargetLowering::DAGCombinerInfo &DCI,
8147                                  const ARMSubtarget *Subtarget) {
8148   SDValue N0 = N->getOperand(0);
8149   SDValue N1 = N->getOperand(1);
8150
8151   // First try with the default operand order.
8152   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8153   if (Result.getNode())
8154     return Result;
8155
8156   // If that didn't work, try again with the operands commuted.
8157   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8158 }
8159
8160 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8161 ///
8162 static SDValue PerformSUBCombine(SDNode *N,
8163                                  TargetLowering::DAGCombinerInfo &DCI) {
8164   SDValue N0 = N->getOperand(0);
8165   SDValue N1 = N->getOperand(1);
8166
8167   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8168   if (N1.getNode()->hasOneUse()) {
8169     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8170     if (Result.getNode()) return Result;
8171   }
8172
8173   return SDValue();
8174 }
8175
8176 /// PerformVMULCombine
8177 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8178 /// special multiplier accumulator forwarding.
8179 ///   vmul d3, d0, d2
8180 ///   vmla d3, d1, d2
8181 /// is faster than
8182 ///   vadd d3, d0, d1
8183 ///   vmul d3, d3, d2
8184 //  However, for (A + B) * (A + B),
8185 //    vadd d2, d0, d1
8186 //    vmul d3, d0, d2
8187 //    vmla d3, d1, d2
8188 //  is slower than
8189 //    vadd d2, d0, d1
8190 //    vmul d3, d2, d2
8191 static SDValue PerformVMULCombine(SDNode *N,
8192                                   TargetLowering::DAGCombinerInfo &DCI,
8193                                   const ARMSubtarget *Subtarget) {
8194   if (!Subtarget->hasVMLxForwarding())
8195     return SDValue();
8196
8197   SelectionDAG &DAG = DCI.DAG;
8198   SDValue N0 = N->getOperand(0);
8199   SDValue N1 = N->getOperand(1);
8200   unsigned Opcode = N0.getOpcode();
8201   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8202       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8203     Opcode = N1.getOpcode();
8204     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8205         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8206       return SDValue();
8207     std::swap(N0, N1);
8208   }
8209
8210   if (N0 == N1)
8211     return SDValue();
8212
8213   EVT VT = N->getValueType(0);
8214   SDLoc DL(N);
8215   SDValue N00 = N0->getOperand(0);
8216   SDValue N01 = N0->getOperand(1);
8217   return DAG.getNode(Opcode, DL, VT,
8218                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8219                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8220 }
8221
8222 static SDValue PerformMULCombine(SDNode *N,
8223                                  TargetLowering::DAGCombinerInfo &DCI,
8224                                  const ARMSubtarget *Subtarget) {
8225   SelectionDAG &DAG = DCI.DAG;
8226
8227   if (Subtarget->isThumb1Only())
8228     return SDValue();
8229
8230   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8231     return SDValue();
8232
8233   EVT VT = N->getValueType(0);
8234   if (VT.is64BitVector() || VT.is128BitVector())
8235     return PerformVMULCombine(N, DCI, Subtarget);
8236   if (VT != MVT::i32)
8237     return SDValue();
8238
8239   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8240   if (!C)
8241     return SDValue();
8242
8243   int64_t MulAmt = C->getSExtValue();
8244   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8245
8246   ShiftAmt = ShiftAmt & (32 - 1);
8247   SDValue V = N->getOperand(0);
8248   SDLoc DL(N);
8249
8250   SDValue Res;
8251   MulAmt >>= ShiftAmt;
8252
8253   if (MulAmt >= 0) {
8254     if (isPowerOf2_32(MulAmt - 1)) {
8255       // (mul x, 2^N + 1) => (add (shl x, N), x)
8256       Res = DAG.getNode(ISD::ADD, DL, VT,
8257                         V,
8258                         DAG.getNode(ISD::SHL, DL, VT,
8259                                     V,
8260                                     DAG.getConstant(Log2_32(MulAmt - 1),
8261                                                     MVT::i32)));
8262     } else if (isPowerOf2_32(MulAmt + 1)) {
8263       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8264       Res = DAG.getNode(ISD::SUB, DL, VT,
8265                         DAG.getNode(ISD::SHL, DL, VT,
8266                                     V,
8267                                     DAG.getConstant(Log2_32(MulAmt + 1),
8268                                                     MVT::i32)),
8269                         V);
8270     } else
8271       return SDValue();
8272   } else {
8273     uint64_t MulAmtAbs = -MulAmt;
8274     if (isPowerOf2_32(MulAmtAbs + 1)) {
8275       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8276       Res = DAG.getNode(ISD::SUB, DL, VT,
8277                         V,
8278                         DAG.getNode(ISD::SHL, DL, VT,
8279                                     V,
8280                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8281                                                     MVT::i32)));
8282     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8283       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8284       Res = DAG.getNode(ISD::ADD, DL, VT,
8285                         V,
8286                         DAG.getNode(ISD::SHL, DL, VT,
8287                                     V,
8288                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8289                                                     MVT::i32)));
8290       Res = DAG.getNode(ISD::SUB, DL, VT,
8291                         DAG.getConstant(0, MVT::i32),Res);
8292
8293     } else
8294       return SDValue();
8295   }
8296
8297   if (ShiftAmt != 0)
8298     Res = DAG.getNode(ISD::SHL, DL, VT,
8299                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8300
8301   // Do not add new nodes to DAG combiner worklist.
8302   DCI.CombineTo(N, Res, false);
8303   return SDValue();
8304 }
8305
8306 static SDValue PerformANDCombine(SDNode *N,
8307                                  TargetLowering::DAGCombinerInfo &DCI,
8308                                  const ARMSubtarget *Subtarget) {
8309
8310   // Attempt to use immediate-form VBIC
8311   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8312   SDLoc dl(N);
8313   EVT VT = N->getValueType(0);
8314   SelectionDAG &DAG = DCI.DAG;
8315
8316   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8317     return SDValue();
8318
8319   APInt SplatBits, SplatUndef;
8320   unsigned SplatBitSize;
8321   bool HasAnyUndefs;
8322   if (BVN &&
8323       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8324     if (SplatBitSize <= 64) {
8325       EVT VbicVT;
8326       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8327                                       SplatUndef.getZExtValue(), SplatBitSize,
8328                                       DAG, VbicVT, VT.is128BitVector(),
8329                                       OtherModImm);
8330       if (Val.getNode()) {
8331         SDValue Input =
8332           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8333         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8334         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8335       }
8336     }
8337   }
8338
8339   if (!Subtarget->isThumb1Only()) {
8340     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8341     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8342     if (Result.getNode())
8343       return Result;
8344   }
8345
8346   return SDValue();
8347 }
8348
8349 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8350 static SDValue PerformORCombine(SDNode *N,
8351                                 TargetLowering::DAGCombinerInfo &DCI,
8352                                 const ARMSubtarget *Subtarget) {
8353   // Attempt to use immediate-form VORR
8354   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8355   SDLoc dl(N);
8356   EVT VT = N->getValueType(0);
8357   SelectionDAG &DAG = DCI.DAG;
8358
8359   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8360     return SDValue();
8361
8362   APInt SplatBits, SplatUndef;
8363   unsigned SplatBitSize;
8364   bool HasAnyUndefs;
8365   if (BVN && Subtarget->hasNEON() &&
8366       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8367     if (SplatBitSize <= 64) {
8368       EVT VorrVT;
8369       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8370                                       SplatUndef.getZExtValue(), SplatBitSize,
8371                                       DAG, VorrVT, VT.is128BitVector(),
8372                                       OtherModImm);
8373       if (Val.getNode()) {
8374         SDValue Input =
8375           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8376         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8377         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8378       }
8379     }
8380   }
8381
8382   if (!Subtarget->isThumb1Only()) {
8383     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8384     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8385     if (Result.getNode())
8386       return Result;
8387   }
8388
8389   // The code below optimizes (or (and X, Y), Z).
8390   // The AND operand needs to have a single user to make these optimizations
8391   // profitable.
8392   SDValue N0 = N->getOperand(0);
8393   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8394     return SDValue();
8395   SDValue N1 = N->getOperand(1);
8396
8397   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8398   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8399       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8400     APInt SplatUndef;
8401     unsigned SplatBitSize;
8402     bool HasAnyUndefs;
8403
8404     APInt SplatBits0, SplatBits1;
8405     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8406     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8407     // Ensure that the second operand of both ands are constants
8408     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8409                                       HasAnyUndefs) && !HasAnyUndefs) {
8410         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8411                                           HasAnyUndefs) && !HasAnyUndefs) {
8412             // Ensure that the bit width of the constants are the same and that
8413             // the splat arguments are logical inverses as per the pattern we
8414             // are trying to simplify.
8415             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8416                 SplatBits0 == ~SplatBits1) {
8417                 // Canonicalize the vector type to make instruction selection
8418                 // simpler.
8419                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8420                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8421                                              N0->getOperand(1),
8422                                              N0->getOperand(0),
8423                                              N1->getOperand(0));
8424                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8425             }
8426         }
8427     }
8428   }
8429
8430   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8431   // reasonable.
8432
8433   // BFI is only available on V6T2+
8434   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8435     return SDValue();
8436
8437   SDLoc DL(N);
8438   // 1) or (and A, mask), val => ARMbfi A, val, mask
8439   //      iff (val & mask) == val
8440   //
8441   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8442   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8443   //          && mask == ~mask2
8444   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8445   //          && ~mask == mask2
8446   //  (i.e., copy a bitfield value into another bitfield of the same width)
8447
8448   if (VT != MVT::i32)
8449     return SDValue();
8450
8451   SDValue N00 = N0.getOperand(0);
8452
8453   // The value and the mask need to be constants so we can verify this is
8454   // actually a bitfield set. If the mask is 0xffff, we can do better
8455   // via a movt instruction, so don't use BFI in that case.
8456   SDValue MaskOp = N0.getOperand(1);
8457   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8458   if (!MaskC)
8459     return SDValue();
8460   unsigned Mask = MaskC->getZExtValue();
8461   if (Mask == 0xffff)
8462     return SDValue();
8463   SDValue Res;
8464   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8465   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8466   if (N1C) {
8467     unsigned Val = N1C->getZExtValue();
8468     if ((Val & ~Mask) != Val)
8469       return SDValue();
8470
8471     if (ARM::isBitFieldInvertedMask(Mask)) {
8472       Val >>= countTrailingZeros(~Mask);
8473
8474       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8475                         DAG.getConstant(Val, MVT::i32),
8476                         DAG.getConstant(Mask, MVT::i32));
8477
8478       // Do not add new nodes to DAG combiner worklist.
8479       DCI.CombineTo(N, Res, false);
8480       return SDValue();
8481     }
8482   } else if (N1.getOpcode() == ISD::AND) {
8483     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8484     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8485     if (!N11C)
8486       return SDValue();
8487     unsigned Mask2 = N11C->getZExtValue();
8488
8489     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8490     // as is to match.
8491     if (ARM::isBitFieldInvertedMask(Mask) &&
8492         (Mask == ~Mask2)) {
8493       // The pack halfword instruction works better for masks that fit it,
8494       // so use that when it's available.
8495       if (Subtarget->hasT2ExtractPack() &&
8496           (Mask == 0xffff || Mask == 0xffff0000))
8497         return SDValue();
8498       // 2a
8499       unsigned amt = countTrailingZeros(Mask2);
8500       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8501                         DAG.getConstant(amt, MVT::i32));
8502       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8503                         DAG.getConstant(Mask, MVT::i32));
8504       // Do not add new nodes to DAG combiner worklist.
8505       DCI.CombineTo(N, Res, false);
8506       return SDValue();
8507     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8508                (~Mask == Mask2)) {
8509       // The pack halfword instruction works better for masks that fit it,
8510       // so use that when it's available.
8511       if (Subtarget->hasT2ExtractPack() &&
8512           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8513         return SDValue();
8514       // 2b
8515       unsigned lsb = countTrailingZeros(Mask);
8516       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8517                         DAG.getConstant(lsb, MVT::i32));
8518       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8519                         DAG.getConstant(Mask2, MVT::i32));
8520       // Do not add new nodes to DAG combiner worklist.
8521       DCI.CombineTo(N, Res, false);
8522       return SDValue();
8523     }
8524   }
8525
8526   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8527       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8528       ARM::isBitFieldInvertedMask(~Mask)) {
8529     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8530     // where lsb(mask) == #shamt and masked bits of B are known zero.
8531     SDValue ShAmt = N00.getOperand(1);
8532     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8533     unsigned LSB = countTrailingZeros(Mask);
8534     if (ShAmtC != LSB)
8535       return SDValue();
8536
8537     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8538                       DAG.getConstant(~Mask, MVT::i32));
8539
8540     // Do not add new nodes to DAG combiner worklist.
8541     DCI.CombineTo(N, Res, false);
8542   }
8543
8544   return SDValue();
8545 }
8546
8547 static SDValue PerformXORCombine(SDNode *N,
8548                                  TargetLowering::DAGCombinerInfo &DCI,
8549                                  const ARMSubtarget *Subtarget) {
8550   EVT VT = N->getValueType(0);
8551   SelectionDAG &DAG = DCI.DAG;
8552
8553   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8554     return SDValue();
8555
8556   if (!Subtarget->isThumb1Only()) {
8557     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8558     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8559     if (Result.getNode())
8560       return Result;
8561   }
8562
8563   return SDValue();
8564 }
8565
8566 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8567 /// the bits being cleared by the AND are not demanded by the BFI.
8568 static SDValue PerformBFICombine(SDNode *N,
8569                                  TargetLowering::DAGCombinerInfo &DCI) {
8570   SDValue N1 = N->getOperand(1);
8571   if (N1.getOpcode() == ISD::AND) {
8572     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8573     if (!N11C)
8574       return SDValue();
8575     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8576     unsigned LSB = countTrailingZeros(~InvMask);
8577     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8578     assert(Width <
8579                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8580            "undefined behavior");
8581     unsigned Mask = (1u << Width) - 1;
8582     unsigned Mask2 = N11C->getZExtValue();
8583     if ((Mask & (~Mask2)) == 0)
8584       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8585                              N->getOperand(0), N1.getOperand(0),
8586                              N->getOperand(2));
8587   }
8588   return SDValue();
8589 }
8590
8591 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8592 /// ARMISD::VMOVRRD.
8593 static SDValue PerformVMOVRRDCombine(SDNode *N,
8594                                      TargetLowering::DAGCombinerInfo &DCI,
8595                                      const ARMSubtarget *Subtarget) {
8596   // vmovrrd(vmovdrr x, y) -> x,y
8597   SDValue InDouble = N->getOperand(0);
8598   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8599     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8600
8601   // vmovrrd(load f64) -> (load i32), (load i32)
8602   SDNode *InNode = InDouble.getNode();
8603   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8604       InNode->getValueType(0) == MVT::f64 &&
8605       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8606       !cast<LoadSDNode>(InNode)->isVolatile()) {
8607     // TODO: Should this be done for non-FrameIndex operands?
8608     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8609
8610     SelectionDAG &DAG = DCI.DAG;
8611     SDLoc DL(LD);
8612     SDValue BasePtr = LD->getBasePtr();
8613     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8614                                  LD->getPointerInfo(), LD->isVolatile(),
8615                                  LD->isNonTemporal(), LD->isInvariant(),
8616                                  LD->getAlignment());
8617
8618     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8619                                     DAG.getConstant(4, MVT::i32));
8620     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8621                                  LD->getPointerInfo(), LD->isVolatile(),
8622                                  LD->isNonTemporal(), LD->isInvariant(),
8623                                  std::min(4U, LD->getAlignment() / 2));
8624
8625     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8626     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8627       std::swap (NewLD1, NewLD2);
8628     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8629     return Result;
8630   }
8631
8632   return SDValue();
8633 }
8634
8635 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8636 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8637 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8638   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8639   SDValue Op0 = N->getOperand(0);
8640   SDValue Op1 = N->getOperand(1);
8641   if (Op0.getOpcode() == ISD::BITCAST)
8642     Op0 = Op0.getOperand(0);
8643   if (Op1.getOpcode() == ISD::BITCAST)
8644     Op1 = Op1.getOperand(0);
8645   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8646       Op0.getNode() == Op1.getNode() &&
8647       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8648     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8649                        N->getValueType(0), Op0.getOperand(0));
8650   return SDValue();
8651 }
8652
8653 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8654 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8655 /// i64 vector to have f64 elements, since the value can then be loaded
8656 /// directly into a VFP register.
8657 static bool hasNormalLoadOperand(SDNode *N) {
8658   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8659   for (unsigned i = 0; i < NumElts; ++i) {
8660     SDNode *Elt = N->getOperand(i).getNode();
8661     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8662       return true;
8663   }
8664   return false;
8665 }
8666
8667 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8668 /// ISD::BUILD_VECTOR.
8669 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8670                                           TargetLowering::DAGCombinerInfo &DCI,
8671                                           const ARMSubtarget *Subtarget) {
8672   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8673   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8674   // into a pair of GPRs, which is fine when the value is used as a scalar,
8675   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8676   SelectionDAG &DAG = DCI.DAG;
8677   if (N->getNumOperands() == 2) {
8678     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8679     if (RV.getNode())
8680       return RV;
8681   }
8682
8683   // Load i64 elements as f64 values so that type legalization does not split
8684   // them up into i32 values.
8685   EVT VT = N->getValueType(0);
8686   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8687     return SDValue();
8688   SDLoc dl(N);
8689   SmallVector<SDValue, 8> Ops;
8690   unsigned NumElts = VT.getVectorNumElements();
8691   for (unsigned i = 0; i < NumElts; ++i) {
8692     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8693     Ops.push_back(V);
8694     // Make the DAGCombiner fold the bitcast.
8695     DCI.AddToWorklist(V.getNode());
8696   }
8697   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8698   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8699   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8700 }
8701
8702 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8703 static SDValue
8704 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8705   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8706   // At that time, we may have inserted bitcasts from integer to float.
8707   // If these bitcasts have survived DAGCombine, change the lowering of this
8708   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8709   // force to use floating point types.
8710
8711   // Make sure we can change the type of the vector.
8712   // This is possible iff:
8713   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8714   //    1.1. Vector is used only once.
8715   //    1.2. Use is a bit convert to an integer type.
8716   // 2. The size of its operands are 32-bits (64-bits are not legal).
8717   EVT VT = N->getValueType(0);
8718   EVT EltVT = VT.getVectorElementType();
8719
8720   // Check 1.1. and 2.
8721   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8722     return SDValue();
8723
8724   // By construction, the input type must be float.
8725   assert(EltVT == MVT::f32 && "Unexpected type!");
8726
8727   // Check 1.2.
8728   SDNode *Use = *N->use_begin();
8729   if (Use->getOpcode() != ISD::BITCAST ||
8730       Use->getValueType(0).isFloatingPoint())
8731     return SDValue();
8732
8733   // Check profitability.
8734   // Model is, if more than half of the relevant operands are bitcast from
8735   // i32, turn the build_vector into a sequence of insert_vector_elt.
8736   // Relevant operands are everything that is not statically
8737   // (i.e., at compile time) bitcasted.
8738   unsigned NumOfBitCastedElts = 0;
8739   unsigned NumElts = VT.getVectorNumElements();
8740   unsigned NumOfRelevantElts = NumElts;
8741   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8742     SDValue Elt = N->getOperand(Idx);
8743     if (Elt->getOpcode() == ISD::BITCAST) {
8744       // Assume only bit cast to i32 will go away.
8745       if (Elt->getOperand(0).getValueType() == MVT::i32)
8746         ++NumOfBitCastedElts;
8747     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8748       // Constants are statically casted, thus do not count them as
8749       // relevant operands.
8750       --NumOfRelevantElts;
8751   }
8752
8753   // Check if more than half of the elements require a non-free bitcast.
8754   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8755     return SDValue();
8756
8757   SelectionDAG &DAG = DCI.DAG;
8758   // Create the new vector type.
8759   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8760   // Check if the type is legal.
8761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8762   if (!TLI.isTypeLegal(VecVT))
8763     return SDValue();
8764
8765   // Combine:
8766   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8767   // => BITCAST INSERT_VECTOR_ELT
8768   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8769   //                      (BITCAST EN), N.
8770   SDValue Vec = DAG.getUNDEF(VecVT);
8771   SDLoc dl(N);
8772   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8773     SDValue V = N->getOperand(Idx);
8774     if (V.getOpcode() == ISD::UNDEF)
8775       continue;
8776     if (V.getOpcode() == ISD::BITCAST &&
8777         V->getOperand(0).getValueType() == MVT::i32)
8778       // Fold obvious case.
8779       V = V.getOperand(0);
8780     else {
8781       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8782       // Make the DAGCombiner fold the bitcasts.
8783       DCI.AddToWorklist(V.getNode());
8784     }
8785     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8786     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8787   }
8788   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8789   // Make the DAGCombiner fold the bitcasts.
8790   DCI.AddToWorklist(Vec.getNode());
8791   return Vec;
8792 }
8793
8794 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8795 /// ISD::INSERT_VECTOR_ELT.
8796 static SDValue PerformInsertEltCombine(SDNode *N,
8797                                        TargetLowering::DAGCombinerInfo &DCI) {
8798   // Bitcast an i64 load inserted into a vector to f64.
8799   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8800   EVT VT = N->getValueType(0);
8801   SDNode *Elt = N->getOperand(1).getNode();
8802   if (VT.getVectorElementType() != MVT::i64 ||
8803       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8804     return SDValue();
8805
8806   SelectionDAG &DAG = DCI.DAG;
8807   SDLoc dl(N);
8808   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8809                                  VT.getVectorNumElements());
8810   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8811   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8812   // Make the DAGCombiner fold the bitcasts.
8813   DCI.AddToWorklist(Vec.getNode());
8814   DCI.AddToWorklist(V.getNode());
8815   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8816                                Vec, V, N->getOperand(2));
8817   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8818 }
8819
8820 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8821 /// ISD::VECTOR_SHUFFLE.
8822 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8823   // The LLVM shufflevector instruction does not require the shuffle mask
8824   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8825   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8826   // operands do not match the mask length, they are extended by concatenating
8827   // them with undef vectors.  That is probably the right thing for other
8828   // targets, but for NEON it is better to concatenate two double-register
8829   // size vector operands into a single quad-register size vector.  Do that
8830   // transformation here:
8831   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8832   //   shuffle(concat(v1, v2), undef)
8833   SDValue Op0 = N->getOperand(0);
8834   SDValue Op1 = N->getOperand(1);
8835   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8836       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8837       Op0.getNumOperands() != 2 ||
8838       Op1.getNumOperands() != 2)
8839     return SDValue();
8840   SDValue Concat0Op1 = Op0.getOperand(1);
8841   SDValue Concat1Op1 = Op1.getOperand(1);
8842   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8843       Concat1Op1.getOpcode() != ISD::UNDEF)
8844     return SDValue();
8845   // Skip the transformation if any of the types are illegal.
8846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8847   EVT VT = N->getValueType(0);
8848   if (!TLI.isTypeLegal(VT) ||
8849       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8850       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8851     return SDValue();
8852
8853   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8854                                   Op0.getOperand(0), Op1.getOperand(0));
8855   // Translate the shuffle mask.
8856   SmallVector<int, 16> NewMask;
8857   unsigned NumElts = VT.getVectorNumElements();
8858   unsigned HalfElts = NumElts/2;
8859   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8860   for (unsigned n = 0; n < NumElts; ++n) {
8861     int MaskElt = SVN->getMaskElt(n);
8862     int NewElt = -1;
8863     if (MaskElt < (int)HalfElts)
8864       NewElt = MaskElt;
8865     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8866       NewElt = HalfElts + MaskElt - NumElts;
8867     NewMask.push_back(NewElt);
8868   }
8869   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8870                               DAG.getUNDEF(VT), NewMask.data());
8871 }
8872
8873 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8874 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8875 /// base address updates.
8876 /// For generic load/stores, the memory type is assumed to be a vector.
8877 /// The caller is assumed to have checked legality.
8878 static SDValue CombineBaseUpdate(SDNode *N,
8879                                  TargetLowering::DAGCombinerInfo &DCI) {
8880   SelectionDAG &DAG = DCI.DAG;
8881   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8882                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8883   const bool isStore = N->getOpcode() == ISD::STORE;
8884   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8885   SDValue Addr = N->getOperand(AddrOpIdx);
8886   MemSDNode *MemN = cast<MemSDNode>(N);
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 isLoadOp = 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; isLoadOp = false; break;
8926       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8927         NumVecs = 2; isLoadOp = false; break;
8928       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8929         NumVecs = 3; isLoadOp = false; break;
8930       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8931         NumVecs = 4; isLoadOp = false; break;
8932       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8933         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8934       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8935         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8936       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8937         NumVecs = 4; isLoadOp = 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       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
8947         NumVecs = 1; isLaneOp = false; break;
8948       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
8949         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8950       }
8951     }
8952
8953     // Find the size of memory referenced by the load/store.
8954     EVT VecTy;
8955     if (isLoadOp) {
8956       VecTy = N->getValueType(0);
8957     } else if (isIntrinsic) {
8958       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8959     } else {
8960       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8961       VecTy = N->getOperand(1).getValueType();
8962     }
8963
8964     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8965     if (isLaneOp)
8966       NumBytes /= VecTy.getVectorNumElements();
8967
8968     // If the increment is a constant, it must match the memory ref size.
8969     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8970     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8971       uint64_t IncVal = CInc->getZExtValue();
8972       if (IncVal != NumBytes)
8973         continue;
8974     } else if (NumBytes >= 3 * 16) {
8975       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8976       // separate instructions that make it harder to use a non-constant update.
8977       continue;
8978     }
8979
8980     // OK, we found an ADD we can fold into the base update.
8981     // Now, create a _UPD node, taking care of not breaking alignment.
8982
8983     EVT AlignedVecTy = VecTy;
8984     unsigned Alignment = MemN->getAlignment();
8985
8986     // If this is a less-than-standard-aligned load/store, change the type to
8987     // match the standard alignment.
8988     // The alignment is overlooked when selecting _UPD variants; and it's
8989     // easier to introduce bitcasts here than fix that.
8990     // There are 3 ways to get to this base-update combine:
8991     // - intrinsics: they are assumed to be properly aligned (to the standard
8992     //   alignment of the memory type), so we don't need to do anything.
8993     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8994     //   intrinsics, so, likewise, there's nothing to do.
8995     // - generic load/store instructions: the alignment is specified as an
8996     //   explicit operand, rather than implicitly as the standard alignment
8997     //   of the memory type (like the intrisics).  We need to change the
8998     //   memory type to match the explicit alignment.  That way, we don't
8999     //   generate non-standard-aligned ARMISD::VLDx nodes.
9000     if (isa<LSBaseSDNode>(N)) {
9001       if (Alignment == 0)
9002         Alignment = 1;
9003       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9004         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9005         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9006         assert(!isLaneOp && "Unexpected generic load/store lane.");
9007         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9008         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9009       }
9010       // Don't set an explicit alignment on regular load/stores that we want
9011       // to transform to VLD/VST 1_UPD nodes.
9012       // This matches the behavior of regular load/stores, which only get an
9013       // explicit alignment if the MMO alignment is larger than the standard
9014       // alignment of the memory type.
9015       // Intrinsics, however, always get an explicit alignment, set to the
9016       // alignment of the MMO.
9017       Alignment = 1;
9018     }
9019
9020     // Create the new updating load/store node.
9021     // First, create an SDVTList for the new updating node's results.
9022     EVT Tys[6];
9023     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9024     unsigned n;
9025     for (n = 0; n < NumResultVecs; ++n)
9026       Tys[n] = AlignedVecTy;
9027     Tys[n++] = MVT::i32;
9028     Tys[n] = MVT::Other;
9029     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9030
9031     // Then, gather the new node's operands.
9032     SmallVector<SDValue, 8> Ops;
9033     Ops.push_back(N->getOperand(0)); // incoming chain
9034     Ops.push_back(N->getOperand(AddrOpIdx));
9035     Ops.push_back(Inc);
9036
9037     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9038       // Try to match the intrinsic's signature
9039       Ops.push_back(StN->getValue());
9040     } else {
9041       // Loads (and of course intrinsics) match the intrinsics' signature,
9042       // so just add all but the alignment operand.
9043       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9044         Ops.push_back(N->getOperand(i));
9045     }
9046
9047     // For all node types, the alignment operand is always the last one.
9048     Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
9049
9050     // If this is a non-standard-aligned STORE, the penultimate operand is the
9051     // stored value.  Bitcast it to the aligned type.
9052     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9053       SDValue &StVal = Ops[Ops.size()-2];
9054       StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
9055     }
9056
9057     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9058                                            Ops, AlignedVecTy,
9059                                            MemN->getMemOperand());
9060
9061     // Update the uses.
9062     SmallVector<SDValue, 5> NewResults;
9063     for (unsigned i = 0; i < NumResultVecs; ++i)
9064       NewResults.push_back(SDValue(UpdN.getNode(), i));
9065
9066     // If this is an non-standard-aligned LOAD, the first result is the loaded
9067     // value.  Bitcast it to the expected result type.
9068     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9069       SDValue &LdVal = NewResults[0];
9070       LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
9071     }
9072
9073     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9074     DCI.CombineTo(N, NewResults);
9075     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9076
9077     break;
9078   }
9079   return SDValue();
9080 }
9081
9082 static SDValue PerformVLDCombine(SDNode *N,
9083                                  TargetLowering::DAGCombinerInfo &DCI) {
9084   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9085     return SDValue();
9086
9087   return CombineBaseUpdate(N, DCI);
9088 }
9089
9090 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9091 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9092 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9093 /// return true.
9094 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9095   SelectionDAG &DAG = DCI.DAG;
9096   EVT VT = N->getValueType(0);
9097   // vldN-dup instructions only support 64-bit vectors for N > 1.
9098   if (!VT.is64BitVector())
9099     return false;
9100
9101   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9102   SDNode *VLD = N->getOperand(0).getNode();
9103   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9104     return false;
9105   unsigned NumVecs = 0;
9106   unsigned NewOpc = 0;
9107   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9108   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9109     NumVecs = 2;
9110     NewOpc = ARMISD::VLD2DUP;
9111   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9112     NumVecs = 3;
9113     NewOpc = ARMISD::VLD3DUP;
9114   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9115     NumVecs = 4;
9116     NewOpc = ARMISD::VLD4DUP;
9117   } else {
9118     return false;
9119   }
9120
9121   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9122   // numbers match the load.
9123   unsigned VLDLaneNo =
9124     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9125   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9126        UI != UE; ++UI) {
9127     // Ignore uses of the chain result.
9128     if (UI.getUse().getResNo() == NumVecs)
9129       continue;
9130     SDNode *User = *UI;
9131     if (User->getOpcode() != ARMISD::VDUPLANE ||
9132         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9133       return false;
9134   }
9135
9136   // Create the vldN-dup node.
9137   EVT Tys[5];
9138   unsigned n;
9139   for (n = 0; n < NumVecs; ++n)
9140     Tys[n] = VT;
9141   Tys[n] = MVT::Other;
9142   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9143   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9144   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9145   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9146                                            Ops, VLDMemInt->getMemoryVT(),
9147                                            VLDMemInt->getMemOperand());
9148
9149   // Update the uses.
9150   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9151        UI != UE; ++UI) {
9152     unsigned ResNo = UI.getUse().getResNo();
9153     // Ignore uses of the chain result.
9154     if (ResNo == NumVecs)
9155       continue;
9156     SDNode *User = *UI;
9157     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9158   }
9159
9160   // Now the vldN-lane intrinsic is dead except for its chain result.
9161   // Update uses of the chain.
9162   std::vector<SDValue> VLDDupResults;
9163   for (unsigned n = 0; n < NumVecs; ++n)
9164     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9165   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9166   DCI.CombineTo(VLD, VLDDupResults);
9167
9168   return true;
9169 }
9170
9171 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9172 /// ARMISD::VDUPLANE.
9173 static SDValue PerformVDUPLANECombine(SDNode *N,
9174                                       TargetLowering::DAGCombinerInfo &DCI) {
9175   SDValue Op = N->getOperand(0);
9176
9177   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9178   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9179   if (CombineVLDDUP(N, DCI))
9180     return SDValue(N, 0);
9181
9182   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9183   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9184   while (Op.getOpcode() == ISD::BITCAST)
9185     Op = Op.getOperand(0);
9186   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9187     return SDValue();
9188
9189   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9190   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9191   // The canonical VMOV for a zero vector uses a 32-bit element size.
9192   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9193   unsigned EltBits;
9194   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9195     EltSize = 8;
9196   EVT VT = N->getValueType(0);
9197   if (EltSize > VT.getVectorElementType().getSizeInBits())
9198     return SDValue();
9199
9200   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9201 }
9202
9203 static SDValue PerformLOADCombine(SDNode *N,
9204                                   TargetLowering::DAGCombinerInfo &DCI) {
9205   EVT VT = N->getValueType(0);
9206
9207   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9208   if (ISD::isNormalLoad(N) && VT.isVector() &&
9209       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9210     return CombineBaseUpdate(N, DCI);
9211
9212   return SDValue();
9213 }
9214
9215 /// PerformSTORECombine - Target-specific dag combine xforms for
9216 /// ISD::STORE.
9217 static SDValue PerformSTORECombine(SDNode *N,
9218                                    TargetLowering::DAGCombinerInfo &DCI) {
9219   StoreSDNode *St = cast<StoreSDNode>(N);
9220   if (St->isVolatile())
9221     return SDValue();
9222
9223   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9224   // pack all of the elements in one place.  Next, store to memory in fewer
9225   // chunks.
9226   SDValue StVal = St->getValue();
9227   EVT VT = StVal.getValueType();
9228   if (St->isTruncatingStore() && VT.isVector()) {
9229     SelectionDAG &DAG = DCI.DAG;
9230     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9231     EVT StVT = St->getMemoryVT();
9232     unsigned NumElems = VT.getVectorNumElements();
9233     assert(StVT != VT && "Cannot truncate to the same type");
9234     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9235     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9236
9237     // From, To sizes and ElemCount must be pow of two
9238     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9239
9240     // We are going to use the original vector elt for storing.
9241     // Accumulated smaller vector elements must be a multiple of the store size.
9242     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9243
9244     unsigned SizeRatio  = FromEltSz / ToEltSz;
9245     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9246
9247     // Create a type on which we perform the shuffle.
9248     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9249                                      NumElems*SizeRatio);
9250     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9251
9252     SDLoc DL(St);
9253     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9254     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9255     for (unsigned i = 0; i < NumElems; ++i)
9256       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9257
9258     // Can't shuffle using an illegal type.
9259     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9260
9261     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9262                                 DAG.getUNDEF(WideVec.getValueType()),
9263                                 ShuffleVec.data());
9264     // At this point all of the data is stored at the bottom of the
9265     // register. We now need to save it to mem.
9266
9267     // Find the largest store unit
9268     MVT StoreType = MVT::i8;
9269     for (MVT Tp : MVT::integer_valuetypes()) {
9270       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9271         StoreType = Tp;
9272     }
9273     // Didn't find a legal store type.
9274     if (!TLI.isTypeLegal(StoreType))
9275       return SDValue();
9276
9277     // Bitcast the original vector into a vector of store-size units
9278     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9279             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9280     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9281     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9282     SmallVector<SDValue, 8> Chains;
9283     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9284                                         TLI.getPointerTy());
9285     SDValue BasePtr = St->getBasePtr();
9286
9287     // Perform one or more big stores into memory.
9288     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9289     for (unsigned I = 0; I < E; I++) {
9290       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9291                                    StoreType, ShuffWide,
9292                                    DAG.getIntPtrConstant(I));
9293       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9294                                 St->getPointerInfo(), St->isVolatile(),
9295                                 St->isNonTemporal(), St->getAlignment());
9296       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9297                             Increment);
9298       Chains.push_back(Ch);
9299     }
9300     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9301   }
9302
9303   if (!ISD::isNormalStore(St))
9304     return SDValue();
9305
9306   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9307   // ARM stores of arguments in the same cache line.
9308   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9309       StVal.getNode()->hasOneUse()) {
9310     SelectionDAG  &DAG = DCI.DAG;
9311     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9312     SDLoc DL(St);
9313     SDValue BasePtr = St->getBasePtr();
9314     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9315                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9316                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9317                                   St->isNonTemporal(), St->getAlignment());
9318
9319     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9320                                     DAG.getConstant(4, MVT::i32));
9321     return DAG.getStore(NewST1.getValue(0), DL,
9322                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9323                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9324                         St->isNonTemporal(),
9325                         std::min(4U, St->getAlignment() / 2));
9326   }
9327
9328   if (StVal.getValueType() == MVT::i64 &&
9329       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9330
9331     // Bitcast an i64 store extracted from a vector to f64.
9332     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9333     SelectionDAG &DAG = DCI.DAG;
9334     SDLoc dl(StVal);
9335     SDValue IntVec = StVal.getOperand(0);
9336     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9337                                    IntVec.getValueType().getVectorNumElements());
9338     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9339     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9340                                  Vec, StVal.getOperand(1));
9341     dl = SDLoc(N);
9342     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9343     // Make the DAGCombiner fold the bitcasts.
9344     DCI.AddToWorklist(Vec.getNode());
9345     DCI.AddToWorklist(ExtElt.getNode());
9346     DCI.AddToWorklist(V.getNode());
9347     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9348                         St->getPointerInfo(), St->isVolatile(),
9349                         St->isNonTemporal(), St->getAlignment(),
9350                         St->getAAInfo());
9351   }
9352
9353   // If this is a legal vector store, try to combine it into a VST1_UPD.
9354   if (ISD::isNormalStore(N) && VT.isVector() &&
9355       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9356     return CombineBaseUpdate(N, DCI);
9357
9358   return SDValue();
9359 }
9360
9361 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9362 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9363 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9364 {
9365   integerPart cN;
9366   integerPart c0 = 0;
9367   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9368        I != E; I++) {
9369     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9370     if (!C)
9371       return false;
9372
9373     bool isExact;
9374     APFloat APF = C->getValueAPF();
9375     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9376         != APFloat::opOK || !isExact)
9377       return false;
9378
9379     c0 = (I == 0) ? cN : c0;
9380     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9381       return false;
9382   }
9383   C = c0;
9384   return true;
9385 }
9386
9387 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9388 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9389 /// when the VMUL has a constant operand that is a power of 2.
9390 ///
9391 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9392 ///  vmul.f32        d16, d17, d16
9393 ///  vcvt.s32.f32    d16, d16
9394 /// becomes:
9395 ///  vcvt.s32.f32    d16, d16, #3
9396 static SDValue PerformVCVTCombine(SDNode *N,
9397                                   TargetLowering::DAGCombinerInfo &DCI,
9398                                   const ARMSubtarget *Subtarget) {
9399   SelectionDAG &DAG = DCI.DAG;
9400   SDValue Op = N->getOperand(0);
9401
9402   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9403       Op.getOpcode() != ISD::FMUL)
9404     return SDValue();
9405
9406   uint64_t C;
9407   SDValue N0 = Op->getOperand(0);
9408   SDValue ConstVec = Op->getOperand(1);
9409   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9410
9411   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9412       !isConstVecPow2(ConstVec, isSigned, C))
9413     return SDValue();
9414
9415   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9416   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9417   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9418   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9419       NumLanes > 4) {
9420     // These instructions only exist converting from f32 to i32. We can handle
9421     // smaller integers by generating an extra truncate, but larger ones would
9422     // be lossy. We also can't handle more then 4 lanes, since these intructions
9423     // only support v2i32/v4i32 types.
9424     return SDValue();
9425   }
9426
9427   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9428     Intrinsic::arm_neon_vcvtfp2fxu;
9429   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9430                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9431                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9432                                  DAG.getConstant(Log2_64(C), MVT::i32));
9433
9434   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9435     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9436
9437   return FixConv;
9438 }
9439
9440 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9441 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9442 /// when the VDIV has a constant operand that is a power of 2.
9443 ///
9444 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9445 ///  vcvt.f32.s32    d16, d16
9446 ///  vdiv.f32        d16, d17, d16
9447 /// becomes:
9448 ///  vcvt.f32.s32    d16, d16, #3
9449 static SDValue PerformVDIVCombine(SDNode *N,
9450                                   TargetLowering::DAGCombinerInfo &DCI,
9451                                   const ARMSubtarget *Subtarget) {
9452   SelectionDAG &DAG = DCI.DAG;
9453   SDValue Op = N->getOperand(0);
9454   unsigned OpOpcode = Op.getNode()->getOpcode();
9455
9456   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9457       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9458     return SDValue();
9459
9460   uint64_t C;
9461   SDValue ConstVec = N->getOperand(1);
9462   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9463
9464   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9465       !isConstVecPow2(ConstVec, isSigned, C))
9466     return SDValue();
9467
9468   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9469   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9470   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9471     // These instructions only exist converting from i32 to f32. We can handle
9472     // smaller integers by generating an extra extend, but larger ones would
9473     // be lossy.
9474     return SDValue();
9475   }
9476
9477   SDValue ConvInput = Op.getOperand(0);
9478   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9479   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9480     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9481                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9482                             ConvInput);
9483
9484   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9485     Intrinsic::arm_neon_vcvtfxu2fp;
9486   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9487                      Op.getValueType(),
9488                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9489                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9490 }
9491
9492 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9493 /// operand of a vector shift operation, where all the elements of the
9494 /// build_vector must have the same constant integer value.
9495 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9496   // Ignore bit_converts.
9497   while (Op.getOpcode() == ISD::BITCAST)
9498     Op = Op.getOperand(0);
9499   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9500   APInt SplatBits, SplatUndef;
9501   unsigned SplatBitSize;
9502   bool HasAnyUndefs;
9503   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9504                                       HasAnyUndefs, ElementBits) ||
9505       SplatBitSize > ElementBits)
9506     return false;
9507   Cnt = SplatBits.getSExtValue();
9508   return true;
9509 }
9510
9511 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9512 /// operand of a vector shift left operation.  That value must be in the range:
9513 ///   0 <= Value < ElementBits for a left shift; or
9514 ///   0 <= Value <= ElementBits for a long left shift.
9515 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9516   assert(VT.isVector() && "vector shift count is not a vector type");
9517   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9518   if (! getVShiftImm(Op, ElementBits, Cnt))
9519     return false;
9520   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9521 }
9522
9523 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9524 /// operand of a vector shift right operation.  For a shift opcode, the value
9525 /// is positive, but for an intrinsic the value count must be negative. The
9526 /// absolute value must be in the range:
9527 ///   1 <= |Value| <= ElementBits for a right shift; or
9528 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9529 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9530                          int64_t &Cnt) {
9531   assert(VT.isVector() && "vector shift count is not a vector type");
9532   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9533   if (! getVShiftImm(Op, ElementBits, Cnt))
9534     return false;
9535   if (isIntrinsic)
9536     Cnt = -Cnt;
9537   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9538 }
9539
9540 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9541 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9542   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9543   switch (IntNo) {
9544   default:
9545     // Don't do anything for most intrinsics.
9546     break;
9547
9548   // Vector shifts: check for immediate versions and lower them.
9549   // Note: This is done during DAG combining instead of DAG legalizing because
9550   // the build_vectors for 64-bit vector element shift counts are generally
9551   // not legal, and it is hard to see their values after they get legalized to
9552   // loads from a constant pool.
9553   case Intrinsic::arm_neon_vshifts:
9554   case Intrinsic::arm_neon_vshiftu:
9555   case Intrinsic::arm_neon_vrshifts:
9556   case Intrinsic::arm_neon_vrshiftu:
9557   case Intrinsic::arm_neon_vrshiftn:
9558   case Intrinsic::arm_neon_vqshifts:
9559   case Intrinsic::arm_neon_vqshiftu:
9560   case Intrinsic::arm_neon_vqshiftsu:
9561   case Intrinsic::arm_neon_vqshiftns:
9562   case Intrinsic::arm_neon_vqshiftnu:
9563   case Intrinsic::arm_neon_vqshiftnsu:
9564   case Intrinsic::arm_neon_vqrshiftns:
9565   case Intrinsic::arm_neon_vqrshiftnu:
9566   case Intrinsic::arm_neon_vqrshiftnsu: {
9567     EVT VT = N->getOperand(1).getValueType();
9568     int64_t Cnt;
9569     unsigned VShiftOpc = 0;
9570
9571     switch (IntNo) {
9572     case Intrinsic::arm_neon_vshifts:
9573     case Intrinsic::arm_neon_vshiftu:
9574       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9575         VShiftOpc = ARMISD::VSHL;
9576         break;
9577       }
9578       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9579         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9580                      ARMISD::VSHRs : ARMISD::VSHRu);
9581         break;
9582       }
9583       return SDValue();
9584
9585     case Intrinsic::arm_neon_vrshifts:
9586     case Intrinsic::arm_neon_vrshiftu:
9587       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9588         break;
9589       return SDValue();
9590
9591     case Intrinsic::arm_neon_vqshifts:
9592     case Intrinsic::arm_neon_vqshiftu:
9593       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9594         break;
9595       return SDValue();
9596
9597     case Intrinsic::arm_neon_vqshiftsu:
9598       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9599         break;
9600       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9601
9602     case Intrinsic::arm_neon_vrshiftn:
9603     case Intrinsic::arm_neon_vqshiftns:
9604     case Intrinsic::arm_neon_vqshiftnu:
9605     case Intrinsic::arm_neon_vqshiftnsu:
9606     case Intrinsic::arm_neon_vqrshiftns:
9607     case Intrinsic::arm_neon_vqrshiftnu:
9608     case Intrinsic::arm_neon_vqrshiftnsu:
9609       // Narrowing shifts require an immediate right shift.
9610       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9611         break;
9612       llvm_unreachable("invalid shift count for narrowing vector shift "
9613                        "intrinsic");
9614
9615     default:
9616       llvm_unreachable("unhandled vector shift");
9617     }
9618
9619     switch (IntNo) {
9620     case Intrinsic::arm_neon_vshifts:
9621     case Intrinsic::arm_neon_vshiftu:
9622       // Opcode already set above.
9623       break;
9624     case Intrinsic::arm_neon_vrshifts:
9625       VShiftOpc = ARMISD::VRSHRs; break;
9626     case Intrinsic::arm_neon_vrshiftu:
9627       VShiftOpc = ARMISD::VRSHRu; break;
9628     case Intrinsic::arm_neon_vrshiftn:
9629       VShiftOpc = ARMISD::VRSHRN; break;
9630     case Intrinsic::arm_neon_vqshifts:
9631       VShiftOpc = ARMISD::VQSHLs; break;
9632     case Intrinsic::arm_neon_vqshiftu:
9633       VShiftOpc = ARMISD::VQSHLu; break;
9634     case Intrinsic::arm_neon_vqshiftsu:
9635       VShiftOpc = ARMISD::VQSHLsu; break;
9636     case Intrinsic::arm_neon_vqshiftns:
9637       VShiftOpc = ARMISD::VQSHRNs; break;
9638     case Intrinsic::arm_neon_vqshiftnu:
9639       VShiftOpc = ARMISD::VQSHRNu; break;
9640     case Intrinsic::arm_neon_vqshiftnsu:
9641       VShiftOpc = ARMISD::VQSHRNsu; break;
9642     case Intrinsic::arm_neon_vqrshiftns:
9643       VShiftOpc = ARMISD::VQRSHRNs; break;
9644     case Intrinsic::arm_neon_vqrshiftnu:
9645       VShiftOpc = ARMISD::VQRSHRNu; break;
9646     case Intrinsic::arm_neon_vqrshiftnsu:
9647       VShiftOpc = ARMISD::VQRSHRNsu; break;
9648     }
9649
9650     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9651                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9652   }
9653
9654   case Intrinsic::arm_neon_vshiftins: {
9655     EVT VT = N->getOperand(1).getValueType();
9656     int64_t Cnt;
9657     unsigned VShiftOpc = 0;
9658
9659     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9660       VShiftOpc = ARMISD::VSLI;
9661     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9662       VShiftOpc = ARMISD::VSRI;
9663     else {
9664       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9665     }
9666
9667     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9668                        N->getOperand(1), N->getOperand(2),
9669                        DAG.getConstant(Cnt, MVT::i32));
9670   }
9671
9672   case Intrinsic::arm_neon_vqrshifts:
9673   case Intrinsic::arm_neon_vqrshiftu:
9674     // No immediate versions of these to check for.
9675     break;
9676   }
9677
9678   return SDValue();
9679 }
9680
9681 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9682 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9683 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9684 /// vector element shift counts are generally not legal, and it is hard to see
9685 /// their values after they get legalized to loads from a constant pool.
9686 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9687                                    const ARMSubtarget *ST) {
9688   EVT VT = N->getValueType(0);
9689   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9690     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9691     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9692     SDValue N1 = N->getOperand(1);
9693     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9694       SDValue N0 = N->getOperand(0);
9695       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9696           DAG.MaskedValueIsZero(N0.getOperand(0),
9697                                 APInt::getHighBitsSet(32, 16)))
9698         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9699     }
9700   }
9701
9702   // Nothing to be done for scalar shifts.
9703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9704   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9705     return SDValue();
9706
9707   assert(ST->hasNEON() && "unexpected vector shift");
9708   int64_t Cnt;
9709
9710   switch (N->getOpcode()) {
9711   default: llvm_unreachable("unexpected shift opcode");
9712
9713   case ISD::SHL:
9714     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9715       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9716                          DAG.getConstant(Cnt, MVT::i32));
9717     break;
9718
9719   case ISD::SRA:
9720   case ISD::SRL:
9721     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9722       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9723                             ARMISD::VSHRs : ARMISD::VSHRu);
9724       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9725                          DAG.getConstant(Cnt, MVT::i32));
9726     }
9727   }
9728   return SDValue();
9729 }
9730
9731 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9732 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9733 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9734                                     const ARMSubtarget *ST) {
9735   SDValue N0 = N->getOperand(0);
9736
9737   // Check for sign- and zero-extensions of vector extract operations of 8-
9738   // and 16-bit vector elements.  NEON supports these directly.  They are
9739   // handled during DAG combining because type legalization will promote them
9740   // to 32-bit types and it is messy to recognize the operations after that.
9741   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9742     SDValue Vec = N0.getOperand(0);
9743     SDValue Lane = N0.getOperand(1);
9744     EVT VT = N->getValueType(0);
9745     EVT EltVT = N0.getValueType();
9746     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9747
9748     if (VT == MVT::i32 &&
9749         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9750         TLI.isTypeLegal(Vec.getValueType()) &&
9751         isa<ConstantSDNode>(Lane)) {
9752
9753       unsigned Opc = 0;
9754       switch (N->getOpcode()) {
9755       default: llvm_unreachable("unexpected opcode");
9756       case ISD::SIGN_EXTEND:
9757         Opc = ARMISD::VGETLANEs;
9758         break;
9759       case ISD::ZERO_EXTEND:
9760       case ISD::ANY_EXTEND:
9761         Opc = ARMISD::VGETLANEu;
9762         break;
9763       }
9764       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9765     }
9766   }
9767
9768   return SDValue();
9769 }
9770
9771 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9772 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9773 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9774                                        const ARMSubtarget *ST) {
9775   // If the target supports NEON, try to use vmax/vmin instructions for f32
9776   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9777   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9778   // a NaN; only do the transformation when it matches that behavior.
9779
9780   // For now only do this when using NEON for FP operations; if using VFP, it
9781   // is not obvious that the benefit outweighs the cost of switching to the
9782   // NEON pipeline.
9783   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9784       N->getValueType(0) != MVT::f32)
9785     return SDValue();
9786
9787   SDValue CondLHS = N->getOperand(0);
9788   SDValue CondRHS = N->getOperand(1);
9789   SDValue LHS = N->getOperand(2);
9790   SDValue RHS = N->getOperand(3);
9791   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9792
9793   unsigned Opcode = 0;
9794   bool IsReversed;
9795   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9796     IsReversed = false; // x CC y ? x : y
9797   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9798     IsReversed = true ; // x CC y ? y : x
9799   } else {
9800     return SDValue();
9801   }
9802
9803   bool IsUnordered;
9804   switch (CC) {
9805   default: break;
9806   case ISD::SETOLT:
9807   case ISD::SETOLE:
9808   case ISD::SETLT:
9809   case ISD::SETLE:
9810   case ISD::SETULT:
9811   case ISD::SETULE:
9812     // If LHS is NaN, an ordered comparison will be false and the result will
9813     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9814     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9815     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9816     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9817       break;
9818     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9819     // will return -0, so vmin can only be used for unsafe math or if one of
9820     // the operands is known to be nonzero.
9821     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9822         !DAG.getTarget().Options.UnsafeFPMath &&
9823         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9824       break;
9825     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9826     break;
9827
9828   case ISD::SETOGT:
9829   case ISD::SETOGE:
9830   case ISD::SETGT:
9831   case ISD::SETGE:
9832   case ISD::SETUGT:
9833   case ISD::SETUGE:
9834     // If LHS is NaN, an ordered comparison will be false and the result will
9835     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9836     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9837     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9838     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9839       break;
9840     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9841     // will return +0, so vmax can only be used for unsafe math or if one of
9842     // the operands is known to be nonzero.
9843     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9844         !DAG.getTarget().Options.UnsafeFPMath &&
9845         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9846       break;
9847     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9848     break;
9849   }
9850
9851   if (!Opcode)
9852     return SDValue();
9853   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9854 }
9855
9856 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9857 SDValue
9858 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9859   SDValue Cmp = N->getOperand(4);
9860   if (Cmp.getOpcode() != ARMISD::CMPZ)
9861     // Only looking at EQ and NE cases.
9862     return SDValue();
9863
9864   EVT VT = N->getValueType(0);
9865   SDLoc dl(N);
9866   SDValue LHS = Cmp.getOperand(0);
9867   SDValue RHS = Cmp.getOperand(1);
9868   SDValue FalseVal = N->getOperand(0);
9869   SDValue TrueVal = N->getOperand(1);
9870   SDValue ARMcc = N->getOperand(2);
9871   ARMCC::CondCodes CC =
9872     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9873
9874   // Simplify
9875   //   mov     r1, r0
9876   //   cmp     r1, x
9877   //   mov     r0, y
9878   //   moveq   r0, x
9879   // to
9880   //   cmp     r0, x
9881   //   movne   r0, y
9882   //
9883   //   mov     r1, r0
9884   //   cmp     r1, x
9885   //   mov     r0, x
9886   //   movne   r0, y
9887   // to
9888   //   cmp     r0, x
9889   //   movne   r0, y
9890   /// FIXME: Turn this into a target neutral optimization?
9891   SDValue Res;
9892   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9893     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9894                       N->getOperand(3), Cmp);
9895   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9896     SDValue ARMcc;
9897     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9898     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9899                       N->getOperand(3), NewCmp);
9900   }
9901
9902   if (Res.getNode()) {
9903     APInt KnownZero, KnownOne;
9904     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9905     // Capture demanded bits information that would be otherwise lost.
9906     if (KnownZero == 0xfffffffe)
9907       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9908                         DAG.getValueType(MVT::i1));
9909     else if (KnownZero == 0xffffff00)
9910       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9911                         DAG.getValueType(MVT::i8));
9912     else if (KnownZero == 0xffff0000)
9913       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9914                         DAG.getValueType(MVT::i16));
9915   }
9916
9917   return Res;
9918 }
9919
9920 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9921                                              DAGCombinerInfo &DCI) const {
9922   switch (N->getOpcode()) {
9923   default: break;
9924   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9925   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9926   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9927   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9928   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9929   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9930   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9931   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9932   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9933   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9934   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9935   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9936   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9937   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9938   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9939   case ISD::FP_TO_SINT:
9940   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9941   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9942   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9943   case ISD::SHL:
9944   case ISD::SRA:
9945   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9946   case ISD::SIGN_EXTEND:
9947   case ISD::ZERO_EXTEND:
9948   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9949   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9950   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9951   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
9952   case ARMISD::VLD2DUP:
9953   case ARMISD::VLD3DUP:
9954   case ARMISD::VLD4DUP:
9955     return PerformVLDCombine(N, DCI);
9956   case ARMISD::BUILD_VECTOR:
9957     return PerformARMBUILD_VECTORCombine(N, DCI);
9958   case ISD::INTRINSIC_VOID:
9959   case ISD::INTRINSIC_W_CHAIN:
9960     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9961     case Intrinsic::arm_neon_vld1:
9962     case Intrinsic::arm_neon_vld2:
9963     case Intrinsic::arm_neon_vld3:
9964     case Intrinsic::arm_neon_vld4:
9965     case Intrinsic::arm_neon_vld2lane:
9966     case Intrinsic::arm_neon_vld3lane:
9967     case Intrinsic::arm_neon_vld4lane:
9968     case Intrinsic::arm_neon_vst1:
9969     case Intrinsic::arm_neon_vst2:
9970     case Intrinsic::arm_neon_vst3:
9971     case Intrinsic::arm_neon_vst4:
9972     case Intrinsic::arm_neon_vst2lane:
9973     case Intrinsic::arm_neon_vst3lane:
9974     case Intrinsic::arm_neon_vst4lane:
9975       return PerformVLDCombine(N, DCI);
9976     default: break;
9977     }
9978     break;
9979   }
9980   return SDValue();
9981 }
9982
9983 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9984                                                           EVT VT) const {
9985   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9986 }
9987
9988 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9989                                                        unsigned,
9990                                                        unsigned,
9991                                                        bool *Fast) const {
9992   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9993   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9994
9995   switch (VT.getSimpleVT().SimpleTy) {
9996   default:
9997     return false;
9998   case MVT::i8:
9999   case MVT::i16:
10000   case MVT::i32: {
10001     // Unaligned access can use (for example) LRDB, LRDH, LDR
10002     if (AllowsUnaligned) {
10003       if (Fast)
10004         *Fast = Subtarget->hasV7Ops();
10005       return true;
10006     }
10007     return false;
10008   }
10009   case MVT::f64:
10010   case MVT::v2f64: {
10011     // For any little-endian targets with neon, we can support unaligned ld/st
10012     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10013     // A big-endian target may also explicitly support unaligned accesses
10014     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10015       if (Fast)
10016         *Fast = true;
10017       return true;
10018     }
10019     return false;
10020   }
10021   }
10022 }
10023
10024 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10025                        unsigned AlignCheck) {
10026   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10027           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10028 }
10029
10030 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10031                                            unsigned DstAlign, unsigned SrcAlign,
10032                                            bool IsMemset, bool ZeroMemset,
10033                                            bool MemcpyStrSrc,
10034                                            MachineFunction &MF) const {
10035   const Function *F = MF.getFunction();
10036
10037   // See if we can use NEON instructions for this...
10038   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10039       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10040     bool Fast;
10041     if (Size >= 16 &&
10042         (memOpAlign(SrcAlign, DstAlign, 16) ||
10043          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10044       return MVT::v2f64;
10045     } else if (Size >= 8 &&
10046                (memOpAlign(SrcAlign, DstAlign, 8) ||
10047                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10048                  Fast))) {
10049       return MVT::f64;
10050     }
10051   }
10052
10053   // Lowering to i32/i16 if the size permits.
10054   if (Size >= 4)
10055     return MVT::i32;
10056   else if (Size >= 2)
10057     return MVT::i16;
10058
10059   // Let the target-independent logic figure it out.
10060   return MVT::Other;
10061 }
10062
10063 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10064   if (Val.getOpcode() != ISD::LOAD)
10065     return false;
10066
10067   EVT VT1 = Val.getValueType();
10068   if (!VT1.isSimple() || !VT1.isInteger() ||
10069       !VT2.isSimple() || !VT2.isInteger())
10070     return false;
10071
10072   switch (VT1.getSimpleVT().SimpleTy) {
10073   default: break;
10074   case MVT::i1:
10075   case MVT::i8:
10076   case MVT::i16:
10077     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10078     return true;
10079   }
10080
10081   return false;
10082 }
10083
10084 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10085   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10086     return false;
10087
10088   if (!isTypeLegal(EVT::getEVT(Ty1)))
10089     return false;
10090
10091   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10092
10093   // Assuming the caller doesn't have a zeroext or signext return parameter,
10094   // truncation all the way down to i1 is valid.
10095   return true;
10096 }
10097
10098
10099 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10100   if (V < 0)
10101     return false;
10102
10103   unsigned Scale = 1;
10104   switch (VT.getSimpleVT().SimpleTy) {
10105   default: return false;
10106   case MVT::i1:
10107   case MVT::i8:
10108     // Scale == 1;
10109     break;
10110   case MVT::i16:
10111     // Scale == 2;
10112     Scale = 2;
10113     break;
10114   case MVT::i32:
10115     // Scale == 4;
10116     Scale = 4;
10117     break;
10118   }
10119
10120   if ((V & (Scale - 1)) != 0)
10121     return false;
10122   V /= Scale;
10123   return V == (V & ((1LL << 5) - 1));
10124 }
10125
10126 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10127                                       const ARMSubtarget *Subtarget) {
10128   bool isNeg = false;
10129   if (V < 0) {
10130     isNeg = true;
10131     V = - V;
10132   }
10133
10134   switch (VT.getSimpleVT().SimpleTy) {
10135   default: return false;
10136   case MVT::i1:
10137   case MVT::i8:
10138   case MVT::i16:
10139   case MVT::i32:
10140     // + imm12 or - imm8
10141     if (isNeg)
10142       return V == (V & ((1LL << 8) - 1));
10143     return V == (V & ((1LL << 12) - 1));
10144   case MVT::f32:
10145   case MVT::f64:
10146     // Same as ARM mode. FIXME: NEON?
10147     if (!Subtarget->hasVFP2())
10148       return false;
10149     if ((V & 3) != 0)
10150       return false;
10151     V >>= 2;
10152     return V == (V & ((1LL << 8) - 1));
10153   }
10154 }
10155
10156 /// isLegalAddressImmediate - Return true if the integer value can be used
10157 /// as the offset of the target addressing mode for load / store of the
10158 /// given type.
10159 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10160                                     const ARMSubtarget *Subtarget) {
10161   if (V == 0)
10162     return true;
10163
10164   if (!VT.isSimple())
10165     return false;
10166
10167   if (Subtarget->isThumb1Only())
10168     return isLegalT1AddressImmediate(V, VT);
10169   else if (Subtarget->isThumb2())
10170     return isLegalT2AddressImmediate(V, VT, Subtarget);
10171
10172   // ARM mode.
10173   if (V < 0)
10174     V = - V;
10175   switch (VT.getSimpleVT().SimpleTy) {
10176   default: return false;
10177   case MVT::i1:
10178   case MVT::i8:
10179   case MVT::i32:
10180     // +- imm12
10181     return V == (V & ((1LL << 12) - 1));
10182   case MVT::i16:
10183     // +- imm8
10184     return V == (V & ((1LL << 8) - 1));
10185   case MVT::f32:
10186   case MVT::f64:
10187     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10188       return false;
10189     if ((V & 3) != 0)
10190       return false;
10191     V >>= 2;
10192     return V == (V & ((1LL << 8) - 1));
10193   }
10194 }
10195
10196 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10197                                                       EVT VT) const {
10198   int Scale = AM.Scale;
10199   if (Scale < 0)
10200     return false;
10201
10202   switch (VT.getSimpleVT().SimpleTy) {
10203   default: return false;
10204   case MVT::i1:
10205   case MVT::i8:
10206   case MVT::i16:
10207   case MVT::i32:
10208     if (Scale == 1)
10209       return true;
10210     // r + r << imm
10211     Scale = Scale & ~1;
10212     return Scale == 2 || Scale == 4 || Scale == 8;
10213   case MVT::i64:
10214     // r + r
10215     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10216       return true;
10217     return false;
10218   case MVT::isVoid:
10219     // Note, we allow "void" uses (basically, uses that aren't loads or
10220     // stores), because arm allows folding a scale into many arithmetic
10221     // operations.  This should be made more precise and revisited later.
10222
10223     // Allow r << imm, but the imm has to be a multiple of two.
10224     if (Scale & 1) return false;
10225     return isPowerOf2_32(Scale);
10226   }
10227 }
10228
10229 /// isLegalAddressingMode - Return true if the addressing mode represented
10230 /// by AM is legal for this target, for a load/store of the specified type.
10231 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10232                                               Type *Ty) const {
10233   EVT VT = getValueType(Ty, true);
10234   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10235     return false;
10236
10237   // Can never fold addr of global into load/store.
10238   if (AM.BaseGV)
10239     return false;
10240
10241   switch (AM.Scale) {
10242   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10243     break;
10244   case 1:
10245     if (Subtarget->isThumb1Only())
10246       return false;
10247     // FALL THROUGH.
10248   default:
10249     // ARM doesn't support any R+R*scale+imm addr modes.
10250     if (AM.BaseOffs)
10251       return false;
10252
10253     if (!VT.isSimple())
10254       return false;
10255
10256     if (Subtarget->isThumb2())
10257       return isLegalT2ScaledAddressingMode(AM, VT);
10258
10259     int Scale = AM.Scale;
10260     switch (VT.getSimpleVT().SimpleTy) {
10261     default: return false;
10262     case MVT::i1:
10263     case MVT::i8:
10264     case MVT::i32:
10265       if (Scale < 0) Scale = -Scale;
10266       if (Scale == 1)
10267         return true;
10268       // r + r << imm
10269       return isPowerOf2_32(Scale & ~1);
10270     case MVT::i16:
10271     case MVT::i64:
10272       // r + r
10273       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10274         return true;
10275       return false;
10276
10277     case MVT::isVoid:
10278       // Note, we allow "void" uses (basically, uses that aren't loads or
10279       // stores), because arm allows folding a scale into many arithmetic
10280       // operations.  This should be made more precise and revisited later.
10281
10282       // Allow r << imm, but the imm has to be a multiple of two.
10283       if (Scale & 1) return false;
10284       return isPowerOf2_32(Scale);
10285     }
10286   }
10287   return true;
10288 }
10289
10290 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10291 /// icmp immediate, that is the target has icmp instructions which can compare
10292 /// a register against the immediate without having to materialize the
10293 /// immediate into a register.
10294 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10295   // Thumb2 and ARM modes can use cmn for negative immediates.
10296   if (!Subtarget->isThumb())
10297     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10298   if (Subtarget->isThumb2())
10299     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10300   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10301   return Imm >= 0 && Imm <= 255;
10302 }
10303
10304 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10305 /// *or sub* immediate, that is the target has add or sub instructions which can
10306 /// add a register with the immediate without having to materialize the
10307 /// immediate into a register.
10308 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10309   // Same encoding for add/sub, just flip the sign.
10310   int64_t AbsImm = llvm::abs64(Imm);
10311   if (!Subtarget->isThumb())
10312     return ARM_AM::getSOImmVal(AbsImm) != -1;
10313   if (Subtarget->isThumb2())
10314     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10315   // Thumb1 only has 8-bit unsigned immediate.
10316   return AbsImm >= 0 && AbsImm <= 255;
10317 }
10318
10319 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10320                                       bool isSEXTLoad, SDValue &Base,
10321                                       SDValue &Offset, bool &isInc,
10322                                       SelectionDAG &DAG) {
10323   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10324     return false;
10325
10326   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10327     // AddressingMode 3
10328     Base = Ptr->getOperand(0);
10329     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10330       int RHSC = (int)RHS->getZExtValue();
10331       if (RHSC < 0 && RHSC > -256) {
10332         assert(Ptr->getOpcode() == ISD::ADD);
10333         isInc = false;
10334         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10335         return true;
10336       }
10337     }
10338     isInc = (Ptr->getOpcode() == ISD::ADD);
10339     Offset = Ptr->getOperand(1);
10340     return true;
10341   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10342     // AddressingMode 2
10343     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10344       int RHSC = (int)RHS->getZExtValue();
10345       if (RHSC < 0 && RHSC > -0x1000) {
10346         assert(Ptr->getOpcode() == ISD::ADD);
10347         isInc = false;
10348         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10349         Base = Ptr->getOperand(0);
10350         return true;
10351       }
10352     }
10353
10354     if (Ptr->getOpcode() == ISD::ADD) {
10355       isInc = true;
10356       ARM_AM::ShiftOpc ShOpcVal=
10357         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10358       if (ShOpcVal != ARM_AM::no_shift) {
10359         Base = Ptr->getOperand(1);
10360         Offset = Ptr->getOperand(0);
10361       } else {
10362         Base = Ptr->getOperand(0);
10363         Offset = Ptr->getOperand(1);
10364       }
10365       return true;
10366     }
10367
10368     isInc = (Ptr->getOpcode() == ISD::ADD);
10369     Base = Ptr->getOperand(0);
10370     Offset = Ptr->getOperand(1);
10371     return true;
10372   }
10373
10374   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10375   return false;
10376 }
10377
10378 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10379                                      bool isSEXTLoad, SDValue &Base,
10380                                      SDValue &Offset, bool &isInc,
10381                                      SelectionDAG &DAG) {
10382   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10383     return false;
10384
10385   Base = Ptr->getOperand(0);
10386   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10387     int RHSC = (int)RHS->getZExtValue();
10388     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10389       assert(Ptr->getOpcode() == ISD::ADD);
10390       isInc = false;
10391       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10392       return true;
10393     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10394       isInc = Ptr->getOpcode() == ISD::ADD;
10395       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10396       return true;
10397     }
10398   }
10399
10400   return false;
10401 }
10402
10403 /// getPreIndexedAddressParts - returns true by value, base pointer and
10404 /// offset pointer and addressing mode by reference if the node's address
10405 /// can be legally represented as pre-indexed load / store address.
10406 bool
10407 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10408                                              SDValue &Offset,
10409                                              ISD::MemIndexedMode &AM,
10410                                              SelectionDAG &DAG) const {
10411   if (Subtarget->isThumb1Only())
10412     return false;
10413
10414   EVT VT;
10415   SDValue Ptr;
10416   bool isSEXTLoad = false;
10417   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10418     Ptr = LD->getBasePtr();
10419     VT  = LD->getMemoryVT();
10420     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10421   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10422     Ptr = ST->getBasePtr();
10423     VT  = ST->getMemoryVT();
10424   } else
10425     return false;
10426
10427   bool isInc;
10428   bool isLegal = false;
10429   if (Subtarget->isThumb2())
10430     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10431                                        Offset, isInc, DAG);
10432   else
10433     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10434                                         Offset, isInc, DAG);
10435   if (!isLegal)
10436     return false;
10437
10438   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10439   return true;
10440 }
10441
10442 /// getPostIndexedAddressParts - returns true by value, base pointer and
10443 /// offset pointer and addressing mode by reference if this node can be
10444 /// combined with a load / store to form a post-indexed load / store.
10445 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10446                                                    SDValue &Base,
10447                                                    SDValue &Offset,
10448                                                    ISD::MemIndexedMode &AM,
10449                                                    SelectionDAG &DAG) const {
10450   if (Subtarget->isThumb1Only())
10451     return false;
10452
10453   EVT VT;
10454   SDValue Ptr;
10455   bool isSEXTLoad = false;
10456   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10457     VT  = LD->getMemoryVT();
10458     Ptr = LD->getBasePtr();
10459     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10460   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10461     VT  = ST->getMemoryVT();
10462     Ptr = ST->getBasePtr();
10463   } else
10464     return false;
10465
10466   bool isInc;
10467   bool isLegal = false;
10468   if (Subtarget->isThumb2())
10469     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10470                                        isInc, DAG);
10471   else
10472     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10473                                         isInc, DAG);
10474   if (!isLegal)
10475     return false;
10476
10477   if (Ptr != Base) {
10478     // Swap base ptr and offset to catch more post-index load / store when
10479     // it's legal. In Thumb2 mode, offset must be an immediate.
10480     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10481         !Subtarget->isThumb2())
10482       std::swap(Base, Offset);
10483
10484     // Post-indexed load / store update the base pointer.
10485     if (Ptr != Base)
10486       return false;
10487   }
10488
10489   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10490   return true;
10491 }
10492
10493 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10494                                                       APInt &KnownZero,
10495                                                       APInt &KnownOne,
10496                                                       const SelectionDAG &DAG,
10497                                                       unsigned Depth) const {
10498   unsigned BitWidth = KnownOne.getBitWidth();
10499   KnownZero = KnownOne = APInt(BitWidth, 0);
10500   switch (Op.getOpcode()) {
10501   default: break;
10502   case ARMISD::ADDC:
10503   case ARMISD::ADDE:
10504   case ARMISD::SUBC:
10505   case ARMISD::SUBE:
10506     // These nodes' second result is a boolean
10507     if (Op.getResNo() == 0)
10508       break;
10509     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10510     break;
10511   case ARMISD::CMOV: {
10512     // Bits are known zero/one if known on the LHS and RHS.
10513     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10514     if (KnownZero == 0 && KnownOne == 0) return;
10515
10516     APInt KnownZeroRHS, KnownOneRHS;
10517     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10518     KnownZero &= KnownZeroRHS;
10519     KnownOne  &= KnownOneRHS;
10520     return;
10521   }
10522   case ISD::INTRINSIC_W_CHAIN: {
10523     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10524     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10525     switch (IntID) {
10526     default: return;
10527     case Intrinsic::arm_ldaex:
10528     case Intrinsic::arm_ldrex: {
10529       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10530       unsigned MemBits = VT.getScalarType().getSizeInBits();
10531       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10532       return;
10533     }
10534     }
10535   }
10536   }
10537 }
10538
10539 //===----------------------------------------------------------------------===//
10540 //                           ARM Inline Assembly Support
10541 //===----------------------------------------------------------------------===//
10542
10543 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10544   // Looking for "rev" which is V6+.
10545   if (!Subtarget->hasV6Ops())
10546     return false;
10547
10548   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10549   std::string AsmStr = IA->getAsmString();
10550   SmallVector<StringRef, 4> AsmPieces;
10551   SplitString(AsmStr, AsmPieces, ";\n");
10552
10553   switch (AsmPieces.size()) {
10554   default: return false;
10555   case 1:
10556     AsmStr = AsmPieces[0];
10557     AsmPieces.clear();
10558     SplitString(AsmStr, AsmPieces, " \t,");
10559
10560     // rev $0, $1
10561     if (AsmPieces.size() == 3 &&
10562         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10563         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10564       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10565       if (Ty && Ty->getBitWidth() == 32)
10566         return IntrinsicLowering::LowerToByteSwap(CI);
10567     }
10568     break;
10569   }
10570
10571   return false;
10572 }
10573
10574 /// getConstraintType - Given a constraint letter, return the type of
10575 /// constraint it is for this target.
10576 ARMTargetLowering::ConstraintType
10577 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10578   if (Constraint.size() == 1) {
10579     switch (Constraint[0]) {
10580     default:  break;
10581     case 'l': return C_RegisterClass;
10582     case 'w': return C_RegisterClass;
10583     case 'h': return C_RegisterClass;
10584     case 'x': return C_RegisterClass;
10585     case 't': return C_RegisterClass;
10586     case 'j': return C_Other; // Constant for movw.
10587       // An address with a single base register. Due to the way we
10588       // currently handle addresses it is the same as an 'r' memory constraint.
10589     case 'Q': return C_Memory;
10590     }
10591   } else if (Constraint.size() == 2) {
10592     switch (Constraint[0]) {
10593     default: break;
10594     // All 'U+' constraints are addresses.
10595     case 'U': return C_Memory;
10596     }
10597   }
10598   return TargetLowering::getConstraintType(Constraint);
10599 }
10600
10601 /// Examine constraint type and operand type and determine a weight value.
10602 /// This object must already have been set up with the operand type
10603 /// and the current alternative constraint selected.
10604 TargetLowering::ConstraintWeight
10605 ARMTargetLowering::getSingleConstraintMatchWeight(
10606     AsmOperandInfo &info, const char *constraint) const {
10607   ConstraintWeight weight = CW_Invalid;
10608   Value *CallOperandVal = info.CallOperandVal;
10609     // If we don't have a value, we can't do a match,
10610     // but allow it at the lowest weight.
10611   if (!CallOperandVal)
10612     return CW_Default;
10613   Type *type = CallOperandVal->getType();
10614   // Look at the constraint type.
10615   switch (*constraint) {
10616   default:
10617     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10618     break;
10619   case 'l':
10620     if (type->isIntegerTy()) {
10621       if (Subtarget->isThumb())
10622         weight = CW_SpecificReg;
10623       else
10624         weight = CW_Register;
10625     }
10626     break;
10627   case 'w':
10628     if (type->isFloatingPointTy())
10629       weight = CW_Register;
10630     break;
10631   }
10632   return weight;
10633 }
10634
10635 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10636 RCPair
10637 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10638                                                 MVT VT) const {
10639   if (Constraint.size() == 1) {
10640     // GCC ARM Constraint Letters
10641     switch (Constraint[0]) {
10642     case 'l': // Low regs or general regs.
10643       if (Subtarget->isThumb())
10644         return RCPair(0U, &ARM::tGPRRegClass);
10645       return RCPair(0U, &ARM::GPRRegClass);
10646     case 'h': // High regs or no regs.
10647       if (Subtarget->isThumb())
10648         return RCPair(0U, &ARM::hGPRRegClass);
10649       break;
10650     case 'r':
10651       if (Subtarget->isThumb1Only())
10652         return RCPair(0U, &ARM::tGPRRegClass);
10653       return RCPair(0U, &ARM::GPRRegClass);
10654     case 'w':
10655       if (VT == MVT::Other)
10656         break;
10657       if (VT == MVT::f32)
10658         return RCPair(0U, &ARM::SPRRegClass);
10659       if (VT.getSizeInBits() == 64)
10660         return RCPair(0U, &ARM::DPRRegClass);
10661       if (VT.getSizeInBits() == 128)
10662         return RCPair(0U, &ARM::QPRRegClass);
10663       break;
10664     case 'x':
10665       if (VT == MVT::Other)
10666         break;
10667       if (VT == MVT::f32)
10668         return RCPair(0U, &ARM::SPR_8RegClass);
10669       if (VT.getSizeInBits() == 64)
10670         return RCPair(0U, &ARM::DPR_8RegClass);
10671       if (VT.getSizeInBits() == 128)
10672         return RCPair(0U, &ARM::QPR_8RegClass);
10673       break;
10674     case 't':
10675       if (VT == MVT::f32)
10676         return RCPair(0U, &ARM::SPRRegClass);
10677       break;
10678     }
10679   }
10680   if (StringRef("{cc}").equals_lower(Constraint))
10681     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10682
10683   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10684 }
10685
10686 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10687 /// vector.  If it is invalid, don't add anything to Ops.
10688 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10689                                                      std::string &Constraint,
10690                                                      std::vector<SDValue>&Ops,
10691                                                      SelectionDAG &DAG) const {
10692   SDValue Result;
10693
10694   // Currently only support length 1 constraints.
10695   if (Constraint.length() != 1) return;
10696
10697   char ConstraintLetter = Constraint[0];
10698   switch (ConstraintLetter) {
10699   default: break;
10700   case 'j':
10701   case 'I': case 'J': case 'K': case 'L':
10702   case 'M': case 'N': case 'O':
10703     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10704     if (!C)
10705       return;
10706
10707     int64_t CVal64 = C->getSExtValue();
10708     int CVal = (int) CVal64;
10709     // None of these constraints allow values larger than 32 bits.  Check
10710     // that the value fits in an int.
10711     if (CVal != CVal64)
10712       return;
10713
10714     switch (ConstraintLetter) {
10715       case 'j':
10716         // Constant suitable for movw, must be between 0 and
10717         // 65535.
10718         if (Subtarget->hasV6T2Ops())
10719           if (CVal >= 0 && CVal <= 65535)
10720             break;
10721         return;
10722       case 'I':
10723         if (Subtarget->isThumb1Only()) {
10724           // This must be a constant between 0 and 255, for ADD
10725           // immediates.
10726           if (CVal >= 0 && CVal <= 255)
10727             break;
10728         } else if (Subtarget->isThumb2()) {
10729           // A constant that can be used as an immediate value in a
10730           // data-processing instruction.
10731           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10732             break;
10733         } else {
10734           // A constant that can be used as an immediate value in a
10735           // data-processing instruction.
10736           if (ARM_AM::getSOImmVal(CVal) != -1)
10737             break;
10738         }
10739         return;
10740
10741       case 'J':
10742         if (Subtarget->isThumb()) {  // FIXME thumb2
10743           // This must be a constant between -255 and -1, for negated ADD
10744           // immediates. This can be used in GCC with an "n" modifier that
10745           // prints the negated value, for use with SUB instructions. It is
10746           // not useful otherwise but is implemented for compatibility.
10747           if (CVal >= -255 && CVal <= -1)
10748             break;
10749         } else {
10750           // This must be a constant between -4095 and 4095. It is not clear
10751           // what this constraint is intended for. Implemented for
10752           // compatibility with GCC.
10753           if (CVal >= -4095 && CVal <= 4095)
10754             break;
10755         }
10756         return;
10757
10758       case 'K':
10759         if (Subtarget->isThumb1Only()) {
10760           // A 32-bit value where only one byte has a nonzero value. Exclude
10761           // zero to match GCC. This constraint is used by GCC internally for
10762           // constants that can be loaded with a move/shift combination.
10763           // It is not useful otherwise but is implemented for compatibility.
10764           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10765             break;
10766         } else if (Subtarget->isThumb2()) {
10767           // A constant whose bitwise inverse can be used as an immediate
10768           // value in a data-processing instruction. This can be used in GCC
10769           // with a "B" modifier that prints the inverted value, for use with
10770           // BIC and MVN instructions. It is not useful otherwise but is
10771           // implemented for compatibility.
10772           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10773             break;
10774         } else {
10775           // A constant whose bitwise inverse can be used as an immediate
10776           // value in a data-processing instruction. This can be used in GCC
10777           // with a "B" modifier that prints the inverted value, for use with
10778           // BIC and MVN instructions. It is not useful otherwise but is
10779           // implemented for compatibility.
10780           if (ARM_AM::getSOImmVal(~CVal) != -1)
10781             break;
10782         }
10783         return;
10784
10785       case 'L':
10786         if (Subtarget->isThumb1Only()) {
10787           // This must be a constant between -7 and 7,
10788           // for 3-operand ADD/SUB immediate instructions.
10789           if (CVal >= -7 && CVal < 7)
10790             break;
10791         } else if (Subtarget->isThumb2()) {
10792           // A constant whose negation can be used as an immediate value in a
10793           // data-processing instruction. This can be used in GCC with an "n"
10794           // modifier that prints the negated value, for use with SUB
10795           // instructions. It is not useful otherwise but is implemented for
10796           // compatibility.
10797           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10798             break;
10799         } else {
10800           // A constant whose negation can be used as an immediate value in a
10801           // data-processing instruction. This can be used in GCC with an "n"
10802           // modifier that prints the negated value, for use with SUB
10803           // instructions. It is not useful otherwise but is implemented for
10804           // compatibility.
10805           if (ARM_AM::getSOImmVal(-CVal) != -1)
10806             break;
10807         }
10808         return;
10809
10810       case 'M':
10811         if (Subtarget->isThumb()) { // FIXME thumb2
10812           // This must be a multiple of 4 between 0 and 1020, for
10813           // ADD sp + immediate.
10814           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10815             break;
10816         } else {
10817           // A power of two or a constant between 0 and 32.  This is used in
10818           // GCC for the shift amount on shifted register operands, but it is
10819           // useful in general for any shift amounts.
10820           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10821             break;
10822         }
10823         return;
10824
10825       case 'N':
10826         if (Subtarget->isThumb()) {  // FIXME thumb2
10827           // This must be a constant between 0 and 31, for shift amounts.
10828           if (CVal >= 0 && CVal <= 31)
10829             break;
10830         }
10831         return;
10832
10833       case 'O':
10834         if (Subtarget->isThumb()) {  // FIXME thumb2
10835           // This must be a multiple of 4 between -508 and 508, for
10836           // ADD/SUB sp = sp + immediate.
10837           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10838             break;
10839         }
10840         return;
10841     }
10842     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10843     break;
10844   }
10845
10846   if (Result.getNode()) {
10847     Ops.push_back(Result);
10848     return;
10849   }
10850   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10851 }
10852
10853 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10854   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10855   unsigned Opcode = Op->getOpcode();
10856   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10857          "Invalid opcode for Div/Rem lowering");
10858   bool isSigned = (Opcode == ISD::SDIVREM);
10859   EVT VT = Op->getValueType(0);
10860   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10861
10862   RTLIB::Libcall LC;
10863   switch (VT.getSimpleVT().SimpleTy) {
10864   default: llvm_unreachable("Unexpected request for libcall!");
10865   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10866   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10867   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10868   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10869   }
10870
10871   SDValue InChain = DAG.getEntryNode();
10872
10873   TargetLowering::ArgListTy Args;
10874   TargetLowering::ArgListEntry Entry;
10875   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10876     EVT ArgVT = Op->getOperand(i).getValueType();
10877     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10878     Entry.Node = Op->getOperand(i);
10879     Entry.Ty = ArgTy;
10880     Entry.isSExt = isSigned;
10881     Entry.isZExt = !isSigned;
10882     Args.push_back(Entry);
10883   }
10884
10885   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10886                                          getPointerTy());
10887
10888   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10889
10890   SDLoc dl(Op);
10891   TargetLowering::CallLoweringInfo CLI(DAG);
10892   CLI.setDebugLoc(dl).setChain(InChain)
10893     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10894     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10895
10896   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10897   return CallInfo.first;
10898 }
10899
10900 SDValue
10901 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10902   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10903   SDLoc DL(Op);
10904
10905   // Get the inputs.
10906   SDValue Chain = Op.getOperand(0);
10907   SDValue Size  = Op.getOperand(1);
10908
10909   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10910                               DAG.getConstant(2, MVT::i32));
10911
10912   SDValue Flag;
10913   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10914   Flag = Chain.getValue(1);
10915
10916   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10917   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10918
10919   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10920   Chain = NewSP.getValue(1);
10921
10922   SDValue Ops[2] = { NewSP, Chain };
10923   return DAG.getMergeValues(Ops, DL);
10924 }
10925
10926 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10927   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10928          "Unexpected type for custom-lowering FP_EXTEND");
10929
10930   RTLIB::Libcall LC;
10931   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10932
10933   SDValue SrcVal = Op.getOperand(0);
10934   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10935                      /*isSigned*/ false, SDLoc(Op)).first;
10936 }
10937
10938 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10939   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10940          Subtarget->isFPOnlySP() &&
10941          "Unexpected type for custom-lowering FP_ROUND");
10942
10943   RTLIB::Libcall LC;
10944   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10945
10946   SDValue SrcVal = Op.getOperand(0);
10947   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10948                      /*isSigned*/ false, SDLoc(Op)).first;
10949 }
10950
10951 bool
10952 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10953   // The ARM target isn't yet aware of offsets.
10954   return false;
10955 }
10956
10957 bool ARM::isBitFieldInvertedMask(unsigned v) {
10958   if (v == 0xffffffff)
10959     return false;
10960
10961   // there can be 1's on either or both "outsides", all the "inside"
10962   // bits must be 0's
10963   return isShiftedMask_32(~v);
10964 }
10965
10966 /// isFPImmLegal - Returns true if the target can instruction select the
10967 /// specified FP immediate natively. If false, the legalizer will
10968 /// materialize the FP immediate as a load from a constant pool.
10969 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10970   if (!Subtarget->hasVFP3())
10971     return false;
10972   if (VT == MVT::f32)
10973     return ARM_AM::getFP32Imm(Imm) != -1;
10974   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10975     return ARM_AM::getFP64Imm(Imm) != -1;
10976   return false;
10977 }
10978
10979 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10980 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10981 /// specified in the intrinsic calls.
10982 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10983                                            const CallInst &I,
10984                                            unsigned Intrinsic) const {
10985   switch (Intrinsic) {
10986   case Intrinsic::arm_neon_vld1:
10987   case Intrinsic::arm_neon_vld2:
10988   case Intrinsic::arm_neon_vld3:
10989   case Intrinsic::arm_neon_vld4:
10990   case Intrinsic::arm_neon_vld2lane:
10991   case Intrinsic::arm_neon_vld3lane:
10992   case Intrinsic::arm_neon_vld4lane: {
10993     Info.opc = ISD::INTRINSIC_W_CHAIN;
10994     // Conservatively set memVT to the entire set of vectors loaded.
10995     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10996     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10997     Info.ptrVal = I.getArgOperand(0);
10998     Info.offset = 0;
10999     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11000     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11001     Info.vol = false; // volatile loads with NEON intrinsics not supported
11002     Info.readMem = true;
11003     Info.writeMem = false;
11004     return true;
11005   }
11006   case Intrinsic::arm_neon_vst1:
11007   case Intrinsic::arm_neon_vst2:
11008   case Intrinsic::arm_neon_vst3:
11009   case Intrinsic::arm_neon_vst4:
11010   case Intrinsic::arm_neon_vst2lane:
11011   case Intrinsic::arm_neon_vst3lane:
11012   case Intrinsic::arm_neon_vst4lane: {
11013     Info.opc = ISD::INTRINSIC_VOID;
11014     // Conservatively set memVT to the entire set of vectors stored.
11015     unsigned NumElts = 0;
11016     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11017       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11018       if (!ArgTy->isVectorTy())
11019         break;
11020       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11021     }
11022     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11023     Info.ptrVal = I.getArgOperand(0);
11024     Info.offset = 0;
11025     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11026     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11027     Info.vol = false; // volatile stores with NEON intrinsics not supported
11028     Info.readMem = false;
11029     Info.writeMem = true;
11030     return true;
11031   }
11032   case Intrinsic::arm_ldaex:
11033   case Intrinsic::arm_ldrex: {
11034     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11035     Info.opc = ISD::INTRINSIC_W_CHAIN;
11036     Info.memVT = MVT::getVT(PtrTy->getElementType());
11037     Info.ptrVal = I.getArgOperand(0);
11038     Info.offset = 0;
11039     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11040     Info.vol = true;
11041     Info.readMem = true;
11042     Info.writeMem = false;
11043     return true;
11044   }
11045   case Intrinsic::arm_stlex:
11046   case Intrinsic::arm_strex: {
11047     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11048     Info.opc = ISD::INTRINSIC_W_CHAIN;
11049     Info.memVT = MVT::getVT(PtrTy->getElementType());
11050     Info.ptrVal = I.getArgOperand(1);
11051     Info.offset = 0;
11052     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11053     Info.vol = true;
11054     Info.readMem = false;
11055     Info.writeMem = true;
11056     return true;
11057   }
11058   case Intrinsic::arm_stlexd:
11059   case Intrinsic::arm_strexd: {
11060     Info.opc = ISD::INTRINSIC_W_CHAIN;
11061     Info.memVT = MVT::i64;
11062     Info.ptrVal = I.getArgOperand(2);
11063     Info.offset = 0;
11064     Info.align = 8;
11065     Info.vol = true;
11066     Info.readMem = false;
11067     Info.writeMem = true;
11068     return true;
11069   }
11070   case Intrinsic::arm_ldaexd:
11071   case Intrinsic::arm_ldrexd: {
11072     Info.opc = ISD::INTRINSIC_W_CHAIN;
11073     Info.memVT = MVT::i64;
11074     Info.ptrVal = I.getArgOperand(0);
11075     Info.offset = 0;
11076     Info.align = 8;
11077     Info.vol = true;
11078     Info.readMem = true;
11079     Info.writeMem = false;
11080     return true;
11081   }
11082   default:
11083     break;
11084   }
11085
11086   return false;
11087 }
11088
11089 /// \brief Returns true if it is beneficial to convert a load of a constant
11090 /// to just the constant itself.
11091 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11092                                                           Type *Ty) const {
11093   assert(Ty->isIntegerTy());
11094
11095   unsigned Bits = Ty->getPrimitiveSizeInBits();
11096   if (Bits == 0 || Bits > 32)
11097     return false;
11098   return true;
11099 }
11100
11101 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11102
11103 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11104                                         ARM_MB::MemBOpt Domain) const {
11105   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11106
11107   // First, if the target has no DMB, see what fallback we can use.
11108   if (!Subtarget->hasDataBarrier()) {
11109     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11110     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11111     // here.
11112     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11113       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11114       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11115                         Builder.getInt32(0), Builder.getInt32(7),
11116                         Builder.getInt32(10), Builder.getInt32(5)};
11117       return Builder.CreateCall(MCR, args);
11118     } else {
11119       // Instead of using barriers, atomic accesses on these subtargets use
11120       // libcalls.
11121       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11122     }
11123   } else {
11124     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11125     // Only a full system barrier exists in the M-class architectures.
11126     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11127     Constant *CDomain = Builder.getInt32(Domain);
11128     return Builder.CreateCall(DMB, CDomain);
11129   }
11130 }
11131
11132 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11133 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11134                                          AtomicOrdering Ord, bool IsStore,
11135                                          bool IsLoad) const {
11136   if (!getInsertFencesForAtomic())
11137     return nullptr;
11138
11139   switch (Ord) {
11140   case NotAtomic:
11141   case Unordered:
11142     llvm_unreachable("Invalid fence: unordered/non-atomic");
11143   case Monotonic:
11144   case Acquire:
11145     return nullptr; // Nothing to do
11146   case SequentiallyConsistent:
11147     if (!IsStore)
11148       return nullptr; // Nothing to do
11149     /*FALLTHROUGH*/
11150   case Release:
11151   case AcquireRelease:
11152     if (Subtarget->isSwift())
11153       return makeDMB(Builder, ARM_MB::ISHST);
11154     // FIXME: add a comment with a link to documentation justifying this.
11155     else
11156       return makeDMB(Builder, ARM_MB::ISH);
11157   }
11158   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11159 }
11160
11161 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11162                                           AtomicOrdering Ord, bool IsStore,
11163                                           bool IsLoad) const {
11164   if (!getInsertFencesForAtomic())
11165     return nullptr;
11166
11167   switch (Ord) {
11168   case NotAtomic:
11169   case Unordered:
11170     llvm_unreachable("Invalid fence: unordered/not-atomic");
11171   case Monotonic:
11172   case Release:
11173     return nullptr; // Nothing to do
11174   case Acquire:
11175   case AcquireRelease:
11176   case SequentiallyConsistent:
11177     return makeDMB(Builder, ARM_MB::ISH);
11178   }
11179   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11180 }
11181
11182 // Loads and stores less than 64-bits are already atomic; ones above that
11183 // are doomed anyway, so defer to the default libcall and blame the OS when
11184 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11185 // anything for those.
11186 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11187   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11188   return (Size == 64) && !Subtarget->isMClass();
11189 }
11190
11191 // Loads and stores less than 64-bits are already atomic; ones above that
11192 // are doomed anyway, so defer to the default libcall and blame the OS when
11193 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11194 // anything for those.
11195 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11196 // guarantee, see DDI0406C ARM architecture reference manual,
11197 // sections A8.8.72-74 LDRD)
11198 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11199   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11200   return (Size == 64) && !Subtarget->isMClass();
11201 }
11202
11203 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11204 // and up to 64 bits on the non-M profiles
11205 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11206   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11207   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11208 }
11209
11210 // This has so far only been implemented for MachO.
11211 bool ARMTargetLowering::useLoadStackGuardNode() const {
11212   return Subtarget->isTargetMachO();
11213 }
11214
11215 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11216                                                   unsigned &Cost) const {
11217   // If we do not have NEON, vector types are not natively supported.
11218   if (!Subtarget->hasNEON())
11219     return false;
11220
11221   // Floating point values and vector values map to the same register file.
11222   // Therefore, althought we could do a store extract of a vector type, this is
11223   // better to leave at float as we have more freedom in the addressing mode for
11224   // those.
11225   if (VectorTy->isFPOrFPVectorTy())
11226     return false;
11227
11228   // If the index is unknown at compile time, this is very expensive to lower
11229   // and it is not possible to combine the store with the extract.
11230   if (!isa<ConstantInt>(Idx))
11231     return false;
11232
11233   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11234   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11235   // We can do a store + vector extract on any vector that fits perfectly in a D
11236   // or Q register.
11237   if (BitWidth == 64 || BitWidth == 128) {
11238     Cost = 0;
11239     return true;
11240   }
11241   return false;
11242 }
11243
11244 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11245                                          AtomicOrdering Ord) const {
11246   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11247   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11248   bool IsAcquire = isAtLeastAcquire(Ord);
11249
11250   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11251   // intrinsic must return {i32, i32} and we have to recombine them into a
11252   // single i64 here.
11253   if (ValTy->getPrimitiveSizeInBits() == 64) {
11254     Intrinsic::ID Int =
11255         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11256     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11257
11258     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11259     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11260
11261     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11262     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11263     if (!Subtarget->isLittle())
11264       std::swap (Lo, Hi);
11265     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11266     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11267     return Builder.CreateOr(
11268         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11269   }
11270
11271   Type *Tys[] = { Addr->getType() };
11272   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11273   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11274
11275   return Builder.CreateTruncOrBitCast(
11276       Builder.CreateCall(Ldrex, Addr),
11277       cast<PointerType>(Addr->getType())->getElementType());
11278 }
11279
11280 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11281                                                Value *Addr,
11282                                                AtomicOrdering Ord) const {
11283   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11284   bool IsRelease = isAtLeastRelease(Ord);
11285
11286   // Since the intrinsics must have legal type, the i64 intrinsics take two
11287   // parameters: "i32, i32". We must marshal Val into the appropriate form
11288   // before the call.
11289   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11290     Intrinsic::ID Int =
11291         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11292     Function *Strex = Intrinsic::getDeclaration(M, Int);
11293     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11294
11295     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11296     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11297     if (!Subtarget->isLittle())
11298       std::swap (Lo, Hi);
11299     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11300     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11301   }
11302
11303   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11304   Type *Tys[] = { Addr->getType() };
11305   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11306
11307   return Builder.CreateCall2(
11308       Strex, Builder.CreateZExtOrBitCast(
11309                  Val, Strex->getFunctionType()->getParamType(0)),
11310       Addr);
11311 }
11312
11313 enum HABaseType {
11314   HA_UNKNOWN = 0,
11315   HA_FLOAT,
11316   HA_DOUBLE,
11317   HA_VECT64,
11318   HA_VECT128
11319 };
11320
11321 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11322                                    uint64_t &Members) {
11323   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11324     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11325       uint64_t SubMembers = 0;
11326       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11327         return false;
11328       Members += SubMembers;
11329     }
11330   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11331     uint64_t SubMembers = 0;
11332     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11333       return false;
11334     Members += SubMembers * AT->getNumElements();
11335   } else if (Ty->isFloatTy()) {
11336     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11337       return false;
11338     Members = 1;
11339     Base = HA_FLOAT;
11340   } else if (Ty->isDoubleTy()) {
11341     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11342       return false;
11343     Members = 1;
11344     Base = HA_DOUBLE;
11345   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11346     Members = 1;
11347     switch (Base) {
11348     case HA_FLOAT:
11349     case HA_DOUBLE:
11350       return false;
11351     case HA_VECT64:
11352       return VT->getBitWidth() == 64;
11353     case HA_VECT128:
11354       return VT->getBitWidth() == 128;
11355     case HA_UNKNOWN:
11356       switch (VT->getBitWidth()) {
11357       case 64:
11358         Base = HA_VECT64;
11359         return true;
11360       case 128:
11361         Base = HA_VECT128;
11362         return true;
11363       default:
11364         return false;
11365       }
11366     }
11367   }
11368
11369   return (Members > 0 && Members <= 4);
11370 }
11371
11372 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11373 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11374     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11375   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11376       CallingConv::ARM_AAPCS_VFP)
11377     return false;
11378
11379   HABaseType Base = HA_UNKNOWN;
11380   uint64_t Members = 0;
11381   bool result = isHomogeneousAggregate(Ty, Base, Members);
11382   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11383   return result;
11384 }