Nuke the old JIT.
[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 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
160   if (TT.isOSBinFormatMachO())
161     return new TargetLoweringObjectFileMachO();
162   if (TT.isOSWindows())
163     return new TargetLoweringObjectFileCOFF();
164   return new ARMElfTargetObjectFile();
165 }
166
167 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
168     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
169   Subtarget = &TM.getSubtarget<ARMSubtarget>();
170   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
171   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, nullptr);
255   setLibcallName(RTLIB::SRL_I128, nullptr);
256   setLibcallName(RTLIB::SRA_I128, nullptr);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
259       !Subtarget->isTargetWindows()) {
260     static const struct {
261       const RTLIB::Libcall Op;
262       const char * const Name;
263       const CallingConv::ID CC;
264       const ISD::CondCode Cond;
265     } LibraryCalls[] = {
266       // Double-precision floating-point arithmetic helper functions
267       // RTABI chapter 4.1.2, Table 2
268       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272
273       // Double-precision floating-point comparison helper functions
274       // RTABI chapter 4.1.2, Table 3
275       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
277       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283
284       // Single-precision floating-point arithmetic helper functions
285       // RTABI chapter 4.1.2, Table 4
286       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290
291       // Single-precision floating-point comparison helper functions
292       // RTABI chapter 4.1.2, Table 5
293       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
295       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301
302       // Floating-point to integer conversions.
303       // RTABI chapter 4.1.2, Table 6
304       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Conversions between floating types.
314       // RTABI chapter 4.1.2, Table 7
315       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Integer to floating-point conversions.
320       // RTABI chapter 4.1.2, Table 8
321       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329
330       // Long long helper functions
331       // RTABI chapter 4.2, Table 9
332       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Integer division functions
338       // RTABI chapter 4.3.1
339       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347
348       // Memory operations
349       // RTABI chapter 4.3.4
350       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353     };
354
355     for (const auto &LC : LibraryCalls) {
356       setLibcallName(LC.Op, LC.Name);
357       setLibcallCallingConv(LC.Op, LC.CC);
358       if (LC.Cond != ISD::SETCC_INVALID)
359         setCmpLibcallCC(LC.Op, LC.Cond);
360     }
361   }
362
363   if (Subtarget->isTargetWindows()) {
364     static const struct {
365       const RTLIB::Libcall Op;
366       const char * const Name;
367       const CallingConv::ID CC;
368     } LibraryCalls[] = {
369       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
376       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
377     };
378
379     for (const auto &LC : LibraryCalls) {
380       setLibcallName(LC.Op, LC.Name);
381       setLibcallCallingConv(LC.Op, LC.CC);
382     }
383   }
384
385   // Use divmod compiler-rt calls for iOS 5.0 and later.
386   if (Subtarget->getTargetTriple().isiOS() &&
387       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
388     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
389     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
390   }
391
392   if (Subtarget->isThumb1Only())
393     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
394   else
395     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
396   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
397       !Subtarget->isThumb1Only()) {
398     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
399     if (!Subtarget->isFPOnlySP())
400       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
401   }
402
403   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407       setTruncStoreAction((MVT::SimpleValueType)VT,
408                           (MVT::SimpleValueType)InnerVT, Expand);
409     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412
413     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417
418     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   if (Subtarget->hasNEON()) {
425     addDRTypeForNEON(MVT::v2f32);
426     addDRTypeForNEON(MVT::v8i8);
427     addDRTypeForNEON(MVT::v4i16);
428     addDRTypeForNEON(MVT::v2i32);
429     addDRTypeForNEON(MVT::v1i64);
430
431     addQRTypeForNEON(MVT::v4f32);
432     addQRTypeForNEON(MVT::v2f64);
433     addQRTypeForNEON(MVT::v16i8);
434     addQRTypeForNEON(MVT::v8i16);
435     addQRTypeForNEON(MVT::v4i32);
436     addQRTypeForNEON(MVT::v2i64);
437
438     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439     // neither Neon nor VFP support any arithmetic operations on it.
440     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441     // supported for v4f32.
442     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445     // FIXME: Code duplication: FDIV and FREM are expanded always, see
446     // ARMTargetLowering::addTypeForNEON method for details.
447     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449     // FIXME: Create unittest.
450     // In another words, find a way when "copysign" appears in DAG with vector
451     // operands.
452     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453     // FIXME: Code duplication: SETCC has custom operation action, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456     // FIXME: Create unittest for FNEG and for FABS.
457     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476
477     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492
493     // Mark v2f32 intrinsics.
494     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509
510     // Neon does not support some operations on v1i64 and v2i64 types.
511     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512     // Custom handling for some quad-vector types to detect VMULL.
513     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516     // Custom handling for some vector types to avoid expensive expansions
517     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524     // a destination type that is wider than the source, and nor does
525     // it have a FP_TO_[SU]INT instruction with a narrower destination than
526     // source.
527     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531
532     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
533     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
534
535     // NEON does not have single instruction CTPOP for vectors with element
536     // types wider than 8-bits.  However, custom lowering can leverage the
537     // v8i8/v16i8 vcnt instruction.
538     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
542
543     // NEON only has FMA instructions as of VFP4.
544     if (!Subtarget->hasVFP4()) {
545       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
547     }
548
549     setTargetDAGCombine(ISD::INTRINSIC_VOID);
550     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552     setTargetDAGCombine(ISD::SHL);
553     setTargetDAGCombine(ISD::SRL);
554     setTargetDAGCombine(ISD::SRA);
555     setTargetDAGCombine(ISD::SIGN_EXTEND);
556     setTargetDAGCombine(ISD::ZERO_EXTEND);
557     setTargetDAGCombine(ISD::ANY_EXTEND);
558     setTargetDAGCombine(ISD::SELECT_CC);
559     setTargetDAGCombine(ISD::BUILD_VECTOR);
560     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562     setTargetDAGCombine(ISD::STORE);
563     setTargetDAGCombine(ISD::FP_TO_SINT);
564     setTargetDAGCombine(ISD::FP_TO_UINT);
565     setTargetDAGCombine(ISD::FDIV);
566
567     // It is legal to extload from v4i8 to v4i16 or v4i32.
568     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569                   MVT::v4i16, MVT::v2i16,
570                   MVT::v2i32};
571     for (unsigned i = 0; i < 6; ++i) {
572       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
575     }
576   }
577
578   // ARM and Thumb2 support UMLAL/SMLAL.
579   if (!Subtarget->isThumb1Only())
580     setTargetDAGCombine(ISD::ADDC);
581
582
583   computeRegisterProperties();
584
585   // ARM does not have floating-point extending loads.
586   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
587   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
588
589   // ... or truncating stores
590   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
591   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
592   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
593
594   // ARM does not have i1 sign extending load.
595   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
596
597   // ARM supports all 4 flavors of integer indexed load / store.
598   if (!Subtarget->isThumb1Only()) {
599     for (unsigned im = (unsigned)ISD::PRE_INC;
600          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
601       setIndexedLoadAction(im,  MVT::i1,  Legal);
602       setIndexedLoadAction(im,  MVT::i8,  Legal);
603       setIndexedLoadAction(im,  MVT::i16, Legal);
604       setIndexedLoadAction(im,  MVT::i32, Legal);
605       setIndexedStoreAction(im, MVT::i1,  Legal);
606       setIndexedStoreAction(im, MVT::i8,  Legal);
607       setIndexedStoreAction(im, MVT::i16, Legal);
608       setIndexedStoreAction(im, MVT::i32, Legal);
609     }
610   }
611
612   setOperationAction(ISD::SADDO, MVT::i32, Custom);
613   setOperationAction(ISD::UADDO, MVT::i32, Custom);
614   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
615   setOperationAction(ISD::USUBO, MVT::i32, Custom);
616
617   // i64 operation support.
618   setOperationAction(ISD::MUL,     MVT::i64, Expand);
619   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
620   if (Subtarget->isThumb1Only()) {
621     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
622     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
623   }
624   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
625       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
626     setOperationAction(ISD::MULHS, MVT::i32, Expand);
627
628   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
629   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
630   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
631   setOperationAction(ISD::SRL,       MVT::i64, Custom);
632   setOperationAction(ISD::SRA,       MVT::i64, Custom);
633
634   if (!Subtarget->isThumb1Only()) {
635     // FIXME: We should do this for Thumb1 as well.
636     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
637     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
638     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
639     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
640   }
641
642   // ARM does not have ROTL.
643   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
644   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
645   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
646   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
647     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
648
649   // These just redirect to CTTZ and CTLZ on ARM.
650   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
651   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
652
653   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
654
655   // Only ARMv6 has BSWAP.
656   if (!Subtarget->hasV6Ops())
657     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
658
659   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
660       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
661     // These are expanded into libcalls if the cpu doesn't have HW divider.
662     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
663     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
664   }
665
666   // FIXME: Also set divmod for SREM on EABI
667   setOperationAction(ISD::SREM,  MVT::i32, Expand);
668   setOperationAction(ISD::UREM,  MVT::i32, Expand);
669   // Register based DivRem for AEABI (RTABI 4.2)
670   if (Subtarget->isTargetAEABI()) {
671     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
672     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
673     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
674     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
675     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
676     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
677     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
678     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
679
680     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
682     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
683     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
684     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
685     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
686     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
687     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
688
689     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
690     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
691   } else {
692     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
693     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
694   }
695
696   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
697   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
698   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
699   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
700   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
701
702   setOperationAction(ISD::TRAP, MVT::Other, Legal);
703
704   // Use the default implementation.
705   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
706   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
707   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
708   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
709   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
710   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
711
712   if (!Subtarget->isTargetMachO()) {
713     // Non-MachO platforms may return values in these registers via the
714     // personality function.
715     setExceptionPointerRegister(ARM::R0);
716     setExceptionSelectorRegister(ARM::R1);
717   }
718
719   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
720     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
721   else
722     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
723
724   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
725   // the default expansion.
726   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
727     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
728     // to ldrex/strex loops already.
729     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
730
731     // On v8, we have particularly efficient implementations of atomic fences
732     // if they can be combined with nearby atomic loads and stores.
733     if (!Subtarget->hasV8Ops()) {
734       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
735       setInsertFencesForAtomic(true);
736     }
737   } else {
738     // If there's anything we can use as a barrier, go through custom lowering
739     // for ATOMIC_FENCE.
740     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
741                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
742
743     // Set them all for expansion, which will force libcalls.
744     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
746     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
747     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
748     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
749     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
750     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
756     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
757     // Unordered/Monotonic case.
758     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
759     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
760   }
761
762   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
763
764   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
765   if (!Subtarget->hasV6Ops()) {
766     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
767     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
768   }
769   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
770
771   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
772       !Subtarget->isThumb1Only()) {
773     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
774     // iff target supports vfp2.
775     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
776     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
777   }
778
779   // We want to custom lower some of our intrinsics.
780   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
781   if (Subtarget->isTargetDarwin()) {
782     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
783     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
784     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
785   }
786
787   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
788   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
789   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
790   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
791   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
792   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
793   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
794   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
795   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
796
797   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
798   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
799   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
800   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
801   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
802
803   // We don't support sin/cos/fmod/copysign/pow
804   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
805   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
806   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
807   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
808   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
809   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
810   setOperationAction(ISD::FREM,      MVT::f64, Expand);
811   setOperationAction(ISD::FREM,      MVT::f32, Expand);
812   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
813       !Subtarget->isThumb1Only()) {
814     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
815     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
816   }
817   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
818   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
819
820   if (!Subtarget->hasVFP4()) {
821     setOperationAction(ISD::FMA, MVT::f64, Expand);
822     setOperationAction(ISD::FMA, MVT::f32, Expand);
823   }
824
825   // Various VFP goodness
826   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
827     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
828     if (Subtarget->hasVFP2()) {
829       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
830       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
831       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
832       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
833     }
834
835     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
836     if (!Subtarget->hasV8Ops()) {
837       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
838       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
839     }
840
841     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
842     if (!Subtarget->hasFP16()) {
843       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
844       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
845     }
846   }
847
848   // Combine sin / cos into one node or libcall if possible.
849   if (Subtarget->hasSinCos()) {
850     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
851     setLibcallName(RTLIB::SINCOS_F64, "sincos");
852     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
853       // For iOS, we don't want to the normal expansion of a libcall to
854       // sincos. We want to issue a libcall to __sincos_stret.
855       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
856       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
857     }
858   }
859
860   // We have target-specific dag combine patterns for the following nodes:
861   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
862   setTargetDAGCombine(ISD::ADD);
863   setTargetDAGCombine(ISD::SUB);
864   setTargetDAGCombine(ISD::MUL);
865   setTargetDAGCombine(ISD::AND);
866   setTargetDAGCombine(ISD::OR);
867   setTargetDAGCombine(ISD::XOR);
868
869   if (Subtarget->hasV6Ops())
870     setTargetDAGCombine(ISD::SRL);
871
872   setStackPointerRegisterToSaveRestore(ARM::SP);
873
874   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
875       !Subtarget->hasVFP2())
876     setSchedulingPreference(Sched::RegPressure);
877   else
878     setSchedulingPreference(Sched::Hybrid);
879
880   //// temporary - rewrite interface to use type
881   MaxStoresPerMemset = 8;
882   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
883   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
884   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
885   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
886   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
887
888   // On ARM arguments smaller than 4 bytes are extended, so all arguments
889   // are at least 4 bytes aligned.
890   setMinStackArgumentAlignment(4);
891
892   // Prefer likely predicted branches to selects on out-of-order cores.
893   PredictableSelectIsExpensive = Subtarget->isLikeA9();
894
895   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
896 }
897
898 // FIXME: It might make sense to define the representative register class as the
899 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
900 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
901 // SPR's representative would be DPR_VFP2. This should work well if register
902 // pressure tracking were modified such that a register use would increment the
903 // pressure of the register class's representative and all of it's super
904 // classes' representatives transitively. We have not implemented this because
905 // of the difficulty prior to coalescing of modeling operand register classes
906 // due to the common occurrence of cross class copies and subregister insertions
907 // and extractions.
908 std::pair<const TargetRegisterClass*, uint8_t>
909 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
910   const TargetRegisterClass *RRC = nullptr;
911   uint8_t Cost = 1;
912   switch (VT.SimpleTy) {
913   default:
914     return TargetLowering::findRepresentativeClass(VT);
915   // Use DPR as representative register class for all floating point
916   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
917   // the cost is 1 for both f32 and f64.
918   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
919   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
920     RRC = &ARM::DPRRegClass;
921     // When NEON is used for SP, only half of the register file is available
922     // because operations that define both SP and DP results will be constrained
923     // to the VFP2 class (D0-D15). We currently model this constraint prior to
924     // coalescing by double-counting the SP regs. See the FIXME above.
925     if (Subtarget->useNEONForSinglePrecisionFP())
926       Cost = 2;
927     break;
928   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
929   case MVT::v4f32: case MVT::v2f64:
930     RRC = &ARM::DPRRegClass;
931     Cost = 2;
932     break;
933   case MVT::v4i64:
934     RRC = &ARM::DPRRegClass;
935     Cost = 4;
936     break;
937   case MVT::v8i64:
938     RRC = &ARM::DPRRegClass;
939     Cost = 8;
940     break;
941   }
942   return std::make_pair(RRC, Cost);
943 }
944
945 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
946   switch (Opcode) {
947   default: return nullptr;
948   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
949   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
950   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
951   case ARMISD::CALL:          return "ARMISD::CALL";
952   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
953   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
954   case ARMISD::tCALL:         return "ARMISD::tCALL";
955   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
956   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
957   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
958   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
959   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
960   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
961   case ARMISD::CMP:           return "ARMISD::CMP";
962   case ARMISD::CMN:           return "ARMISD::CMN";
963   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
964   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
965   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
966   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
967   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
968
969   case ARMISD::CMOV:          return "ARMISD::CMOV";
970
971   case ARMISD::RBIT:          return "ARMISD::RBIT";
972
973   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
974   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
975   case ARMISD::SITOF:         return "ARMISD::SITOF";
976   case ARMISD::UITOF:         return "ARMISD::UITOF";
977
978   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
979   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
980   case ARMISD::RRX:           return "ARMISD::RRX";
981
982   case ARMISD::ADDC:          return "ARMISD::ADDC";
983   case ARMISD::ADDE:          return "ARMISD::ADDE";
984   case ARMISD::SUBC:          return "ARMISD::SUBC";
985   case ARMISD::SUBE:          return "ARMISD::SUBE";
986
987   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
988   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
989
990   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
991   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
992
993   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
994
995   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
996
997   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
998
999   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1000
1001   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1002
1003   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1004
1005   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1006   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1007   case ARMISD::VCGE:          return "ARMISD::VCGE";
1008   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1009   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1010   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1011   case ARMISD::VCGT:          return "ARMISD::VCGT";
1012   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1013   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1014   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1015   case ARMISD::VTST:          return "ARMISD::VTST";
1016
1017   case ARMISD::VSHL:          return "ARMISD::VSHL";
1018   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1019   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1020   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1021   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1022   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1023   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1024   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1025   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1026   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1027   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1028   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1029   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1030   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1031   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1032   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1033   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1034   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1035   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1036   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1037   case ARMISD::VDUP:          return "ARMISD::VDUP";
1038   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1039   case ARMISD::VEXT:          return "ARMISD::VEXT";
1040   case ARMISD::VREV64:        return "ARMISD::VREV64";
1041   case ARMISD::VREV32:        return "ARMISD::VREV32";
1042   case ARMISD::VREV16:        return "ARMISD::VREV16";
1043   case ARMISD::VZIP:          return "ARMISD::VZIP";
1044   case ARMISD::VUZP:          return "ARMISD::VUZP";
1045   case ARMISD::VTRN:          return "ARMISD::VTRN";
1046   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1047   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1048   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1049   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1050   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1051   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1052   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1053   case ARMISD::FMAX:          return "ARMISD::FMAX";
1054   case ARMISD::FMIN:          return "ARMISD::FMIN";
1055   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1056   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1057   case ARMISD::BFI:           return "ARMISD::BFI";
1058   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1059   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1060   case ARMISD::VBSL:          return "ARMISD::VBSL";
1061   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1062   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1063   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1064   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1065   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1066   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1067   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1068   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1069   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1070   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1071   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1072   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1073   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1074   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1075   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1076   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1077   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1078   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1079   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1080   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1081   }
1082 }
1083
1084 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1085   if (!VT.isVector()) return getPointerTy();
1086   return VT.changeVectorElementTypeToInteger();
1087 }
1088
1089 /// getRegClassFor - Return the register class that should be used for the
1090 /// specified value type.
1091 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1092   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1093   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1094   // load / store 4 to 8 consecutive D registers.
1095   if (Subtarget->hasNEON()) {
1096     if (VT == MVT::v4i64)
1097       return &ARM::QQPRRegClass;
1098     if (VT == MVT::v8i64)
1099       return &ARM::QQQQPRRegClass;
1100   }
1101   return TargetLowering::getRegClassFor(VT);
1102 }
1103
1104 // Create a fast isel object.
1105 FastISel *
1106 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1107                                   const TargetLibraryInfo *libInfo) const {
1108   return ARM::createFastISel(funcInfo, libInfo);
1109 }
1110
1111 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1112 /// be used for loads / stores from the global.
1113 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1114   return (Subtarget->isThumb1Only() ? 127 : 4095);
1115 }
1116
1117 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1118   unsigned NumVals = N->getNumValues();
1119   if (!NumVals)
1120     return Sched::RegPressure;
1121
1122   for (unsigned i = 0; i != NumVals; ++i) {
1123     EVT VT = N->getValueType(i);
1124     if (VT == MVT::Glue || VT == MVT::Other)
1125       continue;
1126     if (VT.isFloatingPoint() || VT.isVector())
1127       return Sched::ILP;
1128   }
1129
1130   if (!N->isMachineOpcode())
1131     return Sched::RegPressure;
1132
1133   // Load are scheduled for latency even if there instruction itinerary
1134   // is not available.
1135   const TargetInstrInfo *TII =
1136       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1137   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1138
1139   if (MCID.getNumDefs() == 0)
1140     return Sched::RegPressure;
1141   if (!Itins->isEmpty() &&
1142       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1143     return Sched::ILP;
1144
1145   return Sched::RegPressure;
1146 }
1147
1148 //===----------------------------------------------------------------------===//
1149 // Lowering Code
1150 //===----------------------------------------------------------------------===//
1151
1152 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1153 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1154   switch (CC) {
1155   default: llvm_unreachable("Unknown condition code!");
1156   case ISD::SETNE:  return ARMCC::NE;
1157   case ISD::SETEQ:  return ARMCC::EQ;
1158   case ISD::SETGT:  return ARMCC::GT;
1159   case ISD::SETGE:  return ARMCC::GE;
1160   case ISD::SETLT:  return ARMCC::LT;
1161   case ISD::SETLE:  return ARMCC::LE;
1162   case ISD::SETUGT: return ARMCC::HI;
1163   case ISD::SETUGE: return ARMCC::HS;
1164   case ISD::SETULT: return ARMCC::LO;
1165   case ISD::SETULE: return ARMCC::LS;
1166   }
1167 }
1168
1169 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1170 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1171                         ARMCC::CondCodes &CondCode2) {
1172   CondCode2 = ARMCC::AL;
1173   switch (CC) {
1174   default: llvm_unreachable("Unknown FP condition!");
1175   case ISD::SETEQ:
1176   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1177   case ISD::SETGT:
1178   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1179   case ISD::SETGE:
1180   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1181   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1182   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1183   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1184   case ISD::SETO:   CondCode = ARMCC::VC; break;
1185   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1186   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1187   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1188   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1189   case ISD::SETLT:
1190   case ISD::SETULT: CondCode = ARMCC::LT; break;
1191   case ISD::SETLE:
1192   case ISD::SETULE: CondCode = ARMCC::LE; break;
1193   case ISD::SETNE:
1194   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1195   }
1196 }
1197
1198 //===----------------------------------------------------------------------===//
1199 //                      Calling Convention Implementation
1200 //===----------------------------------------------------------------------===//
1201
1202 #include "ARMGenCallingConv.inc"
1203
1204 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1205 /// account presence of floating point hardware and calling convention
1206 /// limitations, such as support for variadic functions.
1207 CallingConv::ID
1208 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1209                                            bool isVarArg) const {
1210   switch (CC) {
1211   default:
1212     llvm_unreachable("Unsupported calling convention");
1213   case CallingConv::ARM_AAPCS:
1214   case CallingConv::ARM_APCS:
1215   case CallingConv::GHC:
1216     return CC;
1217   case CallingConv::ARM_AAPCS_VFP:
1218     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1219   case CallingConv::C:
1220     if (!Subtarget->isAAPCS_ABI())
1221       return CallingConv::ARM_APCS;
1222     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1223              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1224              !isVarArg)
1225       return CallingConv::ARM_AAPCS_VFP;
1226     else
1227       return CallingConv::ARM_AAPCS;
1228   case CallingConv::Fast:
1229     if (!Subtarget->isAAPCS_ABI()) {
1230       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1231         return CallingConv::Fast;
1232       return CallingConv::ARM_APCS;
1233     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1234       return CallingConv::ARM_AAPCS_VFP;
1235     else
1236       return CallingConv::ARM_AAPCS;
1237   }
1238 }
1239
1240 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1241 /// CallingConvention.
1242 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1243                                                  bool Return,
1244                                                  bool isVarArg) const {
1245   switch (getEffectiveCallingConv(CC, isVarArg)) {
1246   default:
1247     llvm_unreachable("Unsupported calling convention");
1248   case CallingConv::ARM_APCS:
1249     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1250   case CallingConv::ARM_AAPCS:
1251     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1252   case CallingConv::ARM_AAPCS_VFP:
1253     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1254   case CallingConv::Fast:
1255     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1256   case CallingConv::GHC:
1257     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1258   }
1259 }
1260
1261 /// LowerCallResult - Lower the result values of a call into the
1262 /// appropriate copies out of appropriate physical registers.
1263 SDValue
1264 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1265                                    CallingConv::ID CallConv, bool isVarArg,
1266                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1267                                    SDLoc dl, SelectionDAG &DAG,
1268                                    SmallVectorImpl<SDValue> &InVals,
1269                                    bool isThisReturn, SDValue ThisVal) const {
1270
1271   // Assign locations to each value returned by this call.
1272   SmallVector<CCValAssign, 16> RVLocs;
1273   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1274                     *DAG.getContext(), Call);
1275   CCInfo.AnalyzeCallResult(Ins,
1276                            CCAssignFnForNode(CallConv, /* Return*/ true,
1277                                              isVarArg));
1278
1279   // Copy all of the result registers out of their specified physreg.
1280   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1281     CCValAssign VA = RVLocs[i];
1282
1283     // Pass 'this' value directly from the argument to return value, to avoid
1284     // reg unit interference
1285     if (i == 0 && isThisReturn) {
1286       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1287              "unexpected return calling convention register assignment");
1288       InVals.push_back(ThisVal);
1289       continue;
1290     }
1291
1292     SDValue Val;
1293     if (VA.needsCustom()) {
1294       // Handle f64 or half of a v2f64.
1295       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1296                                       InFlag);
1297       Chain = Lo.getValue(1);
1298       InFlag = Lo.getValue(2);
1299       VA = RVLocs[++i]; // skip ahead to next loc
1300       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1301                                       InFlag);
1302       Chain = Hi.getValue(1);
1303       InFlag = Hi.getValue(2);
1304       if (!Subtarget->isLittle())
1305         std::swap (Lo, Hi);
1306       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1307
1308       if (VA.getLocVT() == MVT::v2f64) {
1309         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1310         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1311                           DAG.getConstant(0, MVT::i32));
1312
1313         VA = RVLocs[++i]; // skip ahead to next loc
1314         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1315         Chain = Lo.getValue(1);
1316         InFlag = Lo.getValue(2);
1317         VA = RVLocs[++i]; // skip ahead to next loc
1318         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1319         Chain = Hi.getValue(1);
1320         InFlag = Hi.getValue(2);
1321         if (!Subtarget->isLittle())
1322           std::swap (Lo, Hi);
1323         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1324         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1325                           DAG.getConstant(1, MVT::i32));
1326       }
1327     } else {
1328       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1329                                InFlag);
1330       Chain = Val.getValue(1);
1331       InFlag = Val.getValue(2);
1332     }
1333
1334     switch (VA.getLocInfo()) {
1335     default: llvm_unreachable("Unknown loc info!");
1336     case CCValAssign::Full: break;
1337     case CCValAssign::BCvt:
1338       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1339       break;
1340     }
1341
1342     InVals.push_back(Val);
1343   }
1344
1345   return Chain;
1346 }
1347
1348 /// LowerMemOpCallTo - Store the argument to the stack.
1349 SDValue
1350 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1351                                     SDValue StackPtr, SDValue Arg,
1352                                     SDLoc dl, SelectionDAG &DAG,
1353                                     const CCValAssign &VA,
1354                                     ISD::ArgFlagsTy Flags) const {
1355   unsigned LocMemOffset = VA.getLocMemOffset();
1356   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1357   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1358   return DAG.getStore(Chain, dl, Arg, PtrOff,
1359                       MachinePointerInfo::getStack(LocMemOffset),
1360                       false, false, 0);
1361 }
1362
1363 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1364                                          SDValue Chain, SDValue &Arg,
1365                                          RegsToPassVector &RegsToPass,
1366                                          CCValAssign &VA, CCValAssign &NextVA,
1367                                          SDValue &StackPtr,
1368                                          SmallVectorImpl<SDValue> &MemOpChains,
1369                                          ISD::ArgFlagsTy Flags) const {
1370
1371   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1372                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1373   unsigned id = Subtarget->isLittle() ? 0 : 1;
1374   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1375
1376   if (NextVA.isRegLoc())
1377     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1378   else {
1379     assert(NextVA.isMemLoc());
1380     if (!StackPtr.getNode())
1381       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1382
1383     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1384                                            dl, DAG, NextVA,
1385                                            Flags));
1386   }
1387 }
1388
1389 /// LowerCall - Lowering a call into a callseq_start <-
1390 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1391 /// nodes.
1392 SDValue
1393 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1394                              SmallVectorImpl<SDValue> &InVals) const {
1395   SelectionDAG &DAG                     = CLI.DAG;
1396   SDLoc &dl                          = CLI.DL;
1397   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1398   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1399   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1400   SDValue Chain                         = CLI.Chain;
1401   SDValue Callee                        = CLI.Callee;
1402   bool &isTailCall                      = CLI.IsTailCall;
1403   CallingConv::ID CallConv              = CLI.CallConv;
1404   bool doesNotRet                       = CLI.DoesNotReturn;
1405   bool isVarArg                         = CLI.IsVarArg;
1406
1407   MachineFunction &MF = DAG.getMachineFunction();
1408   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1409   bool isThisReturn   = false;
1410   bool isSibCall      = false;
1411
1412   // Disable tail calls if they're not supported.
1413   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1414     isTailCall = false;
1415
1416   if (isTailCall) {
1417     // Check if it's really possible to do a tail call.
1418     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1419                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1420                                                    Outs, OutVals, Ins, DAG);
1421     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1422       report_fatal_error("failed to perform tail call elimination on a call "
1423                          "site marked musttail");
1424     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1425     // detected sibcalls.
1426     if (isTailCall) {
1427       ++NumTailCalls;
1428       isSibCall = true;
1429     }
1430   }
1431
1432   // Analyze operands of the call, assigning locations to each operand.
1433   SmallVector<CCValAssign, 16> ArgLocs;
1434   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1435                     *DAG.getContext(), Call);
1436   CCInfo.AnalyzeCallOperands(Outs,
1437                              CCAssignFnForNode(CallConv, /* Return*/ false,
1438                                                isVarArg));
1439
1440   // Get a count of how many bytes are to be pushed on the stack.
1441   unsigned NumBytes = CCInfo.getNextStackOffset();
1442
1443   // For tail calls, memory operands are available in our caller's stack.
1444   if (isSibCall)
1445     NumBytes = 0;
1446
1447   // Adjust the stack pointer for the new arguments...
1448   // These operations are automatically eliminated by the prolog/epilog pass
1449   if (!isSibCall)
1450     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1451                                  dl);
1452
1453   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1454
1455   RegsToPassVector RegsToPass;
1456   SmallVector<SDValue, 8> MemOpChains;
1457
1458   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1459   // of tail call optimization, arguments are handled later.
1460   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1461        i != e;
1462        ++i, ++realArgIdx) {
1463     CCValAssign &VA = ArgLocs[i];
1464     SDValue Arg = OutVals[realArgIdx];
1465     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1466     bool isByVal = Flags.isByVal();
1467
1468     // Promote the value if needed.
1469     switch (VA.getLocInfo()) {
1470     default: llvm_unreachable("Unknown loc info!");
1471     case CCValAssign::Full: break;
1472     case CCValAssign::SExt:
1473       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1474       break;
1475     case CCValAssign::ZExt:
1476       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1477       break;
1478     case CCValAssign::AExt:
1479       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1480       break;
1481     case CCValAssign::BCvt:
1482       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1483       break;
1484     }
1485
1486     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1487     if (VA.needsCustom()) {
1488       if (VA.getLocVT() == MVT::v2f64) {
1489         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1490                                   DAG.getConstant(0, MVT::i32));
1491         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1492                                   DAG.getConstant(1, MVT::i32));
1493
1494         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1495                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1496
1497         VA = ArgLocs[++i]; // skip ahead to next loc
1498         if (VA.isRegLoc()) {
1499           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1500                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1501         } else {
1502           assert(VA.isMemLoc());
1503
1504           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1505                                                  dl, DAG, VA, Flags));
1506         }
1507       } else {
1508         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1509                          StackPtr, MemOpChains, Flags);
1510       }
1511     } else if (VA.isRegLoc()) {
1512       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1513         assert(VA.getLocVT() == MVT::i32 &&
1514                "unexpected calling convention register assignment");
1515         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1516                "unexpected use of 'returned'");
1517         isThisReturn = true;
1518       }
1519       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1520     } else if (isByVal) {
1521       assert(VA.isMemLoc());
1522       unsigned offset = 0;
1523
1524       // True if this byval aggregate will be split between registers
1525       // and memory.
1526       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1527       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1528
1529       if (CurByValIdx < ByValArgsCount) {
1530
1531         unsigned RegBegin, RegEnd;
1532         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1533
1534         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1535         unsigned int i, j;
1536         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1537           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1538           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1539           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1540                                      MachinePointerInfo(),
1541                                      false, false, false,
1542                                      DAG.InferPtrAlignment(AddArg));
1543           MemOpChains.push_back(Load.getValue(1));
1544           RegsToPass.push_back(std::make_pair(j, Load));
1545         }
1546
1547         // If parameter size outsides register area, "offset" value
1548         // helps us to calculate stack slot for remained part properly.
1549         offset = RegEnd - RegBegin;
1550
1551         CCInfo.nextInRegsParam();
1552       }
1553
1554       if (Flags.getByValSize() > 4*offset) {
1555         unsigned LocMemOffset = VA.getLocMemOffset();
1556         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1557         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1558                                   StkPtrOff);
1559         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1560         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1561         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1562                                            MVT::i32);
1563         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1564
1565         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1566         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1567         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1568                                           Ops));
1569       }
1570     } else if (!isSibCall) {
1571       assert(VA.isMemLoc());
1572
1573       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1574                                              dl, DAG, VA, Flags));
1575     }
1576   }
1577
1578   if (!MemOpChains.empty())
1579     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1580
1581   // Build a sequence of copy-to-reg nodes chained together with token chain
1582   // and flag operands which copy the outgoing args into the appropriate regs.
1583   SDValue InFlag;
1584   // Tail call byval lowering might overwrite argument registers so in case of
1585   // tail call optimization the copies to registers are lowered later.
1586   if (!isTailCall)
1587     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1588       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1589                                RegsToPass[i].second, InFlag);
1590       InFlag = Chain.getValue(1);
1591     }
1592
1593   // For tail calls lower the arguments to the 'real' stack slot.
1594   if (isTailCall) {
1595     // Force all the incoming stack arguments to be loaded from the stack
1596     // before any new outgoing arguments are stored to the stack, because the
1597     // outgoing stack slots may alias the incoming argument stack slots, and
1598     // the alias isn't otherwise explicit. This is slightly more conservative
1599     // than necessary, because it means that each store effectively depends
1600     // on every argument instead of just those arguments it would clobber.
1601
1602     // Do not flag preceding copytoreg stuff together with the following stuff.
1603     InFlag = SDValue();
1604     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1605       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1606                                RegsToPass[i].second, InFlag);
1607       InFlag = Chain.getValue(1);
1608     }
1609     InFlag = SDValue();
1610   }
1611
1612   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1613   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1614   // node so that legalize doesn't hack it.
1615   bool isDirect = false;
1616   bool isARMFunc = false;
1617   bool isLocalARMFunc = false;
1618   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1619
1620   if (EnableARMLongCalls) {
1621     assert((Subtarget->isTargetWindows() ||
1622             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1623            "long-calls with non-static relocation model!");
1624     // Handle a global address or an external symbol. If it's not one of
1625     // those, the target's already in a register, so we don't need to do
1626     // anything extra.
1627     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1628       const GlobalValue *GV = G->getGlobal();
1629       // Create a constant pool entry for the callee address
1630       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1631       ARMConstantPoolValue *CPV =
1632         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1633
1634       // Get the address of the callee into a register
1635       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1636       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1637       Callee = DAG.getLoad(getPointerTy(), dl,
1638                            DAG.getEntryNode(), CPAddr,
1639                            MachinePointerInfo::getConstantPool(),
1640                            false, false, false, 0);
1641     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1642       const char *Sym = S->getSymbol();
1643
1644       // Create a constant pool entry for the callee address
1645       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1646       ARMConstantPoolValue *CPV =
1647         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1648                                       ARMPCLabelIndex, 0);
1649       // Get the address of the callee into a register
1650       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1651       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1652       Callee = DAG.getLoad(getPointerTy(), dl,
1653                            DAG.getEntryNode(), CPAddr,
1654                            MachinePointerInfo::getConstantPool(),
1655                            false, false, false, 0);
1656     }
1657   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1658     const GlobalValue *GV = G->getGlobal();
1659     isDirect = true;
1660     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1661     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1662                    getTargetMachine().getRelocationModel() != Reloc::Static;
1663     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1664     // ARM call to a local ARM function is predicable.
1665     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1666     // tBX takes a register source operand.
1667     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1668       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1669       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1670                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1671                                                       0, ARMII::MO_NONLAZY));
1672       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1673                            MachinePointerInfo::getGOT(), false, false, true, 0);
1674     } else if (Subtarget->isTargetCOFF()) {
1675       assert(Subtarget->isTargetWindows() &&
1676              "Windows is the only supported COFF target");
1677       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1678                                  ? ARMII::MO_DLLIMPORT
1679                                  : ARMII::MO_NO_FLAG;
1680       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1681                                           TargetFlags);
1682       if (GV->hasDLLImportStorageClass())
1683         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1684                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1685                                          Callee), MachinePointerInfo::getGOT(),
1686                              false, false, false, 0);
1687     } else {
1688       // On ELF targets for PIC code, direct calls should go through the PLT
1689       unsigned OpFlags = 0;
1690       if (Subtarget->isTargetELF() &&
1691           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1692         OpFlags = ARMII::MO_PLT;
1693       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1694     }
1695   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1696     isDirect = true;
1697     bool isStub = Subtarget->isTargetMachO() &&
1698                   getTargetMachine().getRelocationModel() != Reloc::Static;
1699     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1700     // tBX takes a register source operand.
1701     const char *Sym = S->getSymbol();
1702     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1703       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1704       ARMConstantPoolValue *CPV =
1705         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1706                                       ARMPCLabelIndex, 4);
1707       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1708       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1709       Callee = DAG.getLoad(getPointerTy(), dl,
1710                            DAG.getEntryNode(), CPAddr,
1711                            MachinePointerInfo::getConstantPool(),
1712                            false, false, false, 0);
1713       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1714       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1715                            getPointerTy(), Callee, PICLabel);
1716     } else {
1717       unsigned OpFlags = 0;
1718       // On ELF targets for PIC code, direct calls should go through the PLT
1719       if (Subtarget->isTargetELF() &&
1720                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1721         OpFlags = ARMII::MO_PLT;
1722       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1723     }
1724   }
1725
1726   // FIXME: handle tail calls differently.
1727   unsigned CallOpc;
1728   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1729       AttributeSet::FunctionIndex, Attribute::MinSize);
1730   if (Subtarget->isThumb()) {
1731     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1732       CallOpc = ARMISD::CALL_NOLINK;
1733     else
1734       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1735   } else {
1736     if (!isDirect && !Subtarget->hasV5TOps())
1737       CallOpc = ARMISD::CALL_NOLINK;
1738     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1739                // Emit regular call when code size is the priority
1740                !HasMinSizeAttr)
1741       // "mov lr, pc; b _foo" to avoid confusing the RSP
1742       CallOpc = ARMISD::CALL_NOLINK;
1743     else
1744       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1745   }
1746
1747   std::vector<SDValue> Ops;
1748   Ops.push_back(Chain);
1749   Ops.push_back(Callee);
1750
1751   // Add argument registers to the end of the list so that they are known live
1752   // into the call.
1753   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1754     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1755                                   RegsToPass[i].second.getValueType()));
1756
1757   // Add a register mask operand representing the call-preserved registers.
1758   if (!isTailCall) {
1759     const uint32_t *Mask;
1760     const TargetRegisterInfo *TRI =
1761         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1762     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1763     if (isThisReturn) {
1764       // For 'this' returns, use the R0-preserving mask if applicable
1765       Mask = ARI->getThisReturnPreservedMask(CallConv);
1766       if (!Mask) {
1767         // Set isThisReturn to false if the calling convention is not one that
1768         // allows 'returned' to be modeled in this way, so LowerCallResult does
1769         // not try to pass 'this' straight through
1770         isThisReturn = false;
1771         Mask = ARI->getCallPreservedMask(CallConv);
1772       }
1773     } else
1774       Mask = ARI->getCallPreservedMask(CallConv);
1775
1776     assert(Mask && "Missing call preserved mask for calling convention");
1777     Ops.push_back(DAG.getRegisterMask(Mask));
1778   }
1779
1780   if (InFlag.getNode())
1781     Ops.push_back(InFlag);
1782
1783   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1784   if (isTailCall)
1785     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1786
1787   // Returns a chain and a flag for retval copy to use.
1788   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1789   InFlag = Chain.getValue(1);
1790
1791   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1792                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1793   if (!Ins.empty())
1794     InFlag = Chain.getValue(1);
1795
1796   // Handle result values, copying them out of physregs into vregs that we
1797   // return.
1798   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1799                          InVals, isThisReturn,
1800                          isThisReturn ? OutVals[0] : SDValue());
1801 }
1802
1803 /// HandleByVal - Every parameter *after* a byval parameter is passed
1804 /// on the stack.  Remember the next parameter register to allocate,
1805 /// and then confiscate the rest of the parameter registers to insure
1806 /// this.
1807 void
1808 ARMTargetLowering::HandleByVal(
1809     CCState *State, unsigned &size, unsigned Align) const {
1810   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1811   assert((State->getCallOrPrologue() == Prologue ||
1812           State->getCallOrPrologue() == Call) &&
1813          "unhandled ParmContext");
1814
1815   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1816     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1817       unsigned AlignInRegs = Align / 4;
1818       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1819       for (unsigned i = 0; i < Waste; ++i)
1820         reg = State->AllocateReg(GPRArgRegs, 4);
1821     }
1822     if (reg != 0) {
1823       unsigned excess = 4 * (ARM::R4 - reg);
1824
1825       // Special case when NSAA != SP and parameter size greater than size of
1826       // all remained GPR regs. In that case we can't split parameter, we must
1827       // send it to stack. We also must set NCRN to R4, so waste all
1828       // remained registers.
1829       const unsigned NSAAOffset = State->getNextStackOffset();
1830       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1831         while (State->AllocateReg(GPRArgRegs, 4))
1832           ;
1833         return;
1834       }
1835
1836       // First register for byval parameter is the first register that wasn't
1837       // allocated before this method call, so it would be "reg".
1838       // If parameter is small enough to be saved in range [reg, r4), then
1839       // the end (first after last) register would be reg + param-size-in-regs,
1840       // else parameter would be splitted between registers and stack,
1841       // end register would be r4 in this case.
1842       unsigned ByValRegBegin = reg;
1843       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1844       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1845       // Note, first register is allocated in the beginning of function already,
1846       // allocate remained amount of registers we need.
1847       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1848         State->AllocateReg(GPRArgRegs, 4);
1849       // A byval parameter that is split between registers and memory needs its
1850       // size truncated here.
1851       // In the case where the entire structure fits in registers, we set the
1852       // size in memory to zero.
1853       if (size < excess)
1854         size = 0;
1855       else
1856         size -= excess;
1857     }
1858   }
1859 }
1860
1861 /// MatchingStackOffset - Return true if the given stack call argument is
1862 /// already available in the same position (relatively) of the caller's
1863 /// incoming argument stack.
1864 static
1865 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1866                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1867                          const TargetInstrInfo *TII) {
1868   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1869   int FI = INT_MAX;
1870   if (Arg.getOpcode() == ISD::CopyFromReg) {
1871     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1872     if (!TargetRegisterInfo::isVirtualRegister(VR))
1873       return false;
1874     MachineInstr *Def = MRI->getVRegDef(VR);
1875     if (!Def)
1876       return false;
1877     if (!Flags.isByVal()) {
1878       if (!TII->isLoadFromStackSlot(Def, FI))
1879         return false;
1880     } else {
1881       return false;
1882     }
1883   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1884     if (Flags.isByVal())
1885       // ByVal argument is passed in as a pointer but it's now being
1886       // dereferenced. e.g.
1887       // define @foo(%struct.X* %A) {
1888       //   tail call @bar(%struct.X* byval %A)
1889       // }
1890       return false;
1891     SDValue Ptr = Ld->getBasePtr();
1892     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1893     if (!FINode)
1894       return false;
1895     FI = FINode->getIndex();
1896   } else
1897     return false;
1898
1899   assert(FI != INT_MAX);
1900   if (!MFI->isFixedObjectIndex(FI))
1901     return false;
1902   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1903 }
1904
1905 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1906 /// for tail call optimization. Targets which want to do tail call
1907 /// optimization should implement this function.
1908 bool
1909 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1910                                                      CallingConv::ID CalleeCC,
1911                                                      bool isVarArg,
1912                                                      bool isCalleeStructRet,
1913                                                      bool isCallerStructRet,
1914                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1915                                     const SmallVectorImpl<SDValue> &OutVals,
1916                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1917                                                      SelectionDAG& DAG) const {
1918   const Function *CallerF = DAG.getMachineFunction().getFunction();
1919   CallingConv::ID CallerCC = CallerF->getCallingConv();
1920   bool CCMatch = CallerCC == CalleeCC;
1921
1922   // Look for obvious safe cases to perform tail call optimization that do not
1923   // require ABI changes. This is what gcc calls sibcall.
1924
1925   // Do not sibcall optimize vararg calls unless the call site is not passing
1926   // any arguments.
1927   if (isVarArg && !Outs.empty())
1928     return false;
1929
1930   // Exception-handling functions need a special set of instructions to indicate
1931   // a return to the hardware. Tail-calling another function would probably
1932   // break this.
1933   if (CallerF->hasFnAttribute("interrupt"))
1934     return false;
1935
1936   // Also avoid sibcall optimization if either caller or callee uses struct
1937   // return semantics.
1938   if (isCalleeStructRet || isCallerStructRet)
1939     return false;
1940
1941   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1942   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1943   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1944   // support in the assembler and linker to be used. This would need to be
1945   // fixed to fully support tail calls in Thumb1.
1946   //
1947   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1948   // LR.  This means if we need to reload LR, it takes an extra instructions,
1949   // which outweighs the value of the tail call; but here we don't know yet
1950   // whether LR is going to be used.  Probably the right approach is to
1951   // generate the tail call here and turn it back into CALL/RET in
1952   // emitEpilogue if LR is used.
1953
1954   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1955   // but we need to make sure there are enough registers; the only valid
1956   // registers are the 4 used for parameters.  We don't currently do this
1957   // case.
1958   if (Subtarget->isThumb1Only())
1959     return false;
1960
1961   // If the calling conventions do not match, then we'd better make sure the
1962   // results are returned in the same way as what the caller expects.
1963   if (!CCMatch) {
1964     SmallVector<CCValAssign, 16> RVLocs1;
1965     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
1966                        *DAG.getContext(), Call);
1967     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1968
1969     SmallVector<CCValAssign, 16> RVLocs2;
1970     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
1971                        *DAG.getContext(), Call);
1972     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1973
1974     if (RVLocs1.size() != RVLocs2.size())
1975       return false;
1976     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1977       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1978         return false;
1979       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1980         return false;
1981       if (RVLocs1[i].isRegLoc()) {
1982         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1983           return false;
1984       } else {
1985         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1986           return false;
1987       }
1988     }
1989   }
1990
1991   // If Caller's vararg or byval argument has been split between registers and
1992   // stack, do not perform tail call, since part of the argument is in caller's
1993   // local frame.
1994   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1995                                       getInfo<ARMFunctionInfo>();
1996   if (AFI_Caller->getArgRegsSaveSize())
1997     return false;
1998
1999   // If the callee takes no arguments then go on to check the results of the
2000   // call.
2001   if (!Outs.empty()) {
2002     // Check if stack adjustment is needed. For now, do not do this if any
2003     // argument is passed on the stack.
2004     SmallVector<CCValAssign, 16> ArgLocs;
2005     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2006                       *DAG.getContext(), Call);
2007     CCInfo.AnalyzeCallOperands(Outs,
2008                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2009     if (CCInfo.getNextStackOffset()) {
2010       MachineFunction &MF = DAG.getMachineFunction();
2011
2012       // Check if the arguments are already laid out in the right way as
2013       // the caller's fixed stack objects.
2014       MachineFrameInfo *MFI = MF.getFrameInfo();
2015       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2016       const TargetInstrInfo *TII =
2017           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2018       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2019            i != e;
2020            ++i, ++realArgIdx) {
2021         CCValAssign &VA = ArgLocs[i];
2022         EVT RegVT = VA.getLocVT();
2023         SDValue Arg = OutVals[realArgIdx];
2024         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2025         if (VA.getLocInfo() == CCValAssign::Indirect)
2026           return false;
2027         if (VA.needsCustom()) {
2028           // f64 and vector types are split into multiple registers or
2029           // register/stack-slot combinations.  The types will not match
2030           // the registers; give up on memory f64 refs until we figure
2031           // out what to do about this.
2032           if (!VA.isRegLoc())
2033             return false;
2034           if (!ArgLocs[++i].isRegLoc())
2035             return false;
2036           if (RegVT == MVT::v2f64) {
2037             if (!ArgLocs[++i].isRegLoc())
2038               return false;
2039             if (!ArgLocs[++i].isRegLoc())
2040               return false;
2041           }
2042         } else if (!VA.isRegLoc()) {
2043           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2044                                    MFI, MRI, TII))
2045             return false;
2046         }
2047       }
2048     }
2049   }
2050
2051   return true;
2052 }
2053
2054 bool
2055 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2056                                   MachineFunction &MF, bool isVarArg,
2057                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2058                                   LLVMContext &Context) const {
2059   SmallVector<CCValAssign, 16> RVLocs;
2060   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2061   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2062                                                     isVarArg));
2063 }
2064
2065 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2066                                     SDLoc DL, SelectionDAG &DAG) {
2067   const MachineFunction &MF = DAG.getMachineFunction();
2068   const Function *F = MF.getFunction();
2069
2070   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2071
2072   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2073   // version of the "preferred return address". These offsets affect the return
2074   // instruction if this is a return from PL1 without hypervisor extensions.
2075   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2076   //    SWI:     0      "subs pc, lr, #0"
2077   //    ABORT:   +4     "subs pc, lr, #4"
2078   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2079   // UNDEF varies depending on where the exception came from ARM or Thumb
2080   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2081
2082   int64_t LROffset;
2083   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2084       IntKind == "ABORT")
2085     LROffset = 4;
2086   else if (IntKind == "SWI" || IntKind == "UNDEF")
2087     LROffset = 0;
2088   else
2089     report_fatal_error("Unsupported interrupt attribute. If present, value "
2090                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2091
2092   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2093
2094   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2095 }
2096
2097 SDValue
2098 ARMTargetLowering::LowerReturn(SDValue Chain,
2099                                CallingConv::ID CallConv, bool isVarArg,
2100                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2101                                const SmallVectorImpl<SDValue> &OutVals,
2102                                SDLoc dl, SelectionDAG &DAG) const {
2103
2104   // CCValAssign - represent the assignment of the return value to a location.
2105   SmallVector<CCValAssign, 16> RVLocs;
2106
2107   // CCState - Info about the registers and stack slots.
2108   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2109                     *DAG.getContext(), Call);
2110
2111   // Analyze outgoing return values.
2112   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2113                                                isVarArg));
2114
2115   SDValue Flag;
2116   SmallVector<SDValue, 4> RetOps;
2117   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2118   bool isLittleEndian = Subtarget->isLittle();
2119
2120   MachineFunction &MF = DAG.getMachineFunction();
2121   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2122   AFI->setReturnRegsCount(RVLocs.size());
2123
2124   // Copy the result values into the output registers.
2125   for (unsigned i = 0, realRVLocIdx = 0;
2126        i != RVLocs.size();
2127        ++i, ++realRVLocIdx) {
2128     CCValAssign &VA = RVLocs[i];
2129     assert(VA.isRegLoc() && "Can only return in registers!");
2130
2131     SDValue Arg = OutVals[realRVLocIdx];
2132
2133     switch (VA.getLocInfo()) {
2134     default: llvm_unreachable("Unknown loc info!");
2135     case CCValAssign::Full: break;
2136     case CCValAssign::BCvt:
2137       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2138       break;
2139     }
2140
2141     if (VA.needsCustom()) {
2142       if (VA.getLocVT() == MVT::v2f64) {
2143         // Extract the first half and return it in two registers.
2144         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2145                                    DAG.getConstant(0, MVT::i32));
2146         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2147                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2148
2149         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2150                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2151                                  Flag);
2152         Flag = Chain.getValue(1);
2153         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2154         VA = RVLocs[++i]; // skip ahead to next loc
2155         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2156                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2157                                  Flag);
2158         Flag = Chain.getValue(1);
2159         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2160         VA = RVLocs[++i]; // skip ahead to next loc
2161
2162         // Extract the 2nd half and fall through to handle it as an f64 value.
2163         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2164                           DAG.getConstant(1, MVT::i32));
2165       }
2166       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2167       // available.
2168       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2169                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2170       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2171                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2172                                Flag);
2173       Flag = Chain.getValue(1);
2174       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175       VA = RVLocs[++i]; // skip ahead to next loc
2176       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2177                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2178                                Flag);
2179     } else
2180       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2181
2182     // Guarantee that all emitted copies are
2183     // stuck together, avoiding something bad.
2184     Flag = Chain.getValue(1);
2185     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2186   }
2187
2188   // Update chain and glue.
2189   RetOps[0] = Chain;
2190   if (Flag.getNode())
2191     RetOps.push_back(Flag);
2192
2193   // CPUs which aren't M-class use a special sequence to return from
2194   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2195   // though we use "subs pc, lr, #N").
2196   //
2197   // M-class CPUs actually use a normal return sequence with a special
2198   // (hardware-provided) value in LR, so the normal code path works.
2199   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2200       !Subtarget->isMClass()) {
2201     if (Subtarget->isThumb1Only())
2202       report_fatal_error("interrupt attribute is not supported in Thumb1");
2203     return LowerInterruptReturn(RetOps, dl, DAG);
2204   }
2205
2206   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2207 }
2208
2209 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2210   if (N->getNumValues() != 1)
2211     return false;
2212   if (!N->hasNUsesOfValue(1, 0))
2213     return false;
2214
2215   SDValue TCChain = Chain;
2216   SDNode *Copy = *N->use_begin();
2217   if (Copy->getOpcode() == ISD::CopyToReg) {
2218     // If the copy has a glue operand, we conservatively assume it isn't safe to
2219     // perform a tail call.
2220     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2221       return false;
2222     TCChain = Copy->getOperand(0);
2223   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2224     SDNode *VMov = Copy;
2225     // f64 returned in a pair of GPRs.
2226     SmallPtrSet<SDNode*, 2> Copies;
2227     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2228          UI != UE; ++UI) {
2229       if (UI->getOpcode() != ISD::CopyToReg)
2230         return false;
2231       Copies.insert(*UI);
2232     }
2233     if (Copies.size() > 2)
2234       return false;
2235
2236     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2237          UI != UE; ++UI) {
2238       SDValue UseChain = UI->getOperand(0);
2239       if (Copies.count(UseChain.getNode()))
2240         // Second CopyToReg
2241         Copy = *UI;
2242       else
2243         // First CopyToReg
2244         TCChain = UseChain;
2245     }
2246   } else if (Copy->getOpcode() == ISD::BITCAST) {
2247     // f32 returned in a single GPR.
2248     if (!Copy->hasOneUse())
2249       return false;
2250     Copy = *Copy->use_begin();
2251     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2252       return false;
2253     TCChain = Copy->getOperand(0);
2254   } else {
2255     return false;
2256   }
2257
2258   bool HasRet = false;
2259   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2260        UI != UE; ++UI) {
2261     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2262         UI->getOpcode() != ARMISD::INTRET_FLAG)
2263       return false;
2264     HasRet = true;
2265   }
2266
2267   if (!HasRet)
2268     return false;
2269
2270   Chain = TCChain;
2271   return true;
2272 }
2273
2274 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2275   if (!Subtarget->supportsTailCall())
2276     return false;
2277
2278   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2279     return false;
2280
2281   return !Subtarget->isThumb1Only();
2282 }
2283
2284 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2285 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2286 // one of the above mentioned nodes. It has to be wrapped because otherwise
2287 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2288 // be used to form addressing mode. These wrapped nodes will be selected
2289 // into MOVi.
2290 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2291   EVT PtrVT = Op.getValueType();
2292   // FIXME there is no actual debug info here
2293   SDLoc dl(Op);
2294   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2295   SDValue Res;
2296   if (CP->isMachineConstantPoolEntry())
2297     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2298                                     CP->getAlignment());
2299   else
2300     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2301                                     CP->getAlignment());
2302   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2303 }
2304
2305 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2306   return MachineJumpTableInfo::EK_Inline;
2307 }
2308
2309 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2310                                              SelectionDAG &DAG) const {
2311   MachineFunction &MF = DAG.getMachineFunction();
2312   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2313   unsigned ARMPCLabelIndex = 0;
2314   SDLoc DL(Op);
2315   EVT PtrVT = getPointerTy();
2316   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2317   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2318   SDValue CPAddr;
2319   if (RelocM == Reloc::Static) {
2320     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2321   } else {
2322     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2323     ARMPCLabelIndex = AFI->createPICLabelUId();
2324     ARMConstantPoolValue *CPV =
2325       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2326                                       ARMCP::CPBlockAddress, PCAdj);
2327     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2328   }
2329   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2330   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2331                                MachinePointerInfo::getConstantPool(),
2332                                false, false, false, 0);
2333   if (RelocM == Reloc::Static)
2334     return Result;
2335   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2336   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2337 }
2338
2339 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2340 SDValue
2341 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2342                                                  SelectionDAG &DAG) const {
2343   SDLoc dl(GA);
2344   EVT PtrVT = getPointerTy();
2345   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2346   MachineFunction &MF = DAG.getMachineFunction();
2347   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2348   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2349   ARMConstantPoolValue *CPV =
2350     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2351                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2352   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2353   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2354   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2355                          MachinePointerInfo::getConstantPool(),
2356                          false, false, false, 0);
2357   SDValue Chain = Argument.getValue(1);
2358
2359   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2360   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2361
2362   // call __tls_get_addr.
2363   ArgListTy Args;
2364   ArgListEntry Entry;
2365   Entry.Node = Argument;
2366   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2367   Args.push_back(Entry);
2368
2369   // FIXME: is there useful debug info available here?
2370   TargetLowering::CallLoweringInfo CLI(DAG);
2371   CLI.setDebugLoc(dl).setChain(Chain)
2372     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2373                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2374                0);
2375
2376   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2377   return CallResult.first;
2378 }
2379
2380 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2381 // "local exec" model.
2382 SDValue
2383 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2384                                         SelectionDAG &DAG,
2385                                         TLSModel::Model model) const {
2386   const GlobalValue *GV = GA->getGlobal();
2387   SDLoc dl(GA);
2388   SDValue Offset;
2389   SDValue Chain = DAG.getEntryNode();
2390   EVT PtrVT = getPointerTy();
2391   // Get the Thread Pointer
2392   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2393
2394   if (model == TLSModel::InitialExec) {
2395     MachineFunction &MF = DAG.getMachineFunction();
2396     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2397     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2398     // Initial exec model.
2399     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2400     ARMConstantPoolValue *CPV =
2401       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2402                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2403                                       true);
2404     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2405     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2406     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2407                          MachinePointerInfo::getConstantPool(),
2408                          false, false, false, 0);
2409     Chain = Offset.getValue(1);
2410
2411     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2412     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2413
2414     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2415                          MachinePointerInfo::getConstantPool(),
2416                          false, false, false, 0);
2417   } else {
2418     // local exec model
2419     assert(model == TLSModel::LocalExec);
2420     ARMConstantPoolValue *CPV =
2421       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2422     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2423     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2424     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2425                          MachinePointerInfo::getConstantPool(),
2426                          false, false, false, 0);
2427   }
2428
2429   // The address of the thread local variable is the add of the thread
2430   // pointer with the offset of the variable.
2431   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2432 }
2433
2434 SDValue
2435 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2436   // TODO: implement the "local dynamic" model
2437   assert(Subtarget->isTargetELF() &&
2438          "TLS not implemented for non-ELF targets");
2439   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2440
2441   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2442
2443   switch (model) {
2444     case TLSModel::GeneralDynamic:
2445     case TLSModel::LocalDynamic:
2446       return LowerToTLSGeneralDynamicModel(GA, DAG);
2447     case TLSModel::InitialExec:
2448     case TLSModel::LocalExec:
2449       return LowerToTLSExecModels(GA, DAG, model);
2450   }
2451   llvm_unreachable("bogus TLS model");
2452 }
2453
2454 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2455                                                  SelectionDAG &DAG) const {
2456   EVT PtrVT = getPointerTy();
2457   SDLoc dl(Op);
2458   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2459   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2460     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2461     ARMConstantPoolValue *CPV =
2462       ARMConstantPoolConstant::Create(GV,
2463                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2464     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2465     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2466     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2467                                  CPAddr,
2468                                  MachinePointerInfo::getConstantPool(),
2469                                  false, false, false, 0);
2470     SDValue Chain = Result.getValue(1);
2471     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2472     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2473     if (!UseGOTOFF)
2474       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2475                            MachinePointerInfo::getGOT(),
2476                            false, false, false, 0);
2477     return Result;
2478   }
2479
2480   // If we have T2 ops, we can materialize the address directly via movt/movw
2481   // pair. This is always cheaper.
2482   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2483     ++NumMovwMovt;
2484     // FIXME: Once remat is capable of dealing with instructions with register
2485     // operands, expand this into two nodes.
2486     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2487                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2488   } else {
2489     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2490     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2491     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2492                        MachinePointerInfo::getConstantPool(),
2493                        false, false, false, 0);
2494   }
2495 }
2496
2497 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2498                                                     SelectionDAG &DAG) const {
2499   EVT PtrVT = getPointerTy();
2500   SDLoc dl(Op);
2501   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2502   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2503
2504   if (Subtarget->useMovt(DAG.getMachineFunction()))
2505     ++NumMovwMovt;
2506
2507   // FIXME: Once remat is capable of dealing with instructions with register
2508   // operands, expand this into multiple nodes
2509   unsigned Wrapper =
2510       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2511
2512   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2513   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2514
2515   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2516     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2517                          MachinePointerInfo::getGOT(), false, false, false, 0);
2518   return Result;
2519 }
2520
2521 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2522                                                      SelectionDAG &DAG) const {
2523   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2524   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2525          "Windows on ARM expects to use movw/movt");
2526
2527   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2528   const ARMII::TOF TargetFlags =
2529     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2530   EVT PtrVT = getPointerTy();
2531   SDValue Result;
2532   SDLoc DL(Op);
2533
2534   ++NumMovwMovt;
2535
2536   // FIXME: Once remat is capable of dealing with instructions with register
2537   // operands, expand this into two nodes.
2538   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2539                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2540                                                   TargetFlags));
2541   if (GV->hasDLLImportStorageClass())
2542     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2543                          MachinePointerInfo::getGOT(), false, false, false, 0);
2544   return Result;
2545 }
2546
2547 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2548                                                     SelectionDAG &DAG) const {
2549   assert(Subtarget->isTargetELF() &&
2550          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2553   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2554   EVT PtrVT = getPointerTy();
2555   SDLoc dl(Op);
2556   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2557   ARMConstantPoolValue *CPV =
2558     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2559                                   ARMPCLabelIndex, PCAdj);
2560   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2561   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2562   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2563                                MachinePointerInfo::getConstantPool(),
2564                                false, false, false, 0);
2565   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2566   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2567 }
2568
2569 SDValue
2570 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2571   SDLoc dl(Op);
2572   SDValue Val = DAG.getConstant(0, MVT::i32);
2573   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2574                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2575                      Op.getOperand(1), Val);
2576 }
2577
2578 SDValue
2579 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2580   SDLoc dl(Op);
2581   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2582                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2583 }
2584
2585 SDValue
2586 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2587                                           const ARMSubtarget *Subtarget) const {
2588   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2589   SDLoc dl(Op);
2590   switch (IntNo) {
2591   default: return SDValue();    // Don't custom lower most intrinsics.
2592   case Intrinsic::arm_rbit: {
2593     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2594            "RBIT intrinsic must have i32 type!");
2595     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2596   }
2597   case Intrinsic::arm_thread_pointer: {
2598     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2599     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2600   }
2601   case Intrinsic::eh_sjlj_lsda: {
2602     MachineFunction &MF = DAG.getMachineFunction();
2603     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2605     EVT PtrVT = getPointerTy();
2606     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2607     SDValue CPAddr;
2608     unsigned PCAdj = (RelocM != Reloc::PIC_)
2609       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2610     ARMConstantPoolValue *CPV =
2611       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2612                                       ARMCP::CPLSDA, PCAdj);
2613     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2614     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2615     SDValue Result =
2616       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2617                   MachinePointerInfo::getConstantPool(),
2618                   false, false, false, 0);
2619
2620     if (RelocM == Reloc::PIC_) {
2621       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2622       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2623     }
2624     return Result;
2625   }
2626   case Intrinsic::arm_neon_vmulls:
2627   case Intrinsic::arm_neon_vmullu: {
2628     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2629       ? ARMISD::VMULLs : ARMISD::VMULLu;
2630     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2631                        Op.getOperand(1), Op.getOperand(2));
2632   }
2633   }
2634 }
2635
2636 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2637                                  const ARMSubtarget *Subtarget) {
2638   // FIXME: handle "fence singlethread" more efficiently.
2639   SDLoc dl(Op);
2640   if (!Subtarget->hasDataBarrier()) {
2641     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2642     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2643     // here.
2644     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2645            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2646     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2647                        DAG.getConstant(0, MVT::i32));
2648   }
2649
2650   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2651   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2652   unsigned Domain = ARM_MB::ISH;
2653   if (Subtarget->isMClass()) {
2654     // Only a full system barrier exists in the M-class architectures.
2655     Domain = ARM_MB::SY;
2656   } else if (Subtarget->isSwift() && Ord == Release) {
2657     // Swift happens to implement ISHST barriers in a way that's compatible with
2658     // Release semantics but weaker than ISH so we'd be fools not to use
2659     // it. Beware: other processors probably don't!
2660     Domain = ARM_MB::ISHST;
2661   }
2662
2663   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2664                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2665                      DAG.getConstant(Domain, MVT::i32));
2666 }
2667
2668 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2669                              const ARMSubtarget *Subtarget) {
2670   // ARM pre v5TE and Thumb1 does not have preload instructions.
2671   if (!(Subtarget->isThumb2() ||
2672         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2673     // Just preserve the chain.
2674     return Op.getOperand(0);
2675
2676   SDLoc dl(Op);
2677   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2678   if (!isRead &&
2679       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2680     // ARMv7 with MP extension has PLDW.
2681     return Op.getOperand(0);
2682
2683   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2684   if (Subtarget->isThumb()) {
2685     // Invert the bits.
2686     isRead = ~isRead & 1;
2687     isData = ~isData & 1;
2688   }
2689
2690   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2691                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2692                      DAG.getConstant(isData, MVT::i32));
2693 }
2694
2695 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2696   MachineFunction &MF = DAG.getMachineFunction();
2697   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2698
2699   // vastart just stores the address of the VarArgsFrameIndex slot into the
2700   // memory location argument.
2701   SDLoc dl(Op);
2702   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2703   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2704   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2705   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2706                       MachinePointerInfo(SV), false, false, 0);
2707 }
2708
2709 SDValue
2710 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2711                                         SDValue &Root, SelectionDAG &DAG,
2712                                         SDLoc dl) const {
2713   MachineFunction &MF = DAG.getMachineFunction();
2714   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2715
2716   const TargetRegisterClass *RC;
2717   if (AFI->isThumb1OnlyFunction())
2718     RC = &ARM::tGPRRegClass;
2719   else
2720     RC = &ARM::GPRRegClass;
2721
2722   // Transform the arguments stored in physical registers into virtual ones.
2723   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2725
2726   SDValue ArgValue2;
2727   if (NextVA.isMemLoc()) {
2728     MachineFrameInfo *MFI = MF.getFrameInfo();
2729     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2730
2731     // Create load node to retrieve arguments from the stack.
2732     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2733     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2734                             MachinePointerInfo::getFixedStack(FI),
2735                             false, false, false, 0);
2736   } else {
2737     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2738     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2739   }
2740   if (!Subtarget->isLittle())
2741     std::swap (ArgValue, ArgValue2);
2742   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2743 }
2744
2745 void
2746 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2747                                   unsigned InRegsParamRecordIdx,
2748                                   unsigned ArgSize,
2749                                   unsigned &ArgRegsSize,
2750                                   unsigned &ArgRegsSaveSize)
2751   const {
2752   unsigned NumGPRs;
2753   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2754     unsigned RBegin, REnd;
2755     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2756     NumGPRs = REnd - RBegin;
2757   } else {
2758     unsigned int firstUnalloced;
2759     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2760                                                 sizeof(GPRArgRegs) /
2761                                                 sizeof(GPRArgRegs[0]));
2762     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2763   }
2764
2765   unsigned Align = MF.getTarget()
2766                        .getSubtargetImpl()
2767                        ->getFrameLowering()
2768                        ->getStackAlignment();
2769   ArgRegsSize = NumGPRs * 4;
2770
2771   // If parameter is split between stack and GPRs...
2772   if (NumGPRs && Align > 4 &&
2773       (ArgRegsSize < ArgSize ||
2774         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2775     // Add padding for part of param recovered from GPRs.  For example,
2776     // if Align == 8, its last byte must be at address K*8 - 1.
2777     // We need to do it, since remained (stack) part of parameter has
2778     // stack alignment, and we need to "attach" "GPRs head" without gaps
2779     // to it:
2780     // Stack:
2781     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2782     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2783     //
2784     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2785     unsigned Padding =
2786         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2787     ArgRegsSaveSize = ArgRegsSize + Padding;
2788   } else
2789     // We don't need to extend regs save size for byval parameters if they
2790     // are passed via GPRs only.
2791     ArgRegsSaveSize = ArgRegsSize;
2792 }
2793
2794 // The remaining GPRs hold either the beginning of variable-argument
2795 // data, or the beginning of an aggregate passed by value (usually
2796 // byval).  Either way, we allocate stack slots adjacent to the data
2797 // provided by our caller, and store the unallocated registers there.
2798 // If this is a variadic function, the va_list pointer will begin with
2799 // these values; otherwise, this reassembles a (byval) structure that
2800 // was split between registers and memory.
2801 // Return: The frame index registers were stored into.
2802 int
2803 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2804                                   SDLoc dl, SDValue &Chain,
2805                                   const Value *OrigArg,
2806                                   unsigned InRegsParamRecordIdx,
2807                                   unsigned OffsetFromOrigArg,
2808                                   unsigned ArgOffset,
2809                                   unsigned ArgSize,
2810                                   bool ForceMutable,
2811                                   unsigned ByValStoreOffset,
2812                                   unsigned TotalArgRegsSaveSize) const {
2813
2814   // Currently, two use-cases possible:
2815   // Case #1. Non-var-args function, and we meet first byval parameter.
2816   //          Setup first unallocated register as first byval register;
2817   //          eat all remained registers
2818   //          (these two actions are performed by HandleByVal method).
2819   //          Then, here, we initialize stack frame with
2820   //          "store-reg" instructions.
2821   // Case #2. Var-args function, that doesn't contain byval parameters.
2822   //          The same: eat all remained unallocated registers,
2823   //          initialize stack frame.
2824
2825   MachineFunction &MF = DAG.getMachineFunction();
2826   MachineFrameInfo *MFI = MF.getFrameInfo();
2827   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2828   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2829   unsigned RBegin, REnd;
2830   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2831     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2832     firstRegToSaveIndex = RBegin - ARM::R0;
2833     lastRegToSaveIndex = REnd - ARM::R0;
2834   } else {
2835     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2836       (GPRArgRegs, array_lengthof(GPRArgRegs));
2837     lastRegToSaveIndex = 4;
2838   }
2839
2840   unsigned ArgRegsSize, ArgRegsSaveSize;
2841   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2842                  ArgRegsSize, ArgRegsSaveSize);
2843
2844   // Store any by-val regs to their spots on the stack so that they may be
2845   // loaded by deferencing the result of formal parameter pointer or va_next.
2846   // Note: once stack area for byval/varargs registers
2847   // was initialized, it can't be initialized again.
2848   if (ArgRegsSaveSize) {
2849     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2850
2851     if (Padding) {
2852       assert(AFI->getStoredByValParamsPadding() == 0 &&
2853              "The only parameter may be padded.");
2854       AFI->setStoredByValParamsPadding(Padding);
2855     }
2856
2857     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2858                                             Padding +
2859                                               ByValStoreOffset -
2860                                               (int64_t)TotalArgRegsSaveSize,
2861                                             false);
2862     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2863     if (Padding) {
2864        MFI->CreateFixedObject(Padding,
2865                               ArgOffset + ByValStoreOffset -
2866                                 (int64_t)ArgRegsSaveSize,
2867                               false);
2868     }
2869
2870     SmallVector<SDValue, 4> MemOps;
2871     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2872          ++firstRegToSaveIndex, ++i) {
2873       const TargetRegisterClass *RC;
2874       if (AFI->isThumb1OnlyFunction())
2875         RC = &ARM::tGPRRegClass;
2876       else
2877         RC = &ARM::GPRRegClass;
2878
2879       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2880       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2881       SDValue Store =
2882         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2883                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2884                      false, false, 0);
2885       MemOps.push_back(Store);
2886       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2887                         DAG.getConstant(4, getPointerTy()));
2888     }
2889
2890     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2891
2892     if (!MemOps.empty())
2893       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2894     return FrameIndex;
2895   } else {
2896     if (ArgSize == 0) {
2897       // We cannot allocate a zero-byte object for the first variadic argument,
2898       // so just make up a size.
2899       ArgSize = 4;
2900     }
2901     // This will point to the next argument passed via stack.
2902     return MFI->CreateFixedObject(
2903       ArgSize, ArgOffset, !ForceMutable);
2904   }
2905 }
2906
2907 // Setup stack frame, the va_list pointer will start from.
2908 void
2909 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2910                                         SDLoc dl, SDValue &Chain,
2911                                         unsigned ArgOffset,
2912                                         unsigned TotalArgRegsSaveSize,
2913                                         bool ForceMutable) const {
2914   MachineFunction &MF = DAG.getMachineFunction();
2915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2916
2917   // Try to store any remaining integer argument regs
2918   // to their spots on the stack so that they may be loaded by deferencing
2919   // the result of va_next.
2920   // If there is no regs to be stored, just point address after last
2921   // argument passed via stack.
2922   int FrameIndex =
2923     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2924                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2925                    0, TotalArgRegsSaveSize);
2926
2927   AFI->setVarArgsFrameIndex(FrameIndex);
2928 }
2929
2930 SDValue
2931 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2932                                         CallingConv::ID CallConv, bool isVarArg,
2933                                         const SmallVectorImpl<ISD::InputArg>
2934                                           &Ins,
2935                                         SDLoc dl, SelectionDAG &DAG,
2936                                         SmallVectorImpl<SDValue> &InVals)
2937                                           const {
2938   MachineFunction &MF = DAG.getMachineFunction();
2939   MachineFrameInfo *MFI = MF.getFrameInfo();
2940
2941   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2942
2943   // Assign locations to all of the incoming arguments.
2944   SmallVector<CCValAssign, 16> ArgLocs;
2945   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2946                     *DAG.getContext(), Prologue);
2947   CCInfo.AnalyzeFormalArguments(Ins,
2948                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2949                                                   isVarArg));
2950
2951   SmallVector<SDValue, 16> ArgValues;
2952   int lastInsIndex = -1;
2953   SDValue ArgValue;
2954   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2955   unsigned CurArgIdx = 0;
2956
2957   // Initially ArgRegsSaveSize is zero.
2958   // Then we increase this value each time we meet byval parameter.
2959   // We also increase this value in case of varargs function.
2960   AFI->setArgRegsSaveSize(0);
2961
2962   unsigned ByValStoreOffset = 0;
2963   unsigned TotalArgRegsSaveSize = 0;
2964   unsigned ArgRegsSaveSizeMaxAlign = 4;
2965
2966   // Calculate the amount of stack space that we need to allocate to store
2967   // byval and variadic arguments that are passed in registers.
2968   // We need to know this before we allocate the first byval or variadic
2969   // argument, as they will be allocated a stack slot below the CFA (Canonical
2970   // Frame Address, the stack pointer at entry to the function).
2971   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2972     CCValAssign &VA = ArgLocs[i];
2973     if (VA.isMemLoc()) {
2974       int index = VA.getValNo();
2975       if (index != lastInsIndex) {
2976         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2977         if (Flags.isByVal()) {
2978           unsigned ExtraArgRegsSize;
2979           unsigned ExtraArgRegsSaveSize;
2980           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2981                          Flags.getByValSize(),
2982                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2983
2984           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2985           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2986               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2987           CCInfo.nextInRegsParam();
2988         }
2989         lastInsIndex = index;
2990       }
2991     }
2992   }
2993   CCInfo.rewindByValRegsInfo();
2994   lastInsIndex = -1;
2995   if (isVarArg) {
2996     unsigned ExtraArgRegsSize;
2997     unsigned ExtraArgRegsSaveSize;
2998     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2999                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3000     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3001   }
3002   // If the arg regs save area contains N-byte aligned values, the
3003   // bottom of it must be at least N-byte aligned.
3004   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3005   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3006
3007   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3008     CCValAssign &VA = ArgLocs[i];
3009     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3010     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3011     // Arguments stored in registers.
3012     if (VA.isRegLoc()) {
3013       EVT RegVT = VA.getLocVT();
3014
3015       if (VA.needsCustom()) {
3016         // f64 and vector types are split up into multiple registers or
3017         // combinations of registers and stack slots.
3018         if (VA.getLocVT() == MVT::v2f64) {
3019           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3020                                                    Chain, DAG, dl);
3021           VA = ArgLocs[++i]; // skip ahead to next loc
3022           SDValue ArgValue2;
3023           if (VA.isMemLoc()) {
3024             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3025             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3026             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3027                                     MachinePointerInfo::getFixedStack(FI),
3028                                     false, false, false, 0);
3029           } else {
3030             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3031                                              Chain, DAG, dl);
3032           }
3033           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3034           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3035                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3036           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3037                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3038         } else
3039           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3040
3041       } else {
3042         const TargetRegisterClass *RC;
3043
3044         if (RegVT == MVT::f32)
3045           RC = &ARM::SPRRegClass;
3046         else if (RegVT == MVT::f64)
3047           RC = &ARM::DPRRegClass;
3048         else if (RegVT == MVT::v2f64)
3049           RC = &ARM::QPRRegClass;
3050         else if (RegVT == MVT::i32)
3051           RC = AFI->isThumb1OnlyFunction() ?
3052             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3053             (const TargetRegisterClass*)&ARM::GPRRegClass;
3054         else
3055           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3056
3057         // Transform the arguments in physical registers into virtual ones.
3058         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3059         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3060       }
3061
3062       // If this is an 8 or 16-bit value, it is really passed promoted
3063       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3064       // truncate to the right size.
3065       switch (VA.getLocInfo()) {
3066       default: llvm_unreachable("Unknown loc info!");
3067       case CCValAssign::Full: break;
3068       case CCValAssign::BCvt:
3069         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3070         break;
3071       case CCValAssign::SExt:
3072         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3073                                DAG.getValueType(VA.getValVT()));
3074         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3075         break;
3076       case CCValAssign::ZExt:
3077         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3078                                DAG.getValueType(VA.getValVT()));
3079         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3080         break;
3081       }
3082
3083       InVals.push_back(ArgValue);
3084
3085     } else { // VA.isRegLoc()
3086
3087       // sanity check
3088       assert(VA.isMemLoc());
3089       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3090
3091       int index = ArgLocs[i].getValNo();
3092
3093       // Some Ins[] entries become multiple ArgLoc[] entries.
3094       // Process them only once.
3095       if (index != lastInsIndex)
3096         {
3097           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3098           // FIXME: For now, all byval parameter objects are marked mutable.
3099           // This can be changed with more analysis.
3100           // In case of tail call optimization mark all arguments mutable.
3101           // Since they could be overwritten by lowering of arguments in case of
3102           // a tail call.
3103           if (Flags.isByVal()) {
3104             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3105
3106             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3107             int FrameIndex = StoreByValRegs(
3108                 CCInfo, DAG, dl, Chain, CurOrigArg,
3109                 CurByValIndex,
3110                 Ins[VA.getValNo()].PartOffset,
3111                 VA.getLocMemOffset(),
3112                 Flags.getByValSize(),
3113                 true /*force mutable frames*/,
3114                 ByValStoreOffset,
3115                 TotalArgRegsSaveSize);
3116             ByValStoreOffset += Flags.getByValSize();
3117             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3118             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3119             CCInfo.nextInRegsParam();
3120           } else {
3121             unsigned FIOffset = VA.getLocMemOffset();
3122             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3123                                             FIOffset, true);
3124
3125             // Create load nodes to retrieve arguments from the stack.
3126             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3127             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3128                                          MachinePointerInfo::getFixedStack(FI),
3129                                          false, false, false, 0));
3130           }
3131           lastInsIndex = index;
3132         }
3133     }
3134   }
3135
3136   // varargs
3137   if (isVarArg)
3138     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3139                          CCInfo.getNextStackOffset(),
3140                          TotalArgRegsSaveSize);
3141
3142   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3143
3144   return Chain;
3145 }
3146
3147 /// isFloatingPointZero - Return true if this is +0.0.
3148 static bool isFloatingPointZero(SDValue Op) {
3149   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3150     return CFP->getValueAPF().isPosZero();
3151   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3152     // Maybe this has already been legalized into the constant pool?
3153     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3154       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3155       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3156         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3157           return CFP->getValueAPF().isPosZero();
3158     }
3159   }
3160   return false;
3161 }
3162
3163 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3164 /// the given operands.
3165 SDValue
3166 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3167                              SDValue &ARMcc, SelectionDAG &DAG,
3168                              SDLoc dl) const {
3169   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3170     unsigned C = RHSC->getZExtValue();
3171     if (!isLegalICmpImmediate(C)) {
3172       // Constant does not fit, try adjusting it by one?
3173       switch (CC) {
3174       default: break;
3175       case ISD::SETLT:
3176       case ISD::SETGE:
3177         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3178           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3179           RHS = DAG.getConstant(C-1, MVT::i32);
3180         }
3181         break;
3182       case ISD::SETULT:
3183       case ISD::SETUGE:
3184         if (C != 0 && isLegalICmpImmediate(C-1)) {
3185           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3186           RHS = DAG.getConstant(C-1, MVT::i32);
3187         }
3188         break;
3189       case ISD::SETLE:
3190       case ISD::SETGT:
3191         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3192           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3193           RHS = DAG.getConstant(C+1, MVT::i32);
3194         }
3195         break;
3196       case ISD::SETULE:
3197       case ISD::SETUGT:
3198         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3199           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3200           RHS = DAG.getConstant(C+1, MVT::i32);
3201         }
3202         break;
3203       }
3204     }
3205   }
3206
3207   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3208   ARMISD::NodeType CompareType;
3209   switch (CondCode) {
3210   default:
3211     CompareType = ARMISD::CMP;
3212     break;
3213   case ARMCC::EQ:
3214   case ARMCC::NE:
3215     // Uses only Z Flag
3216     CompareType = ARMISD::CMPZ;
3217     break;
3218   }
3219   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3220   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3221 }
3222
3223 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3224 SDValue
3225 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3226                              SDLoc dl) const {
3227   SDValue Cmp;
3228   if (!isFloatingPointZero(RHS))
3229     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3230   else
3231     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3232   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3233 }
3234
3235 /// duplicateCmp - Glue values can have only one use, so this function
3236 /// duplicates a comparison node.
3237 SDValue
3238 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3239   unsigned Opc = Cmp.getOpcode();
3240   SDLoc DL(Cmp);
3241   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3242     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3243
3244   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3245   Cmp = Cmp.getOperand(0);
3246   Opc = Cmp.getOpcode();
3247   if (Opc == ARMISD::CMPFP)
3248     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3249   else {
3250     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3251     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3252   }
3253   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3254 }
3255
3256 std::pair<SDValue, SDValue>
3257 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3258                                  SDValue &ARMcc) const {
3259   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3260
3261   SDValue Value, OverflowCmp;
3262   SDValue LHS = Op.getOperand(0);
3263   SDValue RHS = Op.getOperand(1);
3264
3265
3266   // FIXME: We are currently always generating CMPs because we don't support
3267   // generating CMN through the backend. This is not as good as the natural
3268   // CMP case because it causes a register dependency and cannot be folded
3269   // later.
3270
3271   switch (Op.getOpcode()) {
3272   default:
3273     llvm_unreachable("Unknown overflow instruction!");
3274   case ISD::SADDO:
3275     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3276     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3277     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3278     break;
3279   case ISD::UADDO:
3280     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3281     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3282     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3283     break;
3284   case ISD::SSUBO:
3285     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3286     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3287     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3288     break;
3289   case ISD::USUBO:
3290     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3291     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3292     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3293     break;
3294   } // switch (...)
3295
3296   return std::make_pair(Value, OverflowCmp);
3297 }
3298
3299
3300 SDValue
3301 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3302   // Let legalize expand this if it isn't a legal type yet.
3303   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3304     return SDValue();
3305
3306   SDValue Value, OverflowCmp;
3307   SDValue ARMcc;
3308   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3309   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3310   // We use 0 and 1 as false and true values.
3311   SDValue TVal = DAG.getConstant(1, MVT::i32);
3312   SDValue FVal = DAG.getConstant(0, MVT::i32);
3313   EVT VT = Op.getValueType();
3314
3315   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3316                                  ARMcc, CCR, OverflowCmp);
3317
3318   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3319   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3320 }
3321
3322
3323 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3324   SDValue Cond = Op.getOperand(0);
3325   SDValue SelectTrue = Op.getOperand(1);
3326   SDValue SelectFalse = Op.getOperand(2);
3327   SDLoc dl(Op);
3328   unsigned Opc = Cond.getOpcode();
3329
3330   if (Cond.getResNo() == 1 &&
3331       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3332        Opc == ISD::USUBO)) {
3333     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3334       return SDValue();
3335
3336     SDValue Value, OverflowCmp;
3337     SDValue ARMcc;
3338     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3339     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3340     EVT VT = Op.getValueType();
3341
3342     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3343                        ARMcc, CCR, OverflowCmp);
3344
3345   }
3346
3347   // Convert:
3348   //
3349   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3350   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3351   //
3352   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3353     const ConstantSDNode *CMOVTrue =
3354       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3355     const ConstantSDNode *CMOVFalse =
3356       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3357
3358     if (CMOVTrue && CMOVFalse) {
3359       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3360       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3361
3362       SDValue True;
3363       SDValue False;
3364       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3365         True = SelectTrue;
3366         False = SelectFalse;
3367       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3368         True = SelectFalse;
3369         False = SelectTrue;
3370       }
3371
3372       if (True.getNode() && False.getNode()) {
3373         EVT VT = Op.getValueType();
3374         SDValue ARMcc = Cond.getOperand(2);
3375         SDValue CCR = Cond.getOperand(3);
3376         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3377         assert(True.getValueType() == VT);
3378         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3379       }
3380     }
3381   }
3382
3383   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3384   // undefined bits before doing a full-word comparison with zero.
3385   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3386                      DAG.getConstant(1, Cond.getValueType()));
3387
3388   return DAG.getSelectCC(dl, Cond,
3389                          DAG.getConstant(0, Cond.getValueType()),
3390                          SelectTrue, SelectFalse, ISD::SETNE);
3391 }
3392
3393 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3394   if (CC == ISD::SETNE)
3395     return ISD::SETEQ;
3396   return ISD::getSetCCInverse(CC, true);
3397 }
3398
3399 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3400                                  bool &swpCmpOps, bool &swpVselOps) {
3401   // Start by selecting the GE condition code for opcodes that return true for
3402   // 'equality'
3403   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3404       CC == ISD::SETULE)
3405     CondCode = ARMCC::GE;
3406
3407   // and GT for opcodes that return false for 'equality'.
3408   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3409            CC == ISD::SETULT)
3410     CondCode = ARMCC::GT;
3411
3412   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3413   // to swap the compare operands.
3414   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3415       CC == ISD::SETULT)
3416     swpCmpOps = true;
3417
3418   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3419   // If we have an unordered opcode, we need to swap the operands to the VSEL
3420   // instruction (effectively negating the condition).
3421   //
3422   // This also has the effect of swapping which one of 'less' or 'greater'
3423   // returns true, so we also swap the compare operands. It also switches
3424   // whether we return true for 'equality', so we compensate by picking the
3425   // opposite condition code to our original choice.
3426   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3427       CC == ISD::SETUGT) {
3428     swpCmpOps = !swpCmpOps;
3429     swpVselOps = !swpVselOps;
3430     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3431   }
3432
3433   // 'ordered' is 'anything but unordered', so use the VS condition code and
3434   // swap the VSEL operands.
3435   if (CC == ISD::SETO) {
3436     CondCode = ARMCC::VS;
3437     swpVselOps = true;
3438   }
3439
3440   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3441   // code and swap the VSEL operands.
3442   if (CC == ISD::SETUNE) {
3443     CondCode = ARMCC::EQ;
3444     swpVselOps = true;
3445   }
3446 }
3447
3448 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3449   EVT VT = Op.getValueType();
3450   SDValue LHS = Op.getOperand(0);
3451   SDValue RHS = Op.getOperand(1);
3452   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3453   SDValue TrueVal = Op.getOperand(2);
3454   SDValue FalseVal = Op.getOperand(3);
3455   SDLoc dl(Op);
3456
3457   if (LHS.getValueType() == MVT::i32) {
3458     // Try to generate VSEL on ARMv8.
3459     // The VSEL instruction can't use all the usual ARM condition
3460     // codes: it only has two bits to select the condition code, so it's
3461     // constrained to use only GE, GT, VS and EQ.
3462     //
3463     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3464     // swap the operands of the previous compare instruction (effectively
3465     // inverting the compare condition, swapping 'less' and 'greater') and
3466     // sometimes need to swap the operands to the VSEL (which inverts the
3467     // condition in the sense of firing whenever the previous condition didn't)
3468     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3469                                       TrueVal.getValueType() == MVT::f64)) {
3470       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3471       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3472           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3473         CC = getInverseCCForVSEL(CC);
3474         std::swap(TrueVal, FalseVal);
3475       }
3476     }
3477
3478     SDValue ARMcc;
3479     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3480     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3481     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3482                        Cmp);
3483   }
3484
3485   ARMCC::CondCodes CondCode, CondCode2;
3486   FPCCToARMCC(CC, CondCode, CondCode2);
3487
3488   // Try to generate VSEL on ARMv8.
3489   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3490                                     TrueVal.getValueType() == MVT::f64)) {
3491     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3492     // same operands, as follows:
3493     //   c = fcmp [ogt, olt, ugt, ult] a, b
3494     //   select c, a, b
3495     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3496     // handled differently than the original code sequence.
3497     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3498         RHS == FalseVal) {
3499       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3500         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3501       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3502         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3503     }
3504
3505     bool swpCmpOps = false;
3506     bool swpVselOps = false;
3507     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3508
3509     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3510         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3511       if (swpCmpOps)
3512         std::swap(LHS, RHS);
3513       if (swpVselOps)
3514         std::swap(TrueVal, FalseVal);
3515     }
3516   }
3517
3518   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3519   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3520   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3521   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3522                                ARMcc, CCR, Cmp);
3523   if (CondCode2 != ARMCC::AL) {
3524     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3525     // FIXME: Needs another CMP because flag can have but one use.
3526     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3527     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3528                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3529   }
3530   return Result;
3531 }
3532
3533 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3534 /// to morph to an integer compare sequence.
3535 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3536                            const ARMSubtarget *Subtarget) {
3537   SDNode *N = Op.getNode();
3538   if (!N->hasOneUse())
3539     // Otherwise it requires moving the value from fp to integer registers.
3540     return false;
3541   if (!N->getNumValues())
3542     return false;
3543   EVT VT = Op.getValueType();
3544   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3545     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3546     // vmrs are very slow, e.g. cortex-a8.
3547     return false;
3548
3549   if (isFloatingPointZero(Op)) {
3550     SeenZero = true;
3551     return true;
3552   }
3553   return ISD::isNormalLoad(N);
3554 }
3555
3556 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3557   if (isFloatingPointZero(Op))
3558     return DAG.getConstant(0, MVT::i32);
3559
3560   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3561     return DAG.getLoad(MVT::i32, SDLoc(Op),
3562                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3563                        Ld->isVolatile(), Ld->isNonTemporal(),
3564                        Ld->isInvariant(), Ld->getAlignment());
3565
3566   llvm_unreachable("Unknown VFP cmp argument!");
3567 }
3568
3569 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3570                            SDValue &RetVal1, SDValue &RetVal2) {
3571   if (isFloatingPointZero(Op)) {
3572     RetVal1 = DAG.getConstant(0, MVT::i32);
3573     RetVal2 = DAG.getConstant(0, MVT::i32);
3574     return;
3575   }
3576
3577   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3578     SDValue Ptr = Ld->getBasePtr();
3579     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3580                           Ld->getChain(), Ptr,
3581                           Ld->getPointerInfo(),
3582                           Ld->isVolatile(), Ld->isNonTemporal(),
3583                           Ld->isInvariant(), Ld->getAlignment());
3584
3585     EVT PtrType = Ptr.getValueType();
3586     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3587     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3588                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3589     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3590                           Ld->getChain(), NewPtr,
3591                           Ld->getPointerInfo().getWithOffset(4),
3592                           Ld->isVolatile(), Ld->isNonTemporal(),
3593                           Ld->isInvariant(), NewAlign);
3594     return;
3595   }
3596
3597   llvm_unreachable("Unknown VFP cmp argument!");
3598 }
3599
3600 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3601 /// f32 and even f64 comparisons to integer ones.
3602 SDValue
3603 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3604   SDValue Chain = Op.getOperand(0);
3605   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3606   SDValue LHS = Op.getOperand(2);
3607   SDValue RHS = Op.getOperand(3);
3608   SDValue Dest = Op.getOperand(4);
3609   SDLoc dl(Op);
3610
3611   bool LHSSeenZero = false;
3612   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3613   bool RHSSeenZero = false;
3614   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3615   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3616     // If unsafe fp math optimization is enabled and there are no other uses of
3617     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3618     // to an integer comparison.
3619     if (CC == ISD::SETOEQ)
3620       CC = ISD::SETEQ;
3621     else if (CC == ISD::SETUNE)
3622       CC = ISD::SETNE;
3623
3624     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3625     SDValue ARMcc;
3626     if (LHS.getValueType() == MVT::f32) {
3627       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3628                         bitcastf32Toi32(LHS, DAG), Mask);
3629       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3630                         bitcastf32Toi32(RHS, DAG), Mask);
3631       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3632       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3633       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3634                          Chain, Dest, ARMcc, CCR, Cmp);
3635     }
3636
3637     SDValue LHS1, LHS2;
3638     SDValue RHS1, RHS2;
3639     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3640     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3641     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3642     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3643     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3644     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3645     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3646     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3647     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3648   }
3649
3650   return SDValue();
3651 }
3652
3653 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3654   SDValue Chain = Op.getOperand(0);
3655   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3656   SDValue LHS = Op.getOperand(2);
3657   SDValue RHS = Op.getOperand(3);
3658   SDValue Dest = Op.getOperand(4);
3659   SDLoc dl(Op);
3660
3661   if (LHS.getValueType() == MVT::i32) {
3662     SDValue ARMcc;
3663     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3664     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3665     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3666                        Chain, Dest, ARMcc, CCR, Cmp);
3667   }
3668
3669   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3670
3671   if (getTargetMachine().Options.UnsafeFPMath &&
3672       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3673        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3674     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3675     if (Result.getNode())
3676       return Result;
3677   }
3678
3679   ARMCC::CondCodes CondCode, CondCode2;
3680   FPCCToARMCC(CC, CondCode, CondCode2);
3681
3682   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3683   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3684   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3685   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3686   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3687   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3688   if (CondCode2 != ARMCC::AL) {
3689     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3690     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3691     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3692   }
3693   return Res;
3694 }
3695
3696 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3697   SDValue Chain = Op.getOperand(0);
3698   SDValue Table = Op.getOperand(1);
3699   SDValue Index = Op.getOperand(2);
3700   SDLoc dl(Op);
3701
3702   EVT PTy = getPointerTy();
3703   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3704   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3705   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3706   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3707   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3708   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3709   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3710   if (Subtarget->isThumb2()) {
3711     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3712     // which does another jump to the destination. This also makes it easier
3713     // to translate it to TBB / TBH later.
3714     // FIXME: This might not work if the function is extremely large.
3715     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3716                        Addr, Op.getOperand(2), JTI, UId);
3717   }
3718   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3719     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3720                        MachinePointerInfo::getJumpTable(),
3721                        false, false, false, 0);
3722     Chain = Addr.getValue(1);
3723     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3724     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3725   } else {
3726     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3727                        MachinePointerInfo::getJumpTable(),
3728                        false, false, false, 0);
3729     Chain = Addr.getValue(1);
3730     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3731   }
3732 }
3733
3734 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3735   EVT VT = Op.getValueType();
3736   SDLoc dl(Op);
3737
3738   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3739     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3740       return Op;
3741     return DAG.UnrollVectorOp(Op.getNode());
3742   }
3743
3744   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3745          "Invalid type for custom lowering!");
3746   if (VT != MVT::v4i16)
3747     return DAG.UnrollVectorOp(Op.getNode());
3748
3749   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3750   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3751 }
3752
3753 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3754   EVT VT = Op.getValueType();
3755   if (VT.isVector())
3756     return LowerVectorFP_TO_INT(Op, DAG);
3757
3758   SDLoc dl(Op);
3759   unsigned Opc;
3760
3761   switch (Op.getOpcode()) {
3762   default: llvm_unreachable("Invalid opcode!");
3763   case ISD::FP_TO_SINT:
3764     Opc = ARMISD::FTOSI;
3765     break;
3766   case ISD::FP_TO_UINT:
3767     Opc = ARMISD::FTOUI;
3768     break;
3769   }
3770   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3771   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3772 }
3773
3774 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3775   EVT VT = Op.getValueType();
3776   SDLoc dl(Op);
3777
3778   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3779     if (VT.getVectorElementType() == MVT::f32)
3780       return Op;
3781     return DAG.UnrollVectorOp(Op.getNode());
3782   }
3783
3784   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3785          "Invalid type for custom lowering!");
3786   if (VT != MVT::v4f32)
3787     return DAG.UnrollVectorOp(Op.getNode());
3788
3789   unsigned CastOpc;
3790   unsigned Opc;
3791   switch (Op.getOpcode()) {
3792   default: llvm_unreachable("Invalid opcode!");
3793   case ISD::SINT_TO_FP:
3794     CastOpc = ISD::SIGN_EXTEND;
3795     Opc = ISD::SINT_TO_FP;
3796     break;
3797   case ISD::UINT_TO_FP:
3798     CastOpc = ISD::ZERO_EXTEND;
3799     Opc = ISD::UINT_TO_FP;
3800     break;
3801   }
3802
3803   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3804   return DAG.getNode(Opc, dl, VT, Op);
3805 }
3806
3807 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3808   EVT VT = Op.getValueType();
3809   if (VT.isVector())
3810     return LowerVectorINT_TO_FP(Op, DAG);
3811
3812   SDLoc dl(Op);
3813   unsigned Opc;
3814
3815   switch (Op.getOpcode()) {
3816   default: llvm_unreachable("Invalid opcode!");
3817   case ISD::SINT_TO_FP:
3818     Opc = ARMISD::SITOF;
3819     break;
3820   case ISD::UINT_TO_FP:
3821     Opc = ARMISD::UITOF;
3822     break;
3823   }
3824
3825   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3826   return DAG.getNode(Opc, dl, VT, Op);
3827 }
3828
3829 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3830   // Implement fcopysign with a fabs and a conditional fneg.
3831   SDValue Tmp0 = Op.getOperand(0);
3832   SDValue Tmp1 = Op.getOperand(1);
3833   SDLoc dl(Op);
3834   EVT VT = Op.getValueType();
3835   EVT SrcVT = Tmp1.getValueType();
3836   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3837     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3838   bool UseNEON = !InGPR && Subtarget->hasNEON();
3839
3840   if (UseNEON) {
3841     // Use VBSL to copy the sign bit.
3842     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3843     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3844                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3845     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3846     if (VT == MVT::f64)
3847       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3848                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3849                          DAG.getConstant(32, MVT::i32));
3850     else /*if (VT == MVT::f32)*/
3851       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3852     if (SrcVT == MVT::f32) {
3853       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3854       if (VT == MVT::f64)
3855         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3856                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3857                            DAG.getConstant(32, MVT::i32));
3858     } else if (VT == MVT::f32)
3859       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3860                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3861                          DAG.getConstant(32, MVT::i32));
3862     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3863     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3864
3865     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3866                                             MVT::i32);
3867     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3868     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3869                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3870
3871     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3872                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3873                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3874     if (VT == MVT::f32) {
3875       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3876       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3877                         DAG.getConstant(0, MVT::i32));
3878     } else {
3879       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3880     }
3881
3882     return Res;
3883   }
3884
3885   // Bitcast operand 1 to i32.
3886   if (SrcVT == MVT::f64)
3887     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3888                        Tmp1).getValue(1);
3889   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3890
3891   // Or in the signbit with integer operations.
3892   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3893   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3894   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3895   if (VT == MVT::f32) {
3896     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3897                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3898     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3899                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3900   }
3901
3902   // f64: Or the high part with signbit and then combine two parts.
3903   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3904                      Tmp0);
3905   SDValue Lo = Tmp0.getValue(0);
3906   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3907   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3908   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3909 }
3910
3911 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3912   MachineFunction &MF = DAG.getMachineFunction();
3913   MachineFrameInfo *MFI = MF.getFrameInfo();
3914   MFI->setReturnAddressIsTaken(true);
3915
3916   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3917     return SDValue();
3918
3919   EVT VT = Op.getValueType();
3920   SDLoc dl(Op);
3921   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3922   if (Depth) {
3923     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3924     SDValue Offset = DAG.getConstant(4, MVT::i32);
3925     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3926                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3927                        MachinePointerInfo(), false, false, false, 0);
3928   }
3929
3930   // Return LR, which contains the return address. Mark it an implicit live-in.
3931   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3932   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3933 }
3934
3935 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3936   const ARMBaseRegisterInfo &ARI =
3937     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3938   MachineFunction &MF = DAG.getMachineFunction();
3939   MachineFrameInfo *MFI = MF.getFrameInfo();
3940   MFI->setFrameAddressIsTaken(true);
3941
3942   EVT VT = Op.getValueType();
3943   SDLoc dl(Op);  // FIXME probably not meaningful
3944   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3945   unsigned FrameReg = ARI.getFrameRegister(MF);
3946   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3947   while (Depth--)
3948     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3949                             MachinePointerInfo(),
3950                             false, false, false, 0);
3951   return FrameAddr;
3952 }
3953
3954 // FIXME? Maybe this could be a TableGen attribute on some registers and
3955 // this table could be generated automatically from RegInfo.
3956 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3957                                               EVT VT) const {
3958   unsigned Reg = StringSwitch<unsigned>(RegName)
3959                        .Case("sp", ARM::SP)
3960                        .Default(0);
3961   if (Reg)
3962     return Reg;
3963   report_fatal_error("Invalid register name global variable");
3964 }
3965
3966 /// ExpandBITCAST - If the target supports VFP, this function is called to
3967 /// expand a bit convert where either the source or destination type is i64 to
3968 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3969 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3970 /// vectors), since the legalizer won't know what to do with that.
3971 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3972   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3973   SDLoc dl(N);
3974   SDValue Op = N->getOperand(0);
3975
3976   // This function is only supposed to be called for i64 types, either as the
3977   // source or destination of the bit convert.
3978   EVT SrcVT = Op.getValueType();
3979   EVT DstVT = N->getValueType(0);
3980   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3981          "ExpandBITCAST called for non-i64 type");
3982
3983   // Turn i64->f64 into VMOVDRR.
3984   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3985     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3986                              DAG.getConstant(0, MVT::i32));
3987     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3988                              DAG.getConstant(1, MVT::i32));
3989     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3990                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3991   }
3992
3993   // Turn f64->i64 into VMOVRRD.
3994   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3995     SDValue Cvt;
3996     if (TLI.isBigEndian() && SrcVT.isVector() &&
3997         SrcVT.getVectorNumElements() > 1)
3998       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3999                         DAG.getVTList(MVT::i32, MVT::i32),
4000                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4001     else
4002       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4003                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4004     // Merge the pieces into a single i64 value.
4005     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4006   }
4007
4008   return SDValue();
4009 }
4010
4011 /// getZeroVector - Returns a vector of specified type with all zero elements.
4012 /// Zero vectors are used to represent vector negation and in those cases
4013 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4014 /// not support i64 elements, so sometimes the zero vectors will need to be
4015 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4016 /// zero vector.
4017 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4018   assert(VT.isVector() && "Expected a vector type");
4019   // The canonical modified immediate encoding of a zero vector is....0!
4020   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4021   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4022   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4023   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4024 }
4025
4026 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4027 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4028 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4029                                                 SelectionDAG &DAG) const {
4030   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4031   EVT VT = Op.getValueType();
4032   unsigned VTBits = VT.getSizeInBits();
4033   SDLoc dl(Op);
4034   SDValue ShOpLo = Op.getOperand(0);
4035   SDValue ShOpHi = Op.getOperand(1);
4036   SDValue ShAmt  = Op.getOperand(2);
4037   SDValue ARMcc;
4038   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4039
4040   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4041
4042   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4043                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4044   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4045   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4046                                    DAG.getConstant(VTBits, MVT::i32));
4047   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4048   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4049   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4050
4051   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4052   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4053                           ARMcc, DAG, dl);
4054   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4055   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4056                            CCR, Cmp);
4057
4058   SDValue Ops[2] = { Lo, Hi };
4059   return DAG.getMergeValues(Ops, dl);
4060 }
4061
4062 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4063 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4064 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4065                                                SelectionDAG &DAG) const {
4066   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4067   EVT VT = Op.getValueType();
4068   unsigned VTBits = VT.getSizeInBits();
4069   SDLoc dl(Op);
4070   SDValue ShOpLo = Op.getOperand(0);
4071   SDValue ShOpHi = Op.getOperand(1);
4072   SDValue ShAmt  = Op.getOperand(2);
4073   SDValue ARMcc;
4074
4075   assert(Op.getOpcode() == ISD::SHL_PARTS);
4076   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4077                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4078   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4079   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4080                                    DAG.getConstant(VTBits, MVT::i32));
4081   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4082   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4083
4084   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4085   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4086   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4087                           ARMcc, DAG, dl);
4088   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4089   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4090                            CCR, Cmp);
4091
4092   SDValue Ops[2] = { Lo, Hi };
4093   return DAG.getMergeValues(Ops, dl);
4094 }
4095
4096 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4097                                             SelectionDAG &DAG) const {
4098   // The rounding mode is in bits 23:22 of the FPSCR.
4099   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4100   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4101   // so that the shift + and get folded into a bitfield extract.
4102   SDLoc dl(Op);
4103   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4104                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4105                                               MVT::i32));
4106   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4107                                   DAG.getConstant(1U << 22, MVT::i32));
4108   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4109                               DAG.getConstant(22, MVT::i32));
4110   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4111                      DAG.getConstant(3, MVT::i32));
4112 }
4113
4114 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4115                          const ARMSubtarget *ST) {
4116   EVT VT = N->getValueType(0);
4117   SDLoc dl(N);
4118
4119   if (!ST->hasV6T2Ops())
4120     return SDValue();
4121
4122   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4123   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4124 }
4125
4126 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4127 /// for each 16-bit element from operand, repeated.  The basic idea is to
4128 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4129 ///
4130 /// Trace for v4i16:
4131 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4132 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4133 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4134 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4135 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4136 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4137 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4138 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4139 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4140   EVT VT = N->getValueType(0);
4141   SDLoc DL(N);
4142
4143   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4144   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4145   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4146   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4147   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4148   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4149 }
4150
4151 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4152 /// bit-count for each 16-bit element from the operand.  We need slightly
4153 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4154 /// 64/128-bit registers.
4155 ///
4156 /// Trace for v4i16:
4157 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4158 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4159 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4160 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4161 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4162   EVT VT = N->getValueType(0);
4163   SDLoc DL(N);
4164
4165   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4166   if (VT.is64BitVector()) {
4167     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4168     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4169                        DAG.getIntPtrConstant(0));
4170   } else {
4171     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4172                                     BitCounts, DAG.getIntPtrConstant(0));
4173     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4174   }
4175 }
4176
4177 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4178 /// bit-count for each 32-bit element from the operand.  The idea here is
4179 /// to split the vector into 16-bit elements, leverage the 16-bit count
4180 /// routine, and then combine the results.
4181 ///
4182 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4183 /// input    = [v0    v1    ] (vi: 32-bit elements)
4184 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4185 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4186 /// vrev: N0 = [k1 k0 k3 k2 ]
4187 ///            [k0 k1 k2 k3 ]
4188 ///       N1 =+[k1 k0 k3 k2 ]
4189 ///            [k0 k2 k1 k3 ]
4190 ///       N2 =+[k1 k3 k0 k2 ]
4191 ///            [k0    k2    k1    k3    ]
4192 /// Extended =+[k1    k3    k0    k2    ]
4193 ///            [k0    k2    ]
4194 /// Extracted=+[k1    k3    ]
4195 ///
4196 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4197   EVT VT = N->getValueType(0);
4198   SDLoc DL(N);
4199
4200   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4201
4202   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4203   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4204   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4205   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4206   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4207
4208   if (VT.is64BitVector()) {
4209     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4210     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4211                        DAG.getIntPtrConstant(0));
4212   } else {
4213     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4214                                     DAG.getIntPtrConstant(0));
4215     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4216   }
4217 }
4218
4219 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4220                           const ARMSubtarget *ST) {
4221   EVT VT = N->getValueType(0);
4222
4223   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4224   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4225           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4226          "Unexpected type for custom ctpop lowering");
4227
4228   if (VT.getVectorElementType() == MVT::i32)
4229     return lowerCTPOP32BitElements(N, DAG);
4230   else
4231     return lowerCTPOP16BitElements(N, DAG);
4232 }
4233
4234 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4235                           const ARMSubtarget *ST) {
4236   EVT VT = N->getValueType(0);
4237   SDLoc dl(N);
4238
4239   if (!VT.isVector())
4240     return SDValue();
4241
4242   // Lower vector shifts on NEON to use VSHL.
4243   assert(ST->hasNEON() && "unexpected vector shift");
4244
4245   // Left shifts translate directly to the vshiftu intrinsic.
4246   if (N->getOpcode() == ISD::SHL)
4247     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4248                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4249                        N->getOperand(0), N->getOperand(1));
4250
4251   assert((N->getOpcode() == ISD::SRA ||
4252           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4253
4254   // NEON uses the same intrinsics for both left and right shifts.  For
4255   // right shifts, the shift amounts are negative, so negate the vector of
4256   // shift amounts.
4257   EVT ShiftVT = N->getOperand(1).getValueType();
4258   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4259                                      getZeroVector(ShiftVT, DAG, dl),
4260                                      N->getOperand(1));
4261   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4262                              Intrinsic::arm_neon_vshifts :
4263                              Intrinsic::arm_neon_vshiftu);
4264   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4265                      DAG.getConstant(vshiftInt, MVT::i32),
4266                      N->getOperand(0), NegatedCount);
4267 }
4268
4269 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4270                                 const ARMSubtarget *ST) {
4271   EVT VT = N->getValueType(0);
4272   SDLoc dl(N);
4273
4274   // We can get here for a node like i32 = ISD::SHL i32, i64
4275   if (VT != MVT::i64)
4276     return SDValue();
4277
4278   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4279          "Unknown shift to lower!");
4280
4281   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4282   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4283       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4284     return SDValue();
4285
4286   // If we are in thumb mode, we don't have RRX.
4287   if (ST->isThumb1Only()) return SDValue();
4288
4289   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4290   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4291                            DAG.getConstant(0, MVT::i32));
4292   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4293                            DAG.getConstant(1, MVT::i32));
4294
4295   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4296   // captures the result into a carry flag.
4297   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4298   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4299
4300   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4301   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4302
4303   // Merge the pieces into a single i64 value.
4304  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4305 }
4306
4307 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4308   SDValue TmpOp0, TmpOp1;
4309   bool Invert = false;
4310   bool Swap = false;
4311   unsigned Opc = 0;
4312
4313   SDValue Op0 = Op.getOperand(0);
4314   SDValue Op1 = Op.getOperand(1);
4315   SDValue CC = Op.getOperand(2);
4316   EVT VT = Op.getValueType();
4317   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4318   SDLoc dl(Op);
4319
4320   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4321     switch (SetCCOpcode) {
4322     default: llvm_unreachable("Illegal FP comparison");
4323     case ISD::SETUNE:
4324     case ISD::SETNE:  Invert = true; // Fallthrough
4325     case ISD::SETOEQ:
4326     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4327     case ISD::SETOLT:
4328     case ISD::SETLT: Swap = true; // Fallthrough
4329     case ISD::SETOGT:
4330     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4331     case ISD::SETOLE:
4332     case ISD::SETLE:  Swap = true; // Fallthrough
4333     case ISD::SETOGE:
4334     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4335     case ISD::SETUGE: Swap = true; // Fallthrough
4336     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4337     case ISD::SETUGT: Swap = true; // Fallthrough
4338     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4339     case ISD::SETUEQ: Invert = true; // Fallthrough
4340     case ISD::SETONE:
4341       // Expand this to (OLT | OGT).
4342       TmpOp0 = Op0;
4343       TmpOp1 = Op1;
4344       Opc = ISD::OR;
4345       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4346       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4347       break;
4348     case ISD::SETUO: Invert = true; // Fallthrough
4349     case ISD::SETO:
4350       // Expand this to (OLT | OGE).
4351       TmpOp0 = Op0;
4352       TmpOp1 = Op1;
4353       Opc = ISD::OR;
4354       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4355       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4356       break;
4357     }
4358   } else {
4359     // Integer comparisons.
4360     switch (SetCCOpcode) {
4361     default: llvm_unreachable("Illegal integer comparison");
4362     case ISD::SETNE:  Invert = true;
4363     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4364     case ISD::SETLT:  Swap = true;
4365     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4366     case ISD::SETLE:  Swap = true;
4367     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4368     case ISD::SETULT: Swap = true;
4369     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4370     case ISD::SETULE: Swap = true;
4371     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4372     }
4373
4374     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4375     if (Opc == ARMISD::VCEQ) {
4376
4377       SDValue AndOp;
4378       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4379         AndOp = Op0;
4380       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4381         AndOp = Op1;
4382
4383       // Ignore bitconvert.
4384       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4385         AndOp = AndOp.getOperand(0);
4386
4387       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4388         Opc = ARMISD::VTST;
4389         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4390         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4391         Invert = !Invert;
4392       }
4393     }
4394   }
4395
4396   if (Swap)
4397     std::swap(Op0, Op1);
4398
4399   // If one of the operands is a constant vector zero, attempt to fold the
4400   // comparison to a specialized compare-against-zero form.
4401   SDValue SingleOp;
4402   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4403     SingleOp = Op0;
4404   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4405     if (Opc == ARMISD::VCGE)
4406       Opc = ARMISD::VCLEZ;
4407     else if (Opc == ARMISD::VCGT)
4408       Opc = ARMISD::VCLTZ;
4409     SingleOp = Op1;
4410   }
4411
4412   SDValue Result;
4413   if (SingleOp.getNode()) {
4414     switch (Opc) {
4415     case ARMISD::VCEQ:
4416       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4417     case ARMISD::VCGE:
4418       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4419     case ARMISD::VCLEZ:
4420       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4421     case ARMISD::VCGT:
4422       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4423     case ARMISD::VCLTZ:
4424       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4425     default:
4426       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4427     }
4428   } else {
4429      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4430   }
4431
4432   if (Invert)
4433     Result = DAG.getNOT(dl, Result, VT);
4434
4435   return Result;
4436 }
4437
4438 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4439 /// valid vector constant for a NEON instruction with a "modified immediate"
4440 /// operand (e.g., VMOV).  If so, return the encoded value.
4441 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4442                                  unsigned SplatBitSize, SelectionDAG &DAG,
4443                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4444   unsigned OpCmode, Imm;
4445
4446   // SplatBitSize is set to the smallest size that splats the vector, so a
4447   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4448   // immediate instructions others than VMOV do not support the 8-bit encoding
4449   // of a zero vector, and the default encoding of zero is supposed to be the
4450   // 32-bit version.
4451   if (SplatBits == 0)
4452     SplatBitSize = 32;
4453
4454   switch (SplatBitSize) {
4455   case 8:
4456     if (type != VMOVModImm)
4457       return SDValue();
4458     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4459     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4460     OpCmode = 0xe;
4461     Imm = SplatBits;
4462     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4463     break;
4464
4465   case 16:
4466     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4467     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4468     if ((SplatBits & ~0xff) == 0) {
4469       // Value = 0x00nn: Op=x, Cmode=100x.
4470       OpCmode = 0x8;
4471       Imm = SplatBits;
4472       break;
4473     }
4474     if ((SplatBits & ~0xff00) == 0) {
4475       // Value = 0xnn00: Op=x, Cmode=101x.
4476       OpCmode = 0xa;
4477       Imm = SplatBits >> 8;
4478       break;
4479     }
4480     return SDValue();
4481
4482   case 32:
4483     // NEON's 32-bit VMOV supports splat values where:
4484     // * only one byte is nonzero, or
4485     // * the least significant byte is 0xff and the second byte is nonzero, or
4486     // * the least significant 2 bytes are 0xff and the third is nonzero.
4487     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4488     if ((SplatBits & ~0xff) == 0) {
4489       // Value = 0x000000nn: Op=x, Cmode=000x.
4490       OpCmode = 0;
4491       Imm = SplatBits;
4492       break;
4493     }
4494     if ((SplatBits & ~0xff00) == 0) {
4495       // Value = 0x0000nn00: Op=x, Cmode=001x.
4496       OpCmode = 0x2;
4497       Imm = SplatBits >> 8;
4498       break;
4499     }
4500     if ((SplatBits & ~0xff0000) == 0) {
4501       // Value = 0x00nn0000: Op=x, Cmode=010x.
4502       OpCmode = 0x4;
4503       Imm = SplatBits >> 16;
4504       break;
4505     }
4506     if ((SplatBits & ~0xff000000) == 0) {
4507       // Value = 0xnn000000: Op=x, Cmode=011x.
4508       OpCmode = 0x6;
4509       Imm = SplatBits >> 24;
4510       break;
4511     }
4512
4513     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4514     if (type == OtherModImm) return SDValue();
4515
4516     if ((SplatBits & ~0xffff) == 0 &&
4517         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4518       // Value = 0x0000nnff: Op=x, Cmode=1100.
4519       OpCmode = 0xc;
4520       Imm = SplatBits >> 8;
4521       break;
4522     }
4523
4524     if ((SplatBits & ~0xffffff) == 0 &&
4525         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4526       // Value = 0x00nnffff: Op=x, Cmode=1101.
4527       OpCmode = 0xd;
4528       Imm = SplatBits >> 16;
4529       break;
4530     }
4531
4532     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4533     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4534     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4535     // and fall through here to test for a valid 64-bit splat.  But, then the
4536     // caller would also need to check and handle the change in size.
4537     return SDValue();
4538
4539   case 64: {
4540     if (type != VMOVModImm)
4541       return SDValue();
4542     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4543     uint64_t BitMask = 0xff;
4544     uint64_t Val = 0;
4545     unsigned ImmMask = 1;
4546     Imm = 0;
4547     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4548       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4549         Val |= BitMask;
4550         Imm |= ImmMask;
4551       } else if ((SplatBits & BitMask) != 0) {
4552         return SDValue();
4553       }
4554       BitMask <<= 8;
4555       ImmMask <<= 1;
4556     }
4557
4558     if (DAG.getTargetLoweringInfo().isBigEndian())
4559       // swap higher and lower 32 bit word
4560       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4561
4562     // Op=1, Cmode=1110.
4563     OpCmode = 0x1e;
4564     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4565     break;
4566   }
4567
4568   default:
4569     llvm_unreachable("unexpected size for isNEONModifiedImm");
4570   }
4571
4572   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4573   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4574 }
4575
4576 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4577                                            const ARMSubtarget *ST) const {
4578   if (!ST->hasVFP3())
4579     return SDValue();
4580
4581   bool IsDouble = Op.getValueType() == MVT::f64;
4582   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4583
4584   // Try splatting with a VMOV.f32...
4585   APFloat FPVal = CFP->getValueAPF();
4586   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4587
4588   if (ImmVal != -1) {
4589     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4590       // We have code in place to select a valid ConstantFP already, no need to
4591       // do any mangling.
4592       return Op;
4593     }
4594
4595     // It's a float and we are trying to use NEON operations where
4596     // possible. Lower it to a splat followed by an extract.
4597     SDLoc DL(Op);
4598     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4599     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4600                                       NewVal);
4601     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4602                        DAG.getConstant(0, MVT::i32));
4603   }
4604
4605   // The rest of our options are NEON only, make sure that's allowed before
4606   // proceeding..
4607   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4608     return SDValue();
4609
4610   EVT VMovVT;
4611   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4612
4613   // It wouldn't really be worth bothering for doubles except for one very
4614   // important value, which does happen to match: 0.0. So make sure we don't do
4615   // anything stupid.
4616   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4617     return SDValue();
4618
4619   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4620   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4621                                      false, VMOVModImm);
4622   if (NewVal != SDValue()) {
4623     SDLoc DL(Op);
4624     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4625                                       NewVal);
4626     if (IsDouble)
4627       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4628
4629     // It's a float: cast and extract a vector element.
4630     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4631                                        VecConstant);
4632     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4633                        DAG.getConstant(0, MVT::i32));
4634   }
4635
4636   // Finally, try a VMVN.i32
4637   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4638                              false, VMVNModImm);
4639   if (NewVal != SDValue()) {
4640     SDLoc DL(Op);
4641     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4642
4643     if (IsDouble)
4644       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4645
4646     // It's a float: cast and extract a vector element.
4647     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4648                                        VecConstant);
4649     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4650                        DAG.getConstant(0, MVT::i32));
4651   }
4652
4653   return SDValue();
4654 }
4655
4656 // check if an VEXT instruction can handle the shuffle mask when the
4657 // vector sources of the shuffle are the same.
4658 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4659   unsigned NumElts = VT.getVectorNumElements();
4660
4661   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4662   if (M[0] < 0)
4663     return false;
4664
4665   Imm = M[0];
4666
4667   // If this is a VEXT shuffle, the immediate value is the index of the first
4668   // element.  The other shuffle indices must be the successive elements after
4669   // the first one.
4670   unsigned ExpectedElt = Imm;
4671   for (unsigned i = 1; i < NumElts; ++i) {
4672     // Increment the expected index.  If it wraps around, just follow it
4673     // back to index zero and keep going.
4674     ++ExpectedElt;
4675     if (ExpectedElt == NumElts)
4676       ExpectedElt = 0;
4677
4678     if (M[i] < 0) continue; // ignore UNDEF indices
4679     if (ExpectedElt != static_cast<unsigned>(M[i]))
4680       return false;
4681   }
4682
4683   return true;
4684 }
4685
4686
4687 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4688                        bool &ReverseVEXT, unsigned &Imm) {
4689   unsigned NumElts = VT.getVectorNumElements();
4690   ReverseVEXT = false;
4691
4692   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4693   if (M[0] < 0)
4694     return false;
4695
4696   Imm = M[0];
4697
4698   // If this is a VEXT shuffle, the immediate value is the index of the first
4699   // element.  The other shuffle indices must be the successive elements after
4700   // the first one.
4701   unsigned ExpectedElt = Imm;
4702   for (unsigned i = 1; i < NumElts; ++i) {
4703     // Increment the expected index.  If it wraps around, it may still be
4704     // a VEXT but the source vectors must be swapped.
4705     ExpectedElt += 1;
4706     if (ExpectedElt == NumElts * 2) {
4707       ExpectedElt = 0;
4708       ReverseVEXT = true;
4709     }
4710
4711     if (M[i] < 0) continue; // ignore UNDEF indices
4712     if (ExpectedElt != static_cast<unsigned>(M[i]))
4713       return false;
4714   }
4715
4716   // Adjust the index value if the source operands will be swapped.
4717   if (ReverseVEXT)
4718     Imm -= NumElts;
4719
4720   return true;
4721 }
4722
4723 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4724 /// instruction with the specified blocksize.  (The order of the elements
4725 /// within each block of the vector is reversed.)
4726 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4727   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4728          "Only possible block sizes for VREV are: 16, 32, 64");
4729
4730   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4731   if (EltSz == 64)
4732     return false;
4733
4734   unsigned NumElts = VT.getVectorNumElements();
4735   unsigned BlockElts = M[0] + 1;
4736   // If the first shuffle index is UNDEF, be optimistic.
4737   if (M[0] < 0)
4738     BlockElts = BlockSize / EltSz;
4739
4740   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4741     return false;
4742
4743   for (unsigned i = 0; i < NumElts; ++i) {
4744     if (M[i] < 0) continue; // ignore UNDEF indices
4745     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4746       return false;
4747   }
4748
4749   return true;
4750 }
4751
4752 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4753   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4754   // range, then 0 is placed into the resulting vector. So pretty much any mask
4755   // of 8 elements can work here.
4756   return VT == MVT::v8i8 && M.size() == 8;
4757 }
4758
4759 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4760   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4761   if (EltSz == 64)
4762     return false;
4763
4764   unsigned NumElts = VT.getVectorNumElements();
4765   WhichResult = (M[0] == 0 ? 0 : 1);
4766   for (unsigned i = 0; i < NumElts; i += 2) {
4767     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4768         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4769       return false;
4770   }
4771   return true;
4772 }
4773
4774 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4775 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4776 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4777 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4778   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4779   if (EltSz == 64)
4780     return false;
4781
4782   unsigned NumElts = VT.getVectorNumElements();
4783   WhichResult = (M[0] == 0 ? 0 : 1);
4784   for (unsigned i = 0; i < NumElts; i += 2) {
4785     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4786         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4787       return false;
4788   }
4789   return true;
4790 }
4791
4792 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4793   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4794   if (EltSz == 64)
4795     return false;
4796
4797   unsigned NumElts = VT.getVectorNumElements();
4798   WhichResult = (M[0] == 0 ? 0 : 1);
4799   for (unsigned i = 0; i != NumElts; ++i) {
4800     if (M[i] < 0) continue; // ignore UNDEF indices
4801     if ((unsigned) M[i] != 2 * i + WhichResult)
4802       return false;
4803   }
4804
4805   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4806   if (VT.is64BitVector() && EltSz == 32)
4807     return false;
4808
4809   return true;
4810 }
4811
4812 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4813 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4814 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4815 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4816   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4817   if (EltSz == 64)
4818     return false;
4819
4820   unsigned Half = VT.getVectorNumElements() / 2;
4821   WhichResult = (M[0] == 0 ? 0 : 1);
4822   for (unsigned j = 0; j != 2; ++j) {
4823     unsigned Idx = WhichResult;
4824     for (unsigned i = 0; i != Half; ++i) {
4825       int MIdx = M[i + j * Half];
4826       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4827         return false;
4828       Idx += 2;
4829     }
4830   }
4831
4832   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4833   if (VT.is64BitVector() && EltSz == 32)
4834     return false;
4835
4836   return true;
4837 }
4838
4839 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4840   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4841   if (EltSz == 64)
4842     return false;
4843
4844   unsigned NumElts = VT.getVectorNumElements();
4845   WhichResult = (M[0] == 0 ? 0 : 1);
4846   unsigned Idx = WhichResult * NumElts / 2;
4847   for (unsigned i = 0; i != NumElts; i += 2) {
4848     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4849         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4850       return false;
4851     Idx += 1;
4852   }
4853
4854   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4855   if (VT.is64BitVector() && EltSz == 32)
4856     return false;
4857
4858   return true;
4859 }
4860
4861 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4862 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4863 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4864 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4865   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4866   if (EltSz == 64)
4867     return false;
4868
4869   unsigned NumElts = VT.getVectorNumElements();
4870   WhichResult = (M[0] == 0 ? 0 : 1);
4871   unsigned Idx = WhichResult * NumElts / 2;
4872   for (unsigned i = 0; i != NumElts; i += 2) {
4873     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4874         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4875       return false;
4876     Idx += 1;
4877   }
4878
4879   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4880   if (VT.is64BitVector() && EltSz == 32)
4881     return false;
4882
4883   return true;
4884 }
4885
4886 /// \return true if this is a reverse operation on an vector.
4887 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4888   unsigned NumElts = VT.getVectorNumElements();
4889   // Make sure the mask has the right size.
4890   if (NumElts != M.size())
4891       return false;
4892
4893   // Look for <15, ..., 3, -1, 1, 0>.
4894   for (unsigned i = 0; i != NumElts; ++i)
4895     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4896       return false;
4897
4898   return true;
4899 }
4900
4901 // If N is an integer constant that can be moved into a register in one
4902 // instruction, return an SDValue of such a constant (will become a MOV
4903 // instruction).  Otherwise return null.
4904 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4905                                      const ARMSubtarget *ST, SDLoc dl) {
4906   uint64_t Val;
4907   if (!isa<ConstantSDNode>(N))
4908     return SDValue();
4909   Val = cast<ConstantSDNode>(N)->getZExtValue();
4910
4911   if (ST->isThumb1Only()) {
4912     if (Val <= 255 || ~Val <= 255)
4913       return DAG.getConstant(Val, MVT::i32);
4914   } else {
4915     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4916       return DAG.getConstant(Val, MVT::i32);
4917   }
4918   return SDValue();
4919 }
4920
4921 // If this is a case we can't handle, return null and let the default
4922 // expansion code take care of it.
4923 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4924                                              const ARMSubtarget *ST) const {
4925   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4926   SDLoc dl(Op);
4927   EVT VT = Op.getValueType();
4928
4929   APInt SplatBits, SplatUndef;
4930   unsigned SplatBitSize;
4931   bool HasAnyUndefs;
4932   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4933     if (SplatBitSize <= 64) {
4934       // Check if an immediate VMOV works.
4935       EVT VmovVT;
4936       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4937                                       SplatUndef.getZExtValue(), SplatBitSize,
4938                                       DAG, VmovVT, VT.is128BitVector(),
4939                                       VMOVModImm);
4940       if (Val.getNode()) {
4941         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4942         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4943       }
4944
4945       // Try an immediate VMVN.
4946       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4947       Val = isNEONModifiedImm(NegatedImm,
4948                                       SplatUndef.getZExtValue(), SplatBitSize,
4949                                       DAG, VmovVT, VT.is128BitVector(),
4950                                       VMVNModImm);
4951       if (Val.getNode()) {
4952         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4953         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4954       }
4955
4956       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4957       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4958         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4959         if (ImmVal != -1) {
4960           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4961           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4962         }
4963       }
4964     }
4965   }
4966
4967   // Scan through the operands to see if only one value is used.
4968   //
4969   // As an optimisation, even if more than one value is used it may be more
4970   // profitable to splat with one value then change some lanes.
4971   //
4972   // Heuristically we decide to do this if the vector has a "dominant" value,
4973   // defined as splatted to more than half of the lanes.
4974   unsigned NumElts = VT.getVectorNumElements();
4975   bool isOnlyLowElement = true;
4976   bool usesOnlyOneValue = true;
4977   bool hasDominantValue = false;
4978   bool isConstant = true;
4979
4980   // Map of the number of times a particular SDValue appears in the
4981   // element list.
4982   DenseMap<SDValue, unsigned> ValueCounts;
4983   SDValue Value;
4984   for (unsigned i = 0; i < NumElts; ++i) {
4985     SDValue V = Op.getOperand(i);
4986     if (V.getOpcode() == ISD::UNDEF)
4987       continue;
4988     if (i > 0)
4989       isOnlyLowElement = false;
4990     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4991       isConstant = false;
4992
4993     ValueCounts.insert(std::make_pair(V, 0));
4994     unsigned &Count = ValueCounts[V];
4995
4996     // Is this value dominant? (takes up more than half of the lanes)
4997     if (++Count > (NumElts / 2)) {
4998       hasDominantValue = true;
4999       Value = V;
5000     }
5001   }
5002   if (ValueCounts.size() != 1)
5003     usesOnlyOneValue = false;
5004   if (!Value.getNode() && ValueCounts.size() > 0)
5005     Value = ValueCounts.begin()->first;
5006
5007   if (ValueCounts.size() == 0)
5008     return DAG.getUNDEF(VT);
5009
5010   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5011   // Keep going if we are hitting this case.
5012   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5013     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5014
5015   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5016
5017   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5018   // i32 and try again.
5019   if (hasDominantValue && EltSize <= 32) {
5020     if (!isConstant) {
5021       SDValue N;
5022
5023       // If we are VDUPing a value that comes directly from a vector, that will
5024       // cause an unnecessary move to and from a GPR, where instead we could
5025       // just use VDUPLANE. We can only do this if the lane being extracted
5026       // is at a constant index, as the VDUP from lane instructions only have
5027       // constant-index forms.
5028       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5029           isa<ConstantSDNode>(Value->getOperand(1))) {
5030         // We need to create a new undef vector to use for the VDUPLANE if the
5031         // size of the vector from which we get the value is different than the
5032         // size of the vector that we need to create. We will insert the element
5033         // such that the register coalescer will remove unnecessary copies.
5034         if (VT != Value->getOperand(0).getValueType()) {
5035           ConstantSDNode *constIndex;
5036           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5037           assert(constIndex && "The index is not a constant!");
5038           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5039                              VT.getVectorNumElements();
5040           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5041                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5042                         Value, DAG.getConstant(index, MVT::i32)),
5043                            DAG.getConstant(index, MVT::i32));
5044         } else
5045           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5046                         Value->getOperand(0), Value->getOperand(1));
5047       } else
5048         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5049
5050       if (!usesOnlyOneValue) {
5051         // The dominant value was splatted as 'N', but we now have to insert
5052         // all differing elements.
5053         for (unsigned I = 0; I < NumElts; ++I) {
5054           if (Op.getOperand(I) == Value)
5055             continue;
5056           SmallVector<SDValue, 3> Ops;
5057           Ops.push_back(N);
5058           Ops.push_back(Op.getOperand(I));
5059           Ops.push_back(DAG.getConstant(I, MVT::i32));
5060           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5061         }
5062       }
5063       return N;
5064     }
5065     if (VT.getVectorElementType().isFloatingPoint()) {
5066       SmallVector<SDValue, 8> Ops;
5067       for (unsigned i = 0; i < NumElts; ++i)
5068         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5069                                   Op.getOperand(i)));
5070       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5071       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5072       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5073       if (Val.getNode())
5074         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5075     }
5076     if (usesOnlyOneValue) {
5077       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5078       if (isConstant && Val.getNode())
5079         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5080     }
5081   }
5082
5083   // If all elements are constants and the case above didn't get hit, fall back
5084   // to the default expansion, which will generate a load from the constant
5085   // pool.
5086   if (isConstant)
5087     return SDValue();
5088
5089   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5090   if (NumElts >= 4) {
5091     SDValue shuffle = ReconstructShuffle(Op, DAG);
5092     if (shuffle != SDValue())
5093       return shuffle;
5094   }
5095
5096   // Vectors with 32- or 64-bit elements can be built by directly assigning
5097   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5098   // will be legalized.
5099   if (EltSize >= 32) {
5100     // Do the expansion with floating-point types, since that is what the VFP
5101     // registers are defined to use, and since i64 is not legal.
5102     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5103     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5104     SmallVector<SDValue, 8> Ops;
5105     for (unsigned i = 0; i < NumElts; ++i)
5106       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5107     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5108     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5109   }
5110
5111   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5112   // know the default expansion would otherwise fall back on something even
5113   // worse. For a vector with one or two non-undef values, that's
5114   // scalar_to_vector for the elements followed by a shuffle (provided the
5115   // shuffle is valid for the target) and materialization element by element
5116   // on the stack followed by a load for everything else.
5117   if (!isConstant && !usesOnlyOneValue) {
5118     SDValue Vec = DAG.getUNDEF(VT);
5119     for (unsigned i = 0 ; i < NumElts; ++i) {
5120       SDValue V = Op.getOperand(i);
5121       if (V.getOpcode() == ISD::UNDEF)
5122         continue;
5123       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5124       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5125     }
5126     return Vec;
5127   }
5128
5129   return SDValue();
5130 }
5131
5132 // Gather data to see if the operation can be modelled as a
5133 // shuffle in combination with VEXTs.
5134 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5135                                               SelectionDAG &DAG) const {
5136   SDLoc dl(Op);
5137   EVT VT = Op.getValueType();
5138   unsigned NumElts = VT.getVectorNumElements();
5139
5140   SmallVector<SDValue, 2> SourceVecs;
5141   SmallVector<unsigned, 2> MinElts;
5142   SmallVector<unsigned, 2> MaxElts;
5143
5144   for (unsigned i = 0; i < NumElts; ++i) {
5145     SDValue V = Op.getOperand(i);
5146     if (V.getOpcode() == ISD::UNDEF)
5147       continue;
5148     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5149       // A shuffle can only come from building a vector from various
5150       // elements of other vectors.
5151       return SDValue();
5152     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5153                VT.getVectorElementType()) {
5154       // This code doesn't know how to handle shuffles where the vector
5155       // element types do not match (this happens because type legalization
5156       // promotes the return type of EXTRACT_VECTOR_ELT).
5157       // FIXME: It might be appropriate to extend this code to handle
5158       // mismatched types.
5159       return SDValue();
5160     }
5161
5162     // Record this extraction against the appropriate vector if possible...
5163     SDValue SourceVec = V.getOperand(0);
5164     // If the element number isn't a constant, we can't effectively
5165     // analyze what's going on.
5166     if (!isa<ConstantSDNode>(V.getOperand(1)))
5167       return SDValue();
5168     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5169     bool FoundSource = false;
5170     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5171       if (SourceVecs[j] == SourceVec) {
5172         if (MinElts[j] > EltNo)
5173           MinElts[j] = EltNo;
5174         if (MaxElts[j] < EltNo)
5175           MaxElts[j] = EltNo;
5176         FoundSource = true;
5177         break;
5178       }
5179     }
5180
5181     // Or record a new source if not...
5182     if (!FoundSource) {
5183       SourceVecs.push_back(SourceVec);
5184       MinElts.push_back(EltNo);
5185       MaxElts.push_back(EltNo);
5186     }
5187   }
5188
5189   // Currently only do something sane when at most two source vectors
5190   // involved.
5191   if (SourceVecs.size() > 2)
5192     return SDValue();
5193
5194   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5195   int VEXTOffsets[2] = {0, 0};
5196
5197   // This loop extracts the usage patterns of the source vectors
5198   // and prepares appropriate SDValues for a shuffle if possible.
5199   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5200     if (SourceVecs[i].getValueType() == VT) {
5201       // No VEXT necessary
5202       ShuffleSrcs[i] = SourceVecs[i];
5203       VEXTOffsets[i] = 0;
5204       continue;
5205     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5206       // It probably isn't worth padding out a smaller vector just to
5207       // break it down again in a shuffle.
5208       return SDValue();
5209     }
5210
5211     // Since only 64-bit and 128-bit vectors are legal on ARM and
5212     // we've eliminated the other cases...
5213     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5214            "unexpected vector sizes in ReconstructShuffle");
5215
5216     if (MaxElts[i] - MinElts[i] >= NumElts) {
5217       // Span too large for a VEXT to cope
5218       return SDValue();
5219     }
5220
5221     if (MinElts[i] >= NumElts) {
5222       // The extraction can just take the second half
5223       VEXTOffsets[i] = NumElts;
5224       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5225                                    SourceVecs[i],
5226                                    DAG.getIntPtrConstant(NumElts));
5227     } else if (MaxElts[i] < NumElts) {
5228       // The extraction can just take the first half
5229       VEXTOffsets[i] = 0;
5230       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5231                                    SourceVecs[i],
5232                                    DAG.getIntPtrConstant(0));
5233     } else {
5234       // An actual VEXT is needed
5235       VEXTOffsets[i] = MinElts[i];
5236       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5237                                      SourceVecs[i],
5238                                      DAG.getIntPtrConstant(0));
5239       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5240                                      SourceVecs[i],
5241                                      DAG.getIntPtrConstant(NumElts));
5242       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5243                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5244     }
5245   }
5246
5247   SmallVector<int, 8> Mask;
5248
5249   for (unsigned i = 0; i < NumElts; ++i) {
5250     SDValue Entry = Op.getOperand(i);
5251     if (Entry.getOpcode() == ISD::UNDEF) {
5252       Mask.push_back(-1);
5253       continue;
5254     }
5255
5256     SDValue ExtractVec = Entry.getOperand(0);
5257     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5258                                           .getOperand(1))->getSExtValue();
5259     if (ExtractVec == SourceVecs[0]) {
5260       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5261     } else {
5262       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5263     }
5264   }
5265
5266   // Final check before we try to produce nonsense...
5267   if (isShuffleMaskLegal(Mask, VT))
5268     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5269                                 &Mask[0]);
5270
5271   return SDValue();
5272 }
5273
5274 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5275 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5276 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5277 /// are assumed to be legal.
5278 bool
5279 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5280                                       EVT VT) const {
5281   if (VT.getVectorNumElements() == 4 &&
5282       (VT.is128BitVector() || VT.is64BitVector())) {
5283     unsigned PFIndexes[4];
5284     for (unsigned i = 0; i != 4; ++i) {
5285       if (M[i] < 0)
5286         PFIndexes[i] = 8;
5287       else
5288         PFIndexes[i] = M[i];
5289     }
5290
5291     // Compute the index in the perfect shuffle table.
5292     unsigned PFTableIndex =
5293       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5294     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5295     unsigned Cost = (PFEntry >> 30);
5296
5297     if (Cost <= 4)
5298       return true;
5299   }
5300
5301   bool ReverseVEXT;
5302   unsigned Imm, WhichResult;
5303
5304   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5305   return (EltSize >= 32 ||
5306           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5307           isVREVMask(M, VT, 64) ||
5308           isVREVMask(M, VT, 32) ||
5309           isVREVMask(M, VT, 16) ||
5310           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5311           isVTBLMask(M, VT) ||
5312           isVTRNMask(M, VT, WhichResult) ||
5313           isVUZPMask(M, VT, WhichResult) ||
5314           isVZIPMask(M, VT, WhichResult) ||
5315           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5316           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5317           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5318           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5319 }
5320
5321 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5322 /// the specified operations to build the shuffle.
5323 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5324                                       SDValue RHS, SelectionDAG &DAG,
5325                                       SDLoc dl) {
5326   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5327   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5328   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5329
5330   enum {
5331     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5332     OP_VREV,
5333     OP_VDUP0,
5334     OP_VDUP1,
5335     OP_VDUP2,
5336     OP_VDUP3,
5337     OP_VEXT1,
5338     OP_VEXT2,
5339     OP_VEXT3,
5340     OP_VUZPL, // VUZP, left result
5341     OP_VUZPR, // VUZP, right result
5342     OP_VZIPL, // VZIP, left result
5343     OP_VZIPR, // VZIP, right result
5344     OP_VTRNL, // VTRN, left result
5345     OP_VTRNR  // VTRN, right result
5346   };
5347
5348   if (OpNum == OP_COPY) {
5349     if (LHSID == (1*9+2)*9+3) return LHS;
5350     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5351     return RHS;
5352   }
5353
5354   SDValue OpLHS, OpRHS;
5355   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5356   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5357   EVT VT = OpLHS.getValueType();
5358
5359   switch (OpNum) {
5360   default: llvm_unreachable("Unknown shuffle opcode!");
5361   case OP_VREV:
5362     // VREV divides the vector in half and swaps within the half.
5363     if (VT.getVectorElementType() == MVT::i32 ||
5364         VT.getVectorElementType() == MVT::f32)
5365       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5366     // vrev <4 x i16> -> VREV32
5367     if (VT.getVectorElementType() == MVT::i16)
5368       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5369     // vrev <4 x i8> -> VREV16
5370     assert(VT.getVectorElementType() == MVT::i8);
5371     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5372   case OP_VDUP0:
5373   case OP_VDUP1:
5374   case OP_VDUP2:
5375   case OP_VDUP3:
5376     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5377                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5378   case OP_VEXT1:
5379   case OP_VEXT2:
5380   case OP_VEXT3:
5381     return DAG.getNode(ARMISD::VEXT, dl, VT,
5382                        OpLHS, OpRHS,
5383                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5384   case OP_VUZPL:
5385   case OP_VUZPR:
5386     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5387                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5388   case OP_VZIPL:
5389   case OP_VZIPR:
5390     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5391                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5392   case OP_VTRNL:
5393   case OP_VTRNR:
5394     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5395                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5396   }
5397 }
5398
5399 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5400                                        ArrayRef<int> ShuffleMask,
5401                                        SelectionDAG &DAG) {
5402   // Check to see if we can use the VTBL instruction.
5403   SDValue V1 = Op.getOperand(0);
5404   SDValue V2 = Op.getOperand(1);
5405   SDLoc DL(Op);
5406
5407   SmallVector<SDValue, 8> VTBLMask;
5408   for (ArrayRef<int>::iterator
5409          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5410     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5411
5412   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5413     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5414                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5415
5416   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5417                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5418 }
5419
5420 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5421                                                       SelectionDAG &DAG) {
5422   SDLoc DL(Op);
5423   SDValue OpLHS = Op.getOperand(0);
5424   EVT VT = OpLHS.getValueType();
5425
5426   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5427          "Expect an v8i16/v16i8 type");
5428   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5429   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5430   // extract the first 8 bytes into the top double word and the last 8 bytes
5431   // into the bottom double word. The v8i16 case is similar.
5432   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5433   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5434                      DAG.getConstant(ExtractNum, MVT::i32));
5435 }
5436
5437 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5438   SDValue V1 = Op.getOperand(0);
5439   SDValue V2 = Op.getOperand(1);
5440   SDLoc dl(Op);
5441   EVT VT = Op.getValueType();
5442   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5443
5444   // Convert shuffles that are directly supported on NEON to target-specific
5445   // DAG nodes, instead of keeping them as shuffles and matching them again
5446   // during code selection.  This is more efficient and avoids the possibility
5447   // of inconsistencies between legalization and selection.
5448   // FIXME: floating-point vectors should be canonicalized to integer vectors
5449   // of the same time so that they get CSEd properly.
5450   ArrayRef<int> ShuffleMask = SVN->getMask();
5451
5452   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5453   if (EltSize <= 32) {
5454     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5455       int Lane = SVN->getSplatIndex();
5456       // If this is undef splat, generate it via "just" vdup, if possible.
5457       if (Lane == -1) Lane = 0;
5458
5459       // Test if V1 is a SCALAR_TO_VECTOR.
5460       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5461         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5462       }
5463       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5464       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5465       // reaches it).
5466       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5467           !isa<ConstantSDNode>(V1.getOperand(0))) {
5468         bool IsScalarToVector = true;
5469         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5470           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5471             IsScalarToVector = false;
5472             break;
5473           }
5474         if (IsScalarToVector)
5475           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5476       }
5477       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5478                          DAG.getConstant(Lane, MVT::i32));
5479     }
5480
5481     bool ReverseVEXT;
5482     unsigned Imm;
5483     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5484       if (ReverseVEXT)
5485         std::swap(V1, V2);
5486       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5487                          DAG.getConstant(Imm, MVT::i32));
5488     }
5489
5490     if (isVREVMask(ShuffleMask, VT, 64))
5491       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5492     if (isVREVMask(ShuffleMask, VT, 32))
5493       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5494     if (isVREVMask(ShuffleMask, VT, 16))
5495       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5496
5497     if (V2->getOpcode() == ISD::UNDEF &&
5498         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5499       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5500                          DAG.getConstant(Imm, MVT::i32));
5501     }
5502
5503     // Check for Neon shuffles that modify both input vectors in place.
5504     // If both results are used, i.e., if there are two shuffles with the same
5505     // source operands and with masks corresponding to both results of one of
5506     // these operations, DAG memoization will ensure that a single node is
5507     // used for both shuffles.
5508     unsigned WhichResult;
5509     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5510       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5511                          V1, V2).getValue(WhichResult);
5512     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5513       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5514                          V1, V2).getValue(WhichResult);
5515     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5516       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5517                          V1, V2).getValue(WhichResult);
5518
5519     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5520       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5521                          V1, V1).getValue(WhichResult);
5522     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5523       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5524                          V1, V1).getValue(WhichResult);
5525     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5526       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5527                          V1, V1).getValue(WhichResult);
5528   }
5529
5530   // If the shuffle is not directly supported and it has 4 elements, use
5531   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5532   unsigned NumElts = VT.getVectorNumElements();
5533   if (NumElts == 4) {
5534     unsigned PFIndexes[4];
5535     for (unsigned i = 0; i != 4; ++i) {
5536       if (ShuffleMask[i] < 0)
5537         PFIndexes[i] = 8;
5538       else
5539         PFIndexes[i] = ShuffleMask[i];
5540     }
5541
5542     // Compute the index in the perfect shuffle table.
5543     unsigned PFTableIndex =
5544       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5545     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5546     unsigned Cost = (PFEntry >> 30);
5547
5548     if (Cost <= 4)
5549       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5550   }
5551
5552   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5553   if (EltSize >= 32) {
5554     // Do the expansion with floating-point types, since that is what the VFP
5555     // registers are defined to use, and since i64 is not legal.
5556     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5557     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5558     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5559     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5560     SmallVector<SDValue, 8> Ops;
5561     for (unsigned i = 0; i < NumElts; ++i) {
5562       if (ShuffleMask[i] < 0)
5563         Ops.push_back(DAG.getUNDEF(EltVT));
5564       else
5565         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5566                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5567                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5568                                                   MVT::i32)));
5569     }
5570     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5571     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5572   }
5573
5574   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5575     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5576
5577   if (VT == MVT::v8i8) {
5578     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5579     if (NewOp.getNode())
5580       return NewOp;
5581   }
5582
5583   return SDValue();
5584 }
5585
5586 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5587   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5588   SDValue Lane = Op.getOperand(2);
5589   if (!isa<ConstantSDNode>(Lane))
5590     return SDValue();
5591
5592   return Op;
5593 }
5594
5595 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5596   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5597   SDValue Lane = Op.getOperand(1);
5598   if (!isa<ConstantSDNode>(Lane))
5599     return SDValue();
5600
5601   SDValue Vec = Op.getOperand(0);
5602   if (Op.getValueType() == MVT::i32 &&
5603       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5604     SDLoc dl(Op);
5605     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5606   }
5607
5608   return Op;
5609 }
5610
5611 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5612   // The only time a CONCAT_VECTORS operation can have legal types is when
5613   // two 64-bit vectors are concatenated to a 128-bit vector.
5614   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5615          "unexpected CONCAT_VECTORS");
5616   SDLoc dl(Op);
5617   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5618   SDValue Op0 = Op.getOperand(0);
5619   SDValue Op1 = Op.getOperand(1);
5620   if (Op0.getOpcode() != ISD::UNDEF)
5621     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5622                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5623                       DAG.getIntPtrConstant(0));
5624   if (Op1.getOpcode() != ISD::UNDEF)
5625     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5626                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5627                       DAG.getIntPtrConstant(1));
5628   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5629 }
5630
5631 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5632 /// element has been zero/sign-extended, depending on the isSigned parameter,
5633 /// from an integer type half its size.
5634 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5635                                    bool isSigned) {
5636   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5637   EVT VT = N->getValueType(0);
5638   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5639     SDNode *BVN = N->getOperand(0).getNode();
5640     if (BVN->getValueType(0) != MVT::v4i32 ||
5641         BVN->getOpcode() != ISD::BUILD_VECTOR)
5642       return false;
5643     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5644     unsigned HiElt = 1 - LoElt;
5645     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5646     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5647     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5648     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5649     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5650       return false;
5651     if (isSigned) {
5652       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5653           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5654         return true;
5655     } else {
5656       if (Hi0->isNullValue() && Hi1->isNullValue())
5657         return true;
5658     }
5659     return false;
5660   }
5661
5662   if (N->getOpcode() != ISD::BUILD_VECTOR)
5663     return false;
5664
5665   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5666     SDNode *Elt = N->getOperand(i).getNode();
5667     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5668       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5669       unsigned HalfSize = EltSize / 2;
5670       if (isSigned) {
5671         if (!isIntN(HalfSize, C->getSExtValue()))
5672           return false;
5673       } else {
5674         if (!isUIntN(HalfSize, C->getZExtValue()))
5675           return false;
5676       }
5677       continue;
5678     }
5679     return false;
5680   }
5681
5682   return true;
5683 }
5684
5685 /// isSignExtended - Check if a node is a vector value that is sign-extended
5686 /// or a constant BUILD_VECTOR with sign-extended elements.
5687 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5688   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5689     return true;
5690   if (isExtendedBUILD_VECTOR(N, DAG, true))
5691     return true;
5692   return false;
5693 }
5694
5695 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5696 /// or a constant BUILD_VECTOR with zero-extended elements.
5697 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5698   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5699     return true;
5700   if (isExtendedBUILD_VECTOR(N, DAG, false))
5701     return true;
5702   return false;
5703 }
5704
5705 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5706   if (OrigVT.getSizeInBits() >= 64)
5707     return OrigVT;
5708
5709   assert(OrigVT.isSimple() && "Expecting a simple value type");
5710
5711   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5712   switch (OrigSimpleTy) {
5713   default: llvm_unreachable("Unexpected Vector Type");
5714   case MVT::v2i8:
5715   case MVT::v2i16:
5716      return MVT::v2i32;
5717   case MVT::v4i8:
5718     return  MVT::v4i16;
5719   }
5720 }
5721
5722 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5723 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5724 /// We insert the required extension here to get the vector to fill a D register.
5725 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5726                                             const EVT &OrigTy,
5727                                             const EVT &ExtTy,
5728                                             unsigned ExtOpcode) {
5729   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5730   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5731   // 64-bits we need to insert a new extension so that it will be 64-bits.
5732   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5733   if (OrigTy.getSizeInBits() >= 64)
5734     return N;
5735
5736   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5737   EVT NewVT = getExtensionTo64Bits(OrigTy);
5738
5739   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5740 }
5741
5742 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5743 /// does not do any sign/zero extension. If the original vector is less
5744 /// than 64 bits, an appropriate extension will be added after the load to
5745 /// reach a total size of 64 bits. We have to add the extension separately
5746 /// because ARM does not have a sign/zero extending load for vectors.
5747 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5748   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5749
5750   // The load already has the right type.
5751   if (ExtendedTy == LD->getMemoryVT())
5752     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5753                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5754                 LD->isNonTemporal(), LD->isInvariant(),
5755                 LD->getAlignment());
5756
5757   // We need to create a zextload/sextload. We cannot just create a load
5758   // followed by a zext/zext node because LowerMUL is also run during normal
5759   // operation legalization where we can't create illegal types.
5760   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5761                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5762                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5763                         LD->isNonTemporal(), LD->getAlignment());
5764 }
5765
5766 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5767 /// extending load, or BUILD_VECTOR with extended elements, return the
5768 /// unextended value. The unextended vector should be 64 bits so that it can
5769 /// be used as an operand to a VMULL instruction. If the original vector size
5770 /// before extension is less than 64 bits we add a an extension to resize
5771 /// the vector to 64 bits.
5772 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5773   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5774     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5775                                         N->getOperand(0)->getValueType(0),
5776                                         N->getValueType(0),
5777                                         N->getOpcode());
5778
5779   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5780     return SkipLoadExtensionForVMULL(LD, DAG);
5781
5782   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5783   // have been legalized as a BITCAST from v4i32.
5784   if (N->getOpcode() == ISD::BITCAST) {
5785     SDNode *BVN = N->getOperand(0).getNode();
5786     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5787            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5788     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5789     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5790                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5791   }
5792   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5793   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5794   EVT VT = N->getValueType(0);
5795   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5796   unsigned NumElts = VT.getVectorNumElements();
5797   MVT TruncVT = MVT::getIntegerVT(EltSize);
5798   SmallVector<SDValue, 8> Ops;
5799   for (unsigned i = 0; i != NumElts; ++i) {
5800     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5801     const APInt &CInt = C->getAPIntValue();
5802     // Element types smaller than 32 bits are not legal, so use i32 elements.
5803     // The values are implicitly truncated so sext vs. zext doesn't matter.
5804     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5805   }
5806   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5807                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5808 }
5809
5810 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5811   unsigned Opcode = N->getOpcode();
5812   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5813     SDNode *N0 = N->getOperand(0).getNode();
5814     SDNode *N1 = N->getOperand(1).getNode();
5815     return N0->hasOneUse() && N1->hasOneUse() &&
5816       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5817   }
5818   return false;
5819 }
5820
5821 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5822   unsigned Opcode = N->getOpcode();
5823   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5824     SDNode *N0 = N->getOperand(0).getNode();
5825     SDNode *N1 = N->getOperand(1).getNode();
5826     return N0->hasOneUse() && N1->hasOneUse() &&
5827       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5828   }
5829   return false;
5830 }
5831
5832 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5833   // Multiplications are only custom-lowered for 128-bit vectors so that
5834   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5835   EVT VT = Op.getValueType();
5836   assert(VT.is128BitVector() && VT.isInteger() &&
5837          "unexpected type for custom-lowering ISD::MUL");
5838   SDNode *N0 = Op.getOperand(0).getNode();
5839   SDNode *N1 = Op.getOperand(1).getNode();
5840   unsigned NewOpc = 0;
5841   bool isMLA = false;
5842   bool isN0SExt = isSignExtended(N0, DAG);
5843   bool isN1SExt = isSignExtended(N1, DAG);
5844   if (isN0SExt && isN1SExt)
5845     NewOpc = ARMISD::VMULLs;
5846   else {
5847     bool isN0ZExt = isZeroExtended(N0, DAG);
5848     bool isN1ZExt = isZeroExtended(N1, DAG);
5849     if (isN0ZExt && isN1ZExt)
5850       NewOpc = ARMISD::VMULLu;
5851     else if (isN1SExt || isN1ZExt) {
5852       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5853       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5854       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5855         NewOpc = ARMISD::VMULLs;
5856         isMLA = true;
5857       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5858         NewOpc = ARMISD::VMULLu;
5859         isMLA = true;
5860       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5861         std::swap(N0, N1);
5862         NewOpc = ARMISD::VMULLu;
5863         isMLA = true;
5864       }
5865     }
5866
5867     if (!NewOpc) {
5868       if (VT == MVT::v2i64)
5869         // Fall through to expand this.  It is not legal.
5870         return SDValue();
5871       else
5872         // Other vector multiplications are legal.
5873         return Op;
5874     }
5875   }
5876
5877   // Legalize to a VMULL instruction.
5878   SDLoc DL(Op);
5879   SDValue Op0;
5880   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5881   if (!isMLA) {
5882     Op0 = SkipExtensionForVMULL(N0, DAG);
5883     assert(Op0.getValueType().is64BitVector() &&
5884            Op1.getValueType().is64BitVector() &&
5885            "unexpected types for extended operands to VMULL");
5886     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5887   }
5888
5889   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5890   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5891   //   vmull q0, d4, d6
5892   //   vmlal q0, d5, d6
5893   // is faster than
5894   //   vaddl q0, d4, d5
5895   //   vmovl q1, d6
5896   //   vmul  q0, q0, q1
5897   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5898   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5899   EVT Op1VT = Op1.getValueType();
5900   return DAG.getNode(N0->getOpcode(), DL, VT,
5901                      DAG.getNode(NewOpc, DL, VT,
5902                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5903                      DAG.getNode(NewOpc, DL, VT,
5904                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5905 }
5906
5907 static SDValue
5908 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5909   // Convert to float
5910   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5911   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5912   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5913   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5914   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5915   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5916   // Get reciprocal estimate.
5917   // float4 recip = vrecpeq_f32(yf);
5918   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5919                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5920   // Because char has a smaller range than uchar, we can actually get away
5921   // without any newton steps.  This requires that we use a weird bias
5922   // of 0xb000, however (again, this has been exhaustively tested).
5923   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5924   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5925   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5926   Y = DAG.getConstant(0xb000, MVT::i32);
5927   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5928   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5929   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5930   // Convert back to short.
5931   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5932   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5933   return X;
5934 }
5935
5936 static SDValue
5937 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5938   SDValue N2;
5939   // Convert to float.
5940   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5941   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5942   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5943   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5944   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5945   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5946
5947   // Use reciprocal estimate and one refinement step.
5948   // float4 recip = vrecpeq_f32(yf);
5949   // recip *= vrecpsq_f32(yf, recip);
5950   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5951                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5952   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5953                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5954                    N1, N2);
5955   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5956   // Because short has a smaller range than ushort, we can actually get away
5957   // with only a single newton step.  This requires that we use a weird bias
5958   // of 89, however (again, this has been exhaustively tested).
5959   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5960   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5961   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5962   N1 = DAG.getConstant(0x89, MVT::i32);
5963   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5964   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5965   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5966   // Convert back to integer and return.
5967   // return vmovn_s32(vcvt_s32_f32(result));
5968   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5969   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5970   return N0;
5971 }
5972
5973 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5974   EVT VT = Op.getValueType();
5975   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5976          "unexpected type for custom-lowering ISD::SDIV");
5977
5978   SDLoc dl(Op);
5979   SDValue N0 = Op.getOperand(0);
5980   SDValue N1 = Op.getOperand(1);
5981   SDValue N2, N3;
5982
5983   if (VT == MVT::v8i8) {
5984     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5985     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5986
5987     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5988                      DAG.getIntPtrConstant(4));
5989     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5990                      DAG.getIntPtrConstant(4));
5991     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5992                      DAG.getIntPtrConstant(0));
5993     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5994                      DAG.getIntPtrConstant(0));
5995
5996     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5997     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5998
5999     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6000     N0 = LowerCONCAT_VECTORS(N0, DAG);
6001
6002     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6003     return N0;
6004   }
6005   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6006 }
6007
6008 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6009   EVT VT = Op.getValueType();
6010   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6011          "unexpected type for custom-lowering ISD::UDIV");
6012
6013   SDLoc dl(Op);
6014   SDValue N0 = Op.getOperand(0);
6015   SDValue N1 = Op.getOperand(1);
6016   SDValue N2, N3;
6017
6018   if (VT == MVT::v8i8) {
6019     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6020     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6021
6022     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6023                      DAG.getIntPtrConstant(4));
6024     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6025                      DAG.getIntPtrConstant(4));
6026     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6027                      DAG.getIntPtrConstant(0));
6028     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6029                      DAG.getIntPtrConstant(0));
6030
6031     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6032     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6033
6034     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6035     N0 = LowerCONCAT_VECTORS(N0, DAG);
6036
6037     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6038                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6039                      N0);
6040     return N0;
6041   }
6042
6043   // v4i16 sdiv ... Convert to float.
6044   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6045   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6046   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6047   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6048   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6049   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6050
6051   // Use reciprocal estimate and two refinement steps.
6052   // float4 recip = vrecpeq_f32(yf);
6053   // recip *= vrecpsq_f32(yf, recip);
6054   // recip *= vrecpsq_f32(yf, recip);
6055   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6056                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6057   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6058                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6059                    BN1, N2);
6060   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6061   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6062                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6063                    BN1, N2);
6064   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6065   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6066   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6067   // and that it will never cause us to return an answer too large).
6068   // float4 result = as_float4(as_int4(xf*recip) + 2);
6069   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6070   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6071   N1 = DAG.getConstant(2, MVT::i32);
6072   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6073   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6074   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6075   // Convert back to integer and return.
6076   // return vmovn_u32(vcvt_s32_f32(result));
6077   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6078   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6079   return N0;
6080 }
6081
6082 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6083   EVT VT = Op.getNode()->getValueType(0);
6084   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6085
6086   unsigned Opc;
6087   bool ExtraOp = false;
6088   switch (Op.getOpcode()) {
6089   default: llvm_unreachable("Invalid code");
6090   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6091   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6092   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6093   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6094   }
6095
6096   if (!ExtraOp)
6097     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6098                        Op.getOperand(1));
6099   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6100                      Op.getOperand(1), Op.getOperand(2));
6101 }
6102
6103 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6104   assert(Subtarget->isTargetDarwin());
6105
6106   // For iOS, we want to call an alternative entry point: __sincos_stret,
6107   // return values are passed via sret.
6108   SDLoc dl(Op);
6109   SDValue Arg = Op.getOperand(0);
6110   EVT ArgVT = Arg.getValueType();
6111   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6112
6113   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6114   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6115
6116   // Pair of floats / doubles used to pass the result.
6117   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6118
6119   // Create stack object for sret.
6120   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6121   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6122   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6123   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6124
6125   ArgListTy Args;
6126   ArgListEntry Entry;
6127
6128   Entry.Node = SRet;
6129   Entry.Ty = RetTy->getPointerTo();
6130   Entry.isSExt = false;
6131   Entry.isZExt = false;
6132   Entry.isSRet = true;
6133   Args.push_back(Entry);
6134
6135   Entry.Node = Arg;
6136   Entry.Ty = ArgTy;
6137   Entry.isSExt = false;
6138   Entry.isZExt = false;
6139   Args.push_back(Entry);
6140
6141   const char *LibcallName  = (ArgVT == MVT::f64)
6142   ? "__sincos_stret" : "__sincosf_stret";
6143   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6144
6145   TargetLowering::CallLoweringInfo CLI(DAG);
6146   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6147     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6148                std::move(Args), 0)
6149     .setDiscardResult();
6150
6151   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6152
6153   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6154                                 MachinePointerInfo(), false, false, false, 0);
6155
6156   // Address of cos field.
6157   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6158                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6159   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6160                                 MachinePointerInfo(), false, false, false, 0);
6161
6162   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6163   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6164                      LoadSin.getValue(0), LoadCos.getValue(0));
6165 }
6166
6167 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6168   // Monotonic load/store is legal for all targets
6169   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6170     return Op;
6171
6172   // Acquire/Release load/store is not legal for targets without a
6173   // dmb or equivalent available.
6174   return SDValue();
6175 }
6176
6177 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6178                                     SmallVectorImpl<SDValue> &Results,
6179                                     SelectionDAG &DAG,
6180                                     const ARMSubtarget *Subtarget) {
6181   SDLoc DL(N);
6182   SDValue Cycles32, OutChain;
6183
6184   if (Subtarget->hasPerfMon()) {
6185     // Under Power Management extensions, the cycle-count is:
6186     //    mrc p15, #0, <Rt>, c9, c13, #0
6187     SDValue Ops[] = { N->getOperand(0), // Chain
6188                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6189                       DAG.getConstant(15, MVT::i32),
6190                       DAG.getConstant(0, MVT::i32),
6191                       DAG.getConstant(9, MVT::i32),
6192                       DAG.getConstant(13, MVT::i32),
6193                       DAG.getConstant(0, MVT::i32)
6194     };
6195
6196     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6197                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6198     OutChain = Cycles32.getValue(1);
6199   } else {
6200     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6201     // there are older ARM CPUs that have implementation-specific ways of
6202     // obtaining this information (FIXME!).
6203     Cycles32 = DAG.getConstant(0, MVT::i32);
6204     OutChain = DAG.getEntryNode();
6205   }
6206
6207
6208   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6209                                  Cycles32, DAG.getConstant(0, MVT::i32));
6210   Results.push_back(Cycles64);
6211   Results.push_back(OutChain);
6212 }
6213
6214 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6215   switch (Op.getOpcode()) {
6216   default: llvm_unreachable("Don't know how to custom lower this!");
6217   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6218   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6219   case ISD::GlobalAddress:
6220     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6221     default: llvm_unreachable("unknown object format");
6222     case Triple::COFF:
6223       return LowerGlobalAddressWindows(Op, DAG);
6224     case Triple::ELF:
6225       return LowerGlobalAddressELF(Op, DAG);
6226     case Triple::MachO:
6227       return LowerGlobalAddressDarwin(Op, DAG);
6228     }
6229   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6230   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6231   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6232   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6233   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6234   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6235   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6236   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6237   case ISD::SINT_TO_FP:
6238   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6239   case ISD::FP_TO_SINT:
6240   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6241   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6242   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6243   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6244   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6245   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6246   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6247   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6248                                                                Subtarget);
6249   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6250   case ISD::SHL:
6251   case ISD::SRL:
6252   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6253   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6254   case ISD::SRL_PARTS:
6255   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6256   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6257   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6258   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6259   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6260   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6261   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6262   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6263   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6264   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6265   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6266   case ISD::MUL:           return LowerMUL(Op, DAG);
6267   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6268   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6269   case ISD::ADDC:
6270   case ISD::ADDE:
6271   case ISD::SUBC:
6272   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6273   case ISD::SADDO:
6274   case ISD::UADDO:
6275   case ISD::SSUBO:
6276   case ISD::USUBO:
6277     return LowerXALUO(Op, DAG);
6278   case ISD::ATOMIC_LOAD:
6279   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6280   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6281   case ISD::SDIVREM:
6282   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6283   case ISD::DYNAMIC_STACKALLOC:
6284     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6285       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6286     llvm_unreachable("Don't know how to custom lower this!");
6287   }
6288 }
6289
6290 /// ReplaceNodeResults - Replace the results of node with an illegal result
6291 /// type with new values built out of custom code.
6292 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6293                                            SmallVectorImpl<SDValue>&Results,
6294                                            SelectionDAG &DAG) const {
6295   SDValue Res;
6296   switch (N->getOpcode()) {
6297   default:
6298     llvm_unreachable("Don't know how to custom expand this!");
6299   case ISD::BITCAST:
6300     Res = ExpandBITCAST(N, DAG);
6301     break;
6302   case ISD::SRL:
6303   case ISD::SRA:
6304     Res = Expand64BitShift(N, DAG, Subtarget);
6305     break;
6306   case ISD::READCYCLECOUNTER:
6307     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6308     return;
6309   }
6310   if (Res.getNode())
6311     Results.push_back(Res);
6312 }
6313
6314 //===----------------------------------------------------------------------===//
6315 //                           ARM Scheduler Hooks
6316 //===----------------------------------------------------------------------===//
6317
6318 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6319 /// registers the function context.
6320 void ARMTargetLowering::
6321 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6322                        MachineBasicBlock *DispatchBB, int FI) const {
6323   const TargetInstrInfo *TII =
6324       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6325   DebugLoc dl = MI->getDebugLoc();
6326   MachineFunction *MF = MBB->getParent();
6327   MachineRegisterInfo *MRI = &MF->getRegInfo();
6328   MachineConstantPool *MCP = MF->getConstantPool();
6329   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6330   const Function *F = MF->getFunction();
6331
6332   bool isThumb = Subtarget->isThumb();
6333   bool isThumb2 = Subtarget->isThumb2();
6334
6335   unsigned PCLabelId = AFI->createPICLabelUId();
6336   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6337   ARMConstantPoolValue *CPV =
6338     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6339   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6340
6341   const TargetRegisterClass *TRC = isThumb ?
6342     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6343     (const TargetRegisterClass*)&ARM::GPRRegClass;
6344
6345   // Grab constant pool and fixed stack memory operands.
6346   MachineMemOperand *CPMMO =
6347     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6348                              MachineMemOperand::MOLoad, 4, 4);
6349
6350   MachineMemOperand *FIMMOSt =
6351     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6352                              MachineMemOperand::MOStore, 4, 4);
6353
6354   // Load the address of the dispatch MBB into the jump buffer.
6355   if (isThumb2) {
6356     // Incoming value: jbuf
6357     //   ldr.n  r5, LCPI1_1
6358     //   orr    r5, r5, #1
6359     //   add    r5, pc
6360     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6361     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6362     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6363                    .addConstantPoolIndex(CPI)
6364                    .addMemOperand(CPMMO));
6365     // Set the low bit because of thumb mode.
6366     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6367     AddDefaultCC(
6368       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6369                      .addReg(NewVReg1, RegState::Kill)
6370                      .addImm(0x01)));
6371     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6372     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6373       .addReg(NewVReg2, RegState::Kill)
6374       .addImm(PCLabelId);
6375     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6376                    .addReg(NewVReg3, RegState::Kill)
6377                    .addFrameIndex(FI)
6378                    .addImm(36)  // &jbuf[1] :: pc
6379                    .addMemOperand(FIMMOSt));
6380   } else if (isThumb) {
6381     // Incoming value: jbuf
6382     //   ldr.n  r1, LCPI1_4
6383     //   add    r1, pc
6384     //   mov    r2, #1
6385     //   orrs   r1, r2
6386     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6387     //   str    r1, [r2]
6388     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6389     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6390                    .addConstantPoolIndex(CPI)
6391                    .addMemOperand(CPMMO));
6392     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6393     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6394       .addReg(NewVReg1, RegState::Kill)
6395       .addImm(PCLabelId);
6396     // Set the low bit because of thumb mode.
6397     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6398     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6399                    .addReg(ARM::CPSR, RegState::Define)
6400                    .addImm(1));
6401     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6402     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6403                    .addReg(ARM::CPSR, RegState::Define)
6404                    .addReg(NewVReg2, RegState::Kill)
6405                    .addReg(NewVReg3, RegState::Kill));
6406     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6407     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6408                    .addFrameIndex(FI)
6409                    .addImm(36)); // &jbuf[1] :: pc
6410     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6411                    .addReg(NewVReg4, RegState::Kill)
6412                    .addReg(NewVReg5, RegState::Kill)
6413                    .addImm(0)
6414                    .addMemOperand(FIMMOSt));
6415   } else {
6416     // Incoming value: jbuf
6417     //   ldr  r1, LCPI1_1
6418     //   add  r1, pc, r1
6419     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6420     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6421     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6422                    .addConstantPoolIndex(CPI)
6423                    .addImm(0)
6424                    .addMemOperand(CPMMO));
6425     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6426     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6427                    .addReg(NewVReg1, RegState::Kill)
6428                    .addImm(PCLabelId));
6429     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6430                    .addReg(NewVReg2, RegState::Kill)
6431                    .addFrameIndex(FI)
6432                    .addImm(36)  // &jbuf[1] :: pc
6433                    .addMemOperand(FIMMOSt));
6434   }
6435 }
6436
6437 MachineBasicBlock *ARMTargetLowering::
6438 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6439   const TargetInstrInfo *TII =
6440       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6441   DebugLoc dl = MI->getDebugLoc();
6442   MachineFunction *MF = MBB->getParent();
6443   MachineRegisterInfo *MRI = &MF->getRegInfo();
6444   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6445   MachineFrameInfo *MFI = MF->getFrameInfo();
6446   int FI = MFI->getFunctionContextIndex();
6447
6448   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6449     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6450     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6451
6452   // Get a mapping of the call site numbers to all of the landing pads they're
6453   // associated with.
6454   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6455   unsigned MaxCSNum = 0;
6456   MachineModuleInfo &MMI = MF->getMMI();
6457   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6458        ++BB) {
6459     if (!BB->isLandingPad()) continue;
6460
6461     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6462     // pad.
6463     for (MachineBasicBlock::iterator
6464            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6465       if (!II->isEHLabel()) continue;
6466
6467       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6468       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6469
6470       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6471       for (SmallVectorImpl<unsigned>::iterator
6472              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6473            CSI != CSE; ++CSI) {
6474         CallSiteNumToLPad[*CSI].push_back(BB);
6475         MaxCSNum = std::max(MaxCSNum, *CSI);
6476       }
6477       break;
6478     }
6479   }
6480
6481   // Get an ordered list of the machine basic blocks for the jump table.
6482   std::vector<MachineBasicBlock*> LPadList;
6483   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6484   LPadList.reserve(CallSiteNumToLPad.size());
6485   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6486     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6487     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6488            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6489       LPadList.push_back(*II);
6490       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6491     }
6492   }
6493
6494   assert(!LPadList.empty() &&
6495          "No landing pad destinations for the dispatch jump table!");
6496
6497   // Create the jump table and associated information.
6498   MachineJumpTableInfo *JTI =
6499     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6500   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6501   unsigned UId = AFI->createJumpTableUId();
6502   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6503
6504   // Create the MBBs for the dispatch code.
6505
6506   // Shove the dispatch's address into the return slot in the function context.
6507   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6508   DispatchBB->setIsLandingPad();
6509
6510   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6511   unsigned trap_opcode;
6512   if (Subtarget->isThumb())
6513     trap_opcode = ARM::tTRAP;
6514   else
6515     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6516
6517   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6518   DispatchBB->addSuccessor(TrapBB);
6519
6520   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6521   DispatchBB->addSuccessor(DispContBB);
6522
6523   // Insert and MBBs.
6524   MF->insert(MF->end(), DispatchBB);
6525   MF->insert(MF->end(), DispContBB);
6526   MF->insert(MF->end(), TrapBB);
6527
6528   // Insert code into the entry block that creates and registers the function
6529   // context.
6530   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6531
6532   MachineMemOperand *FIMMOLd =
6533     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6534                              MachineMemOperand::MOLoad |
6535                              MachineMemOperand::MOVolatile, 4, 4);
6536
6537   MachineInstrBuilder MIB;
6538   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6539
6540   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6541   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6542
6543   // Add a register mask with no preserved registers.  This results in all
6544   // registers being marked as clobbered.
6545   MIB.addRegMask(RI.getNoPreservedMask());
6546
6547   unsigned NumLPads = LPadList.size();
6548   if (Subtarget->isThumb2()) {
6549     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6551                    .addFrameIndex(FI)
6552                    .addImm(4)
6553                    .addMemOperand(FIMMOLd));
6554
6555     if (NumLPads < 256) {
6556       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6557                      .addReg(NewVReg1)
6558                      .addImm(LPadList.size()));
6559     } else {
6560       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6561       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6562                      .addImm(NumLPads & 0xFFFF));
6563
6564       unsigned VReg2 = VReg1;
6565       if ((NumLPads & 0xFFFF0000) != 0) {
6566         VReg2 = MRI->createVirtualRegister(TRC);
6567         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6568                        .addReg(VReg1)
6569                        .addImm(NumLPads >> 16));
6570       }
6571
6572       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6573                      .addReg(NewVReg1)
6574                      .addReg(VReg2));
6575     }
6576
6577     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6578       .addMBB(TrapBB)
6579       .addImm(ARMCC::HI)
6580       .addReg(ARM::CPSR);
6581
6582     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6583     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6584                    .addJumpTableIndex(MJTI)
6585                    .addImm(UId));
6586
6587     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6588     AddDefaultCC(
6589       AddDefaultPred(
6590         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6591         .addReg(NewVReg3, RegState::Kill)
6592         .addReg(NewVReg1)
6593         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6594
6595     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6596       .addReg(NewVReg4, RegState::Kill)
6597       .addReg(NewVReg1)
6598       .addJumpTableIndex(MJTI)
6599       .addImm(UId);
6600   } else if (Subtarget->isThumb()) {
6601     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6602     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6603                    .addFrameIndex(FI)
6604                    .addImm(1)
6605                    .addMemOperand(FIMMOLd));
6606
6607     if (NumLPads < 256) {
6608       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6609                      .addReg(NewVReg1)
6610                      .addImm(NumLPads));
6611     } else {
6612       MachineConstantPool *ConstantPool = MF->getConstantPool();
6613       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6614       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6615
6616       // MachineConstantPool wants an explicit alignment.
6617       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6618       if (Align == 0)
6619         Align = getDataLayout()->getTypeAllocSize(C->getType());
6620       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6621
6622       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6623       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6624                      .addReg(VReg1, RegState::Define)
6625                      .addConstantPoolIndex(Idx));
6626       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6627                      .addReg(NewVReg1)
6628                      .addReg(VReg1));
6629     }
6630
6631     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6632       .addMBB(TrapBB)
6633       .addImm(ARMCC::HI)
6634       .addReg(ARM::CPSR);
6635
6636     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6637     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6638                    .addReg(ARM::CPSR, RegState::Define)
6639                    .addReg(NewVReg1)
6640                    .addImm(2));
6641
6642     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6643     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6644                    .addJumpTableIndex(MJTI)
6645                    .addImm(UId));
6646
6647     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6648     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6649                    .addReg(ARM::CPSR, RegState::Define)
6650                    .addReg(NewVReg2, RegState::Kill)
6651                    .addReg(NewVReg3));
6652
6653     MachineMemOperand *JTMMOLd =
6654       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6655                                MachineMemOperand::MOLoad, 4, 4);
6656
6657     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6658     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6659                    .addReg(NewVReg4, RegState::Kill)
6660                    .addImm(0)
6661                    .addMemOperand(JTMMOLd));
6662
6663     unsigned NewVReg6 = NewVReg5;
6664     if (RelocM == Reloc::PIC_) {
6665       NewVReg6 = MRI->createVirtualRegister(TRC);
6666       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6667                      .addReg(ARM::CPSR, RegState::Define)
6668                      .addReg(NewVReg5, RegState::Kill)
6669                      .addReg(NewVReg3));
6670     }
6671
6672     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6673       .addReg(NewVReg6, RegState::Kill)
6674       .addJumpTableIndex(MJTI)
6675       .addImm(UId);
6676   } else {
6677     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6678     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6679                    .addFrameIndex(FI)
6680                    .addImm(4)
6681                    .addMemOperand(FIMMOLd));
6682
6683     if (NumLPads < 256) {
6684       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6685                      .addReg(NewVReg1)
6686                      .addImm(NumLPads));
6687     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6688       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6689       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6690                      .addImm(NumLPads & 0xFFFF));
6691
6692       unsigned VReg2 = VReg1;
6693       if ((NumLPads & 0xFFFF0000) != 0) {
6694         VReg2 = MRI->createVirtualRegister(TRC);
6695         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6696                        .addReg(VReg1)
6697                        .addImm(NumLPads >> 16));
6698       }
6699
6700       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6701                      .addReg(NewVReg1)
6702                      .addReg(VReg2));
6703     } else {
6704       MachineConstantPool *ConstantPool = MF->getConstantPool();
6705       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6706       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6707
6708       // MachineConstantPool wants an explicit alignment.
6709       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6710       if (Align == 0)
6711         Align = getDataLayout()->getTypeAllocSize(C->getType());
6712       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6713
6714       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6715       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6716                      .addReg(VReg1, RegState::Define)
6717                      .addConstantPoolIndex(Idx)
6718                      .addImm(0));
6719       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6720                      .addReg(NewVReg1)
6721                      .addReg(VReg1, RegState::Kill));
6722     }
6723
6724     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6725       .addMBB(TrapBB)
6726       .addImm(ARMCC::HI)
6727       .addReg(ARM::CPSR);
6728
6729     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6730     AddDefaultCC(
6731       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6732                      .addReg(NewVReg1)
6733                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6734     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6735     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6736                    .addJumpTableIndex(MJTI)
6737                    .addImm(UId));
6738
6739     MachineMemOperand *JTMMOLd =
6740       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6741                                MachineMemOperand::MOLoad, 4, 4);
6742     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6743     AddDefaultPred(
6744       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6745       .addReg(NewVReg3, RegState::Kill)
6746       .addReg(NewVReg4)
6747       .addImm(0)
6748       .addMemOperand(JTMMOLd));
6749
6750     if (RelocM == Reloc::PIC_) {
6751       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6752         .addReg(NewVReg5, RegState::Kill)
6753         .addReg(NewVReg4)
6754         .addJumpTableIndex(MJTI)
6755         .addImm(UId);
6756     } else {
6757       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6758         .addReg(NewVReg5, RegState::Kill)
6759         .addJumpTableIndex(MJTI)
6760         .addImm(UId);
6761     }
6762   }
6763
6764   // Add the jump table entries as successors to the MBB.
6765   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6766   for (std::vector<MachineBasicBlock*>::iterator
6767          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6768     MachineBasicBlock *CurMBB = *I;
6769     if (SeenMBBs.insert(CurMBB))
6770       DispContBB->addSuccessor(CurMBB);
6771   }
6772
6773   // N.B. the order the invoke BBs are processed in doesn't matter here.
6774   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6775   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6776   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6777          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6778     MachineBasicBlock *BB = *I;
6779
6780     // Remove the landing pad successor from the invoke block and replace it
6781     // with the new dispatch block.
6782     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6783                                                   BB->succ_end());
6784     while (!Successors.empty()) {
6785       MachineBasicBlock *SMBB = Successors.pop_back_val();
6786       if (SMBB->isLandingPad()) {
6787         BB->removeSuccessor(SMBB);
6788         MBBLPads.push_back(SMBB);
6789       }
6790     }
6791
6792     BB->addSuccessor(DispatchBB);
6793
6794     // Find the invoke call and mark all of the callee-saved registers as
6795     // 'implicit defined' so that they're spilled. This prevents code from
6796     // moving instructions to before the EH block, where they will never be
6797     // executed.
6798     for (MachineBasicBlock::reverse_iterator
6799            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6800       if (!II->isCall()) continue;
6801
6802       DenseMap<unsigned, bool> DefRegs;
6803       for (MachineInstr::mop_iterator
6804              OI = II->operands_begin(), OE = II->operands_end();
6805            OI != OE; ++OI) {
6806         if (!OI->isReg()) continue;
6807         DefRegs[OI->getReg()] = true;
6808       }
6809
6810       MachineInstrBuilder MIB(*MF, &*II);
6811
6812       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6813         unsigned Reg = SavedRegs[i];
6814         if (Subtarget->isThumb2() &&
6815             !ARM::tGPRRegClass.contains(Reg) &&
6816             !ARM::hGPRRegClass.contains(Reg))
6817           continue;
6818         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6819           continue;
6820         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6821           continue;
6822         if (!DefRegs[Reg])
6823           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6824       }
6825
6826       break;
6827     }
6828   }
6829
6830   // Mark all former landing pads as non-landing pads. The dispatch is the only
6831   // landing pad now.
6832   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6833          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6834     (*I)->setIsLandingPad(false);
6835
6836   // The instruction is gone now.
6837   MI->eraseFromParent();
6838
6839   return MBB;
6840 }
6841
6842 static
6843 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6844   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6845        E = MBB->succ_end(); I != E; ++I)
6846     if (*I != Succ)
6847       return *I;
6848   llvm_unreachable("Expecting a BB with two successors!");
6849 }
6850
6851 /// Return the load opcode for a given load size. If load size >= 8,
6852 /// neon opcode will be returned.
6853 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6854   if (LdSize >= 8)
6855     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6856                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6857   if (IsThumb1)
6858     return LdSize == 4 ? ARM::tLDRi
6859                        : LdSize == 2 ? ARM::tLDRHi
6860                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6861   if (IsThumb2)
6862     return LdSize == 4 ? ARM::t2LDR_POST
6863                        : LdSize == 2 ? ARM::t2LDRH_POST
6864                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6865   return LdSize == 4 ? ARM::LDR_POST_IMM
6866                      : LdSize == 2 ? ARM::LDRH_POST
6867                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6868 }
6869
6870 /// Return the store opcode for a given store size. If store size >= 8,
6871 /// neon opcode will be returned.
6872 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6873   if (StSize >= 8)
6874     return StSize == 16 ? ARM::VST1q32wb_fixed
6875                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6876   if (IsThumb1)
6877     return StSize == 4 ? ARM::tSTRi
6878                        : StSize == 2 ? ARM::tSTRHi
6879                                      : StSize == 1 ? ARM::tSTRBi : 0;
6880   if (IsThumb2)
6881     return StSize == 4 ? ARM::t2STR_POST
6882                        : StSize == 2 ? ARM::t2STRH_POST
6883                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6884   return StSize == 4 ? ARM::STR_POST_IMM
6885                      : StSize == 2 ? ARM::STRH_POST
6886                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6887 }
6888
6889 /// Emit a post-increment load operation with given size. The instructions
6890 /// will be added to BB at Pos.
6891 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6892                        const TargetInstrInfo *TII, DebugLoc dl,
6893                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6894                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6895   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6896   assert(LdOpc != 0 && "Should have a load opcode");
6897   if (LdSize >= 8) {
6898     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6899                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6900                        .addImm(0));
6901   } else if (IsThumb1) {
6902     // load + update AddrIn
6903     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6904                        .addReg(AddrIn).addImm(0));
6905     MachineInstrBuilder MIB =
6906         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6907     MIB = AddDefaultT1CC(MIB);
6908     MIB.addReg(AddrIn).addImm(LdSize);
6909     AddDefaultPred(MIB);
6910   } else if (IsThumb2) {
6911     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6912                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6913                        .addImm(LdSize));
6914   } else { // arm
6915     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6916                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6917                        .addReg(0).addImm(LdSize));
6918   }
6919 }
6920
6921 /// Emit a post-increment store operation with given size. The instructions
6922 /// will be added to BB at Pos.
6923 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6924                        const TargetInstrInfo *TII, DebugLoc dl,
6925                        unsigned StSize, unsigned Data, unsigned AddrIn,
6926                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6927   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6928   assert(StOpc != 0 && "Should have a store opcode");
6929   if (StSize >= 8) {
6930     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6931                        .addReg(AddrIn).addImm(0).addReg(Data));
6932   } else if (IsThumb1) {
6933     // store + update AddrIn
6934     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6935                        .addReg(AddrIn).addImm(0));
6936     MachineInstrBuilder MIB =
6937         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6938     MIB = AddDefaultT1CC(MIB);
6939     MIB.addReg(AddrIn).addImm(StSize);
6940     AddDefaultPred(MIB);
6941   } else if (IsThumb2) {
6942     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6943                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6944   } else { // arm
6945     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6946                        .addReg(Data).addReg(AddrIn).addReg(0)
6947                        .addImm(StSize));
6948   }
6949 }
6950
6951 MachineBasicBlock *
6952 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6953                                    MachineBasicBlock *BB) const {
6954   // This pseudo instruction has 3 operands: dst, src, size
6955   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6956   // Otherwise, we will generate unrolled scalar copies.
6957   const TargetInstrInfo *TII =
6958       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6959   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6960   MachineFunction::iterator It = BB;
6961   ++It;
6962
6963   unsigned dest = MI->getOperand(0).getReg();
6964   unsigned src = MI->getOperand(1).getReg();
6965   unsigned SizeVal = MI->getOperand(2).getImm();
6966   unsigned Align = MI->getOperand(3).getImm();
6967   DebugLoc dl = MI->getDebugLoc();
6968
6969   MachineFunction *MF = BB->getParent();
6970   MachineRegisterInfo &MRI = MF->getRegInfo();
6971   unsigned UnitSize = 0;
6972   const TargetRegisterClass *TRC = nullptr;
6973   const TargetRegisterClass *VecTRC = nullptr;
6974
6975   bool IsThumb1 = Subtarget->isThumb1Only();
6976   bool IsThumb2 = Subtarget->isThumb2();
6977
6978   if (Align & 1) {
6979     UnitSize = 1;
6980   } else if (Align & 2) {
6981     UnitSize = 2;
6982   } else {
6983     // Check whether we can use NEON instructions.
6984     if (!MF->getFunction()->getAttributes().
6985           hasAttribute(AttributeSet::FunctionIndex,
6986                        Attribute::NoImplicitFloat) &&
6987         Subtarget->hasNEON()) {
6988       if ((Align % 16 == 0) && SizeVal >= 16)
6989         UnitSize = 16;
6990       else if ((Align % 8 == 0) && SizeVal >= 8)
6991         UnitSize = 8;
6992     }
6993     // Can't use NEON instructions.
6994     if (UnitSize == 0)
6995       UnitSize = 4;
6996   }
6997
6998   // Select the correct opcode and register class for unit size load/store
6999   bool IsNeon = UnitSize >= 8;
7000   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7001                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7002   if (IsNeon)
7003     VecTRC = UnitSize == 16
7004                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7005                  : UnitSize == 8
7006                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7007                        : nullptr;
7008
7009   unsigned BytesLeft = SizeVal % UnitSize;
7010   unsigned LoopSize = SizeVal - BytesLeft;
7011
7012   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7013     // Use LDR and STR to copy.
7014     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7015     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7016     unsigned srcIn = src;
7017     unsigned destIn = dest;
7018     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7019       unsigned srcOut = MRI.createVirtualRegister(TRC);
7020       unsigned destOut = MRI.createVirtualRegister(TRC);
7021       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7022       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7023                  IsThumb1, IsThumb2);
7024       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7025                  IsThumb1, IsThumb2);
7026       srcIn = srcOut;
7027       destIn = destOut;
7028     }
7029
7030     // Handle the leftover bytes with LDRB and STRB.
7031     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7032     // [destOut] = STRB_POST(scratch, destIn, 1)
7033     for (unsigned i = 0; i < BytesLeft; i++) {
7034       unsigned srcOut = MRI.createVirtualRegister(TRC);
7035       unsigned destOut = MRI.createVirtualRegister(TRC);
7036       unsigned scratch = MRI.createVirtualRegister(TRC);
7037       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7038                  IsThumb1, IsThumb2);
7039       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7040                  IsThumb1, IsThumb2);
7041       srcIn = srcOut;
7042       destIn = destOut;
7043     }
7044     MI->eraseFromParent();   // The instruction is gone now.
7045     return BB;
7046   }
7047
7048   // Expand the pseudo op to a loop.
7049   // thisMBB:
7050   //   ...
7051   //   movw varEnd, # --> with thumb2
7052   //   movt varEnd, #
7053   //   ldrcp varEnd, idx --> without thumb2
7054   //   fallthrough --> loopMBB
7055   // loopMBB:
7056   //   PHI varPhi, varEnd, varLoop
7057   //   PHI srcPhi, src, srcLoop
7058   //   PHI destPhi, dst, destLoop
7059   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7060   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7061   //   subs varLoop, varPhi, #UnitSize
7062   //   bne loopMBB
7063   //   fallthrough --> exitMBB
7064   // exitMBB:
7065   //   epilogue to handle left-over bytes
7066   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7067   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7068   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7069   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7070   MF->insert(It, loopMBB);
7071   MF->insert(It, exitMBB);
7072
7073   // Transfer the remainder of BB and its successor edges to exitMBB.
7074   exitMBB->splice(exitMBB->begin(), BB,
7075                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7076   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7077
7078   // Load an immediate to varEnd.
7079   unsigned varEnd = MRI.createVirtualRegister(TRC);
7080   if (IsThumb2) {
7081     unsigned Vtmp = varEnd;
7082     if ((LoopSize & 0xFFFF0000) != 0)
7083       Vtmp = MRI.createVirtualRegister(TRC);
7084     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7085                        .addImm(LoopSize & 0xFFFF));
7086
7087     if ((LoopSize & 0xFFFF0000) != 0)
7088       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7089                          .addReg(Vtmp).addImm(LoopSize >> 16));
7090   } else {
7091     MachineConstantPool *ConstantPool = MF->getConstantPool();
7092     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7093     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7094
7095     // MachineConstantPool wants an explicit alignment.
7096     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7097     if (Align == 0)
7098       Align = getDataLayout()->getTypeAllocSize(C->getType());
7099     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7100
7101     if (IsThumb1)
7102       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7103           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7104     else
7105       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7106           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7107   }
7108   BB->addSuccessor(loopMBB);
7109
7110   // Generate the loop body:
7111   //   varPhi = PHI(varLoop, varEnd)
7112   //   srcPhi = PHI(srcLoop, src)
7113   //   destPhi = PHI(destLoop, dst)
7114   MachineBasicBlock *entryBB = BB;
7115   BB = loopMBB;
7116   unsigned varLoop = MRI.createVirtualRegister(TRC);
7117   unsigned varPhi = MRI.createVirtualRegister(TRC);
7118   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7119   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7120   unsigned destLoop = MRI.createVirtualRegister(TRC);
7121   unsigned destPhi = MRI.createVirtualRegister(TRC);
7122
7123   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7124     .addReg(varLoop).addMBB(loopMBB)
7125     .addReg(varEnd).addMBB(entryBB);
7126   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7127     .addReg(srcLoop).addMBB(loopMBB)
7128     .addReg(src).addMBB(entryBB);
7129   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7130     .addReg(destLoop).addMBB(loopMBB)
7131     .addReg(dest).addMBB(entryBB);
7132
7133   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7134   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7135   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7136   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7137              IsThumb1, IsThumb2);
7138   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7139              IsThumb1, IsThumb2);
7140
7141   // Decrement loop variable by UnitSize.
7142   if (IsThumb1) {
7143     MachineInstrBuilder MIB =
7144         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7145     MIB = AddDefaultT1CC(MIB);
7146     MIB.addReg(varPhi).addImm(UnitSize);
7147     AddDefaultPred(MIB);
7148   } else {
7149     MachineInstrBuilder MIB =
7150         BuildMI(*BB, BB->end(), dl,
7151                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7152     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7153     MIB->getOperand(5).setReg(ARM::CPSR);
7154     MIB->getOperand(5).setIsDef(true);
7155   }
7156   BuildMI(*BB, BB->end(), dl,
7157           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7158       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7159
7160   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7161   BB->addSuccessor(loopMBB);
7162   BB->addSuccessor(exitMBB);
7163
7164   // Add epilogue to handle BytesLeft.
7165   BB = exitMBB;
7166   MachineInstr *StartOfExit = exitMBB->begin();
7167
7168   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7169   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7170   unsigned srcIn = srcLoop;
7171   unsigned destIn = destLoop;
7172   for (unsigned i = 0; i < BytesLeft; i++) {
7173     unsigned srcOut = MRI.createVirtualRegister(TRC);
7174     unsigned destOut = MRI.createVirtualRegister(TRC);
7175     unsigned scratch = MRI.createVirtualRegister(TRC);
7176     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7177                IsThumb1, IsThumb2);
7178     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7179                IsThumb1, IsThumb2);
7180     srcIn = srcOut;
7181     destIn = destOut;
7182   }
7183
7184   MI->eraseFromParent();   // The instruction is gone now.
7185   return BB;
7186 }
7187
7188 MachineBasicBlock *
7189 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7190                                        MachineBasicBlock *MBB) const {
7191   const TargetMachine &TM = getTargetMachine();
7192   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7193   DebugLoc DL = MI->getDebugLoc();
7194
7195   assert(Subtarget->isTargetWindows() &&
7196          "__chkstk is only supported on Windows");
7197   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7198
7199   // __chkstk takes the number of words to allocate on the stack in R4, and
7200   // returns the stack adjustment in number of bytes in R4.  This will not
7201   // clober any other registers (other than the obvious lr).
7202   //
7203   // Although, technically, IP should be considered a register which may be
7204   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7205   // thumb-2 environment, so there is no interworking required.  As a result, we
7206   // do not expect a veneer to be emitted by the linker, clobbering IP.
7207   //
7208   // Each module receives its own copy of __chkstk, so no import thunk is
7209   // required, again, ensuring that IP is not clobbered.
7210   //
7211   // Finally, although some linkers may theoretically provide a trampoline for
7212   // out of range calls (which is quite common due to a 32M range limitation of
7213   // branches for Thumb), we can generate the long-call version via
7214   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7215   // IP.
7216
7217   switch (TM.getCodeModel()) {
7218   case CodeModel::Small:
7219   case CodeModel::Medium:
7220   case CodeModel::Default:
7221   case CodeModel::Kernel:
7222     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7223       .addImm((unsigned)ARMCC::AL).addReg(0)
7224       .addExternalSymbol("__chkstk")
7225       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7226       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7227       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7228     break;
7229   case CodeModel::Large:
7230   case CodeModel::JITDefault: {
7231     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7232     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7233
7234     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7235       .addExternalSymbol("__chkstk");
7236     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7237       .addImm((unsigned)ARMCC::AL).addReg(0)
7238       .addReg(Reg, RegState::Kill)
7239       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7240       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7241       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7242     break;
7243   }
7244   }
7245
7246   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7247                                       ARM::SP)
7248                               .addReg(ARM::SP).addReg(ARM::R4)));
7249
7250   MI->eraseFromParent();
7251   return MBB;
7252 }
7253
7254 MachineBasicBlock *
7255 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7256                                                MachineBasicBlock *BB) const {
7257   const TargetInstrInfo *TII =
7258       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7259   DebugLoc dl = MI->getDebugLoc();
7260   bool isThumb2 = Subtarget->isThumb2();
7261   switch (MI->getOpcode()) {
7262   default: {
7263     MI->dump();
7264     llvm_unreachable("Unexpected instr type to insert");
7265   }
7266   // The Thumb2 pre-indexed stores have the same MI operands, they just
7267   // define them differently in the .td files from the isel patterns, so
7268   // they need pseudos.
7269   case ARM::t2STR_preidx:
7270     MI->setDesc(TII->get(ARM::t2STR_PRE));
7271     return BB;
7272   case ARM::t2STRB_preidx:
7273     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7274     return BB;
7275   case ARM::t2STRH_preidx:
7276     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7277     return BB;
7278
7279   case ARM::STRi_preidx:
7280   case ARM::STRBi_preidx: {
7281     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7282       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7283     // Decode the offset.
7284     unsigned Offset = MI->getOperand(4).getImm();
7285     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7286     Offset = ARM_AM::getAM2Offset(Offset);
7287     if (isSub)
7288       Offset = -Offset;
7289
7290     MachineMemOperand *MMO = *MI->memoperands_begin();
7291     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7292       .addOperand(MI->getOperand(0))  // Rn_wb
7293       .addOperand(MI->getOperand(1))  // Rt
7294       .addOperand(MI->getOperand(2))  // Rn
7295       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7296       .addOperand(MI->getOperand(5))  // pred
7297       .addOperand(MI->getOperand(6))
7298       .addMemOperand(MMO);
7299     MI->eraseFromParent();
7300     return BB;
7301   }
7302   case ARM::STRr_preidx:
7303   case ARM::STRBr_preidx:
7304   case ARM::STRH_preidx: {
7305     unsigned NewOpc;
7306     switch (MI->getOpcode()) {
7307     default: llvm_unreachable("unexpected opcode!");
7308     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7309     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7310     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7311     }
7312     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7313     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7314       MIB.addOperand(MI->getOperand(i));
7315     MI->eraseFromParent();
7316     return BB;
7317   }
7318
7319   case ARM::tMOVCCr_pseudo: {
7320     // To "insert" a SELECT_CC instruction, we actually have to insert the
7321     // diamond control-flow pattern.  The incoming instruction knows the
7322     // destination vreg to set, the condition code register to branch on, the
7323     // true/false values to select between, and a branch opcode to use.
7324     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7325     MachineFunction::iterator It = BB;
7326     ++It;
7327
7328     //  thisMBB:
7329     //  ...
7330     //   TrueVal = ...
7331     //   cmpTY ccX, r1, r2
7332     //   bCC copy1MBB
7333     //   fallthrough --> copy0MBB
7334     MachineBasicBlock *thisMBB  = BB;
7335     MachineFunction *F = BB->getParent();
7336     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7337     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7338     F->insert(It, copy0MBB);
7339     F->insert(It, sinkMBB);
7340
7341     // Transfer the remainder of BB and its successor edges to sinkMBB.
7342     sinkMBB->splice(sinkMBB->begin(), BB,
7343                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7344     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7345
7346     BB->addSuccessor(copy0MBB);
7347     BB->addSuccessor(sinkMBB);
7348
7349     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7350       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7351
7352     //  copy0MBB:
7353     //   %FalseValue = ...
7354     //   # fallthrough to sinkMBB
7355     BB = copy0MBB;
7356
7357     // Update machine-CFG edges
7358     BB->addSuccessor(sinkMBB);
7359
7360     //  sinkMBB:
7361     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7362     //  ...
7363     BB = sinkMBB;
7364     BuildMI(*BB, BB->begin(), dl,
7365             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7366       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7367       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7368
7369     MI->eraseFromParent();   // The pseudo instruction is gone now.
7370     return BB;
7371   }
7372
7373   case ARM::BCCi64:
7374   case ARM::BCCZi64: {
7375     // If there is an unconditional branch to the other successor, remove it.
7376     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7377
7378     // Compare both parts that make up the double comparison separately for
7379     // equality.
7380     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7381
7382     unsigned LHS1 = MI->getOperand(1).getReg();
7383     unsigned LHS2 = MI->getOperand(2).getReg();
7384     if (RHSisZero) {
7385       AddDefaultPred(BuildMI(BB, dl,
7386                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7387                      .addReg(LHS1).addImm(0));
7388       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7389         .addReg(LHS2).addImm(0)
7390         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7391     } else {
7392       unsigned RHS1 = MI->getOperand(3).getReg();
7393       unsigned RHS2 = MI->getOperand(4).getReg();
7394       AddDefaultPred(BuildMI(BB, dl,
7395                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7396                      .addReg(LHS1).addReg(RHS1));
7397       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7398         .addReg(LHS2).addReg(RHS2)
7399         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7400     }
7401
7402     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7403     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7404     if (MI->getOperand(0).getImm() == ARMCC::NE)
7405       std::swap(destMBB, exitMBB);
7406
7407     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7408       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7409     if (isThumb2)
7410       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7411     else
7412       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7413
7414     MI->eraseFromParent();   // The pseudo instruction is gone now.
7415     return BB;
7416   }
7417
7418   case ARM::Int_eh_sjlj_setjmp:
7419   case ARM::Int_eh_sjlj_setjmp_nofp:
7420   case ARM::tInt_eh_sjlj_setjmp:
7421   case ARM::t2Int_eh_sjlj_setjmp:
7422   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7423     EmitSjLjDispatchBlock(MI, BB);
7424     return BB;
7425
7426   case ARM::ABS:
7427   case ARM::t2ABS: {
7428     // To insert an ABS instruction, we have to insert the
7429     // diamond control-flow pattern.  The incoming instruction knows the
7430     // source vreg to test against 0, the destination vreg to set,
7431     // the condition code register to branch on, the
7432     // true/false values to select between, and a branch opcode to use.
7433     // It transforms
7434     //     V1 = ABS V0
7435     // into
7436     //     V2 = MOVS V0
7437     //     BCC                      (branch to SinkBB if V0 >= 0)
7438     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7439     //     SinkBB: V1 = PHI(V2, V3)
7440     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7441     MachineFunction::iterator BBI = BB;
7442     ++BBI;
7443     MachineFunction *Fn = BB->getParent();
7444     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7445     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7446     Fn->insert(BBI, RSBBB);
7447     Fn->insert(BBI, SinkBB);
7448
7449     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7450     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7451     bool isThumb2 = Subtarget->isThumb2();
7452     MachineRegisterInfo &MRI = Fn->getRegInfo();
7453     // In Thumb mode S must not be specified if source register is the SP or
7454     // PC and if destination register is the SP, so restrict register class
7455     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7456       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7457       (const TargetRegisterClass*)&ARM::GPRRegClass);
7458
7459     // Transfer the remainder of BB and its successor edges to sinkMBB.
7460     SinkBB->splice(SinkBB->begin(), BB,
7461                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7462     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7463
7464     BB->addSuccessor(RSBBB);
7465     BB->addSuccessor(SinkBB);
7466
7467     // fall through to SinkMBB
7468     RSBBB->addSuccessor(SinkBB);
7469
7470     // insert a cmp at the end of BB
7471     AddDefaultPred(BuildMI(BB, dl,
7472                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7473                    .addReg(ABSSrcReg).addImm(0));
7474
7475     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7476     BuildMI(BB, dl,
7477       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7478       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7479
7480     // insert rsbri in RSBBB
7481     // Note: BCC and rsbri will be converted into predicated rsbmi
7482     // by if-conversion pass
7483     BuildMI(*RSBBB, RSBBB->begin(), dl,
7484       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7485       .addReg(ABSSrcReg, RegState::Kill)
7486       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7487
7488     // insert PHI in SinkBB,
7489     // reuse ABSDstReg to not change uses of ABS instruction
7490     BuildMI(*SinkBB, SinkBB->begin(), dl,
7491       TII->get(ARM::PHI), ABSDstReg)
7492       .addReg(NewRsbDstReg).addMBB(RSBBB)
7493       .addReg(ABSSrcReg).addMBB(BB);
7494
7495     // remove ABS instruction
7496     MI->eraseFromParent();
7497
7498     // return last added BB
7499     return SinkBB;
7500   }
7501   case ARM::COPY_STRUCT_BYVAL_I32:
7502     ++NumLoopByVals;
7503     return EmitStructByval(MI, BB);
7504   case ARM::WIN__CHKSTK:
7505     return EmitLowered__chkstk(MI, BB);
7506   }
7507 }
7508
7509 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7510                                                       SDNode *Node) const {
7511   if (!MI->hasPostISelHook()) {
7512     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7513            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7514     return;
7515   }
7516
7517   const MCInstrDesc *MCID = &MI->getDesc();
7518   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7519   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7520   // operand is still set to noreg. If needed, set the optional operand's
7521   // register to CPSR, and remove the redundant implicit def.
7522   //
7523   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7524
7525   // Rename pseudo opcodes.
7526   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7527   if (NewOpc) {
7528     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7529         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7530     MCID = &TII->get(NewOpc);
7531
7532     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7533            "converted opcode should be the same except for cc_out");
7534
7535     MI->setDesc(*MCID);
7536
7537     // Add the optional cc_out operand
7538     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7539   }
7540   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7541
7542   // Any ARM instruction that sets the 's' bit should specify an optional
7543   // "cc_out" operand in the last operand position.
7544   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7545     assert(!NewOpc && "Optional cc_out operand required");
7546     return;
7547   }
7548   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7549   // since we already have an optional CPSR def.
7550   bool definesCPSR = false;
7551   bool deadCPSR = false;
7552   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7553        i != e; ++i) {
7554     const MachineOperand &MO = MI->getOperand(i);
7555     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7556       definesCPSR = true;
7557       if (MO.isDead())
7558         deadCPSR = true;
7559       MI->RemoveOperand(i);
7560       break;
7561     }
7562   }
7563   if (!definesCPSR) {
7564     assert(!NewOpc && "Optional cc_out operand required");
7565     return;
7566   }
7567   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7568   if (deadCPSR) {
7569     assert(!MI->getOperand(ccOutIdx).getReg() &&
7570            "expect uninitialized optional cc_out operand");
7571     return;
7572   }
7573
7574   // If this instruction was defined with an optional CPSR def and its dag node
7575   // had a live implicit CPSR def, then activate the optional CPSR def.
7576   MachineOperand &MO = MI->getOperand(ccOutIdx);
7577   MO.setReg(ARM::CPSR);
7578   MO.setIsDef(true);
7579 }
7580
7581 //===----------------------------------------------------------------------===//
7582 //                           ARM Optimization Hooks
7583 //===----------------------------------------------------------------------===//
7584
7585 // Helper function that checks if N is a null or all ones constant.
7586 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7587   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7588   if (!C)
7589     return false;
7590   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7591 }
7592
7593 // Return true if N is conditionally 0 or all ones.
7594 // Detects these expressions where cc is an i1 value:
7595 //
7596 //   (select cc 0, y)   [AllOnes=0]
7597 //   (select cc y, 0)   [AllOnes=0]
7598 //   (zext cc)          [AllOnes=0]
7599 //   (sext cc)          [AllOnes=0/1]
7600 //   (select cc -1, y)  [AllOnes=1]
7601 //   (select cc y, -1)  [AllOnes=1]
7602 //
7603 // Invert is set when N is the null/all ones constant when CC is false.
7604 // OtherOp is set to the alternative value of N.
7605 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7606                                        SDValue &CC, bool &Invert,
7607                                        SDValue &OtherOp,
7608                                        SelectionDAG &DAG) {
7609   switch (N->getOpcode()) {
7610   default: return false;
7611   case ISD::SELECT: {
7612     CC = N->getOperand(0);
7613     SDValue N1 = N->getOperand(1);
7614     SDValue N2 = N->getOperand(2);
7615     if (isZeroOrAllOnes(N1, AllOnes)) {
7616       Invert = false;
7617       OtherOp = N2;
7618       return true;
7619     }
7620     if (isZeroOrAllOnes(N2, AllOnes)) {
7621       Invert = true;
7622       OtherOp = N1;
7623       return true;
7624     }
7625     return false;
7626   }
7627   case ISD::ZERO_EXTEND:
7628     // (zext cc) can never be the all ones value.
7629     if (AllOnes)
7630       return false;
7631     // Fall through.
7632   case ISD::SIGN_EXTEND: {
7633     EVT VT = N->getValueType(0);
7634     CC = N->getOperand(0);
7635     if (CC.getValueType() != MVT::i1)
7636       return false;
7637     Invert = !AllOnes;
7638     if (AllOnes)
7639       // When looking for an AllOnes constant, N is an sext, and the 'other'
7640       // value is 0.
7641       OtherOp = DAG.getConstant(0, VT);
7642     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7643       // When looking for a 0 constant, N can be zext or sext.
7644       OtherOp = DAG.getConstant(1, VT);
7645     else
7646       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7647     return true;
7648   }
7649   }
7650 }
7651
7652 // Combine a constant select operand into its use:
7653 //
7654 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7655 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7656 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7657 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7658 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7659 //
7660 // The transform is rejected if the select doesn't have a constant operand that
7661 // is null, or all ones when AllOnes is set.
7662 //
7663 // Also recognize sext/zext from i1:
7664 //
7665 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7666 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7667 //
7668 // These transformations eventually create predicated instructions.
7669 //
7670 // @param N       The node to transform.
7671 // @param Slct    The N operand that is a select.
7672 // @param OtherOp The other N operand (x above).
7673 // @param DCI     Context.
7674 // @param AllOnes Require the select constant to be all ones instead of null.
7675 // @returns The new node, or SDValue() on failure.
7676 static
7677 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7678                             TargetLowering::DAGCombinerInfo &DCI,
7679                             bool AllOnes = false) {
7680   SelectionDAG &DAG = DCI.DAG;
7681   EVT VT = N->getValueType(0);
7682   SDValue NonConstantVal;
7683   SDValue CCOp;
7684   bool SwapSelectOps;
7685   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7686                                   NonConstantVal, DAG))
7687     return SDValue();
7688
7689   // Slct is now know to be the desired identity constant when CC is true.
7690   SDValue TrueVal = OtherOp;
7691   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7692                                  OtherOp, NonConstantVal);
7693   // Unless SwapSelectOps says CC should be false.
7694   if (SwapSelectOps)
7695     std::swap(TrueVal, FalseVal);
7696
7697   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7698                      CCOp, TrueVal, FalseVal);
7699 }
7700
7701 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7702 static
7703 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7704                                        TargetLowering::DAGCombinerInfo &DCI) {
7705   SDValue N0 = N->getOperand(0);
7706   SDValue N1 = N->getOperand(1);
7707   if (N0.getNode()->hasOneUse()) {
7708     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7709     if (Result.getNode())
7710       return Result;
7711   }
7712   if (N1.getNode()->hasOneUse()) {
7713     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7714     if (Result.getNode())
7715       return Result;
7716   }
7717   return SDValue();
7718 }
7719
7720 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7721 // (only after legalization).
7722 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7723                                  TargetLowering::DAGCombinerInfo &DCI,
7724                                  const ARMSubtarget *Subtarget) {
7725
7726   // Only perform optimization if after legalize, and if NEON is available. We
7727   // also expected both operands to be BUILD_VECTORs.
7728   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7729       || N0.getOpcode() != ISD::BUILD_VECTOR
7730       || N1.getOpcode() != ISD::BUILD_VECTOR)
7731     return SDValue();
7732
7733   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7734   EVT VT = N->getValueType(0);
7735   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7736     return SDValue();
7737
7738   // Check that the vector operands are of the right form.
7739   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7740   // operands, where N is the size of the formed vector.
7741   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7742   // index such that we have a pair wise add pattern.
7743
7744   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7745   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7746     return SDValue();
7747   SDValue Vec = N0->getOperand(0)->getOperand(0);
7748   SDNode *V = Vec.getNode();
7749   unsigned nextIndex = 0;
7750
7751   // For each operands to the ADD which are BUILD_VECTORs,
7752   // check to see if each of their operands are an EXTRACT_VECTOR with
7753   // the same vector and appropriate index.
7754   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7755     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7756         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7757
7758       SDValue ExtVec0 = N0->getOperand(i);
7759       SDValue ExtVec1 = N1->getOperand(i);
7760
7761       // First operand is the vector, verify its the same.
7762       if (V != ExtVec0->getOperand(0).getNode() ||
7763           V != ExtVec1->getOperand(0).getNode())
7764         return SDValue();
7765
7766       // Second is the constant, verify its correct.
7767       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7768       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7769
7770       // For the constant, we want to see all the even or all the odd.
7771       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7772           || C1->getZExtValue() != nextIndex+1)
7773         return SDValue();
7774
7775       // Increment index.
7776       nextIndex+=2;
7777     } else
7778       return SDValue();
7779   }
7780
7781   // Create VPADDL node.
7782   SelectionDAG &DAG = DCI.DAG;
7783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7784
7785   // Build operand list.
7786   SmallVector<SDValue, 8> Ops;
7787   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7788                                 TLI.getPointerTy()));
7789
7790   // Input is the vector.
7791   Ops.push_back(Vec);
7792
7793   // Get widened type and narrowed type.
7794   MVT widenType;
7795   unsigned numElem = VT.getVectorNumElements();
7796   
7797   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7798   switch (inputLaneType.getSimpleVT().SimpleTy) {
7799     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7800     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7801     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7802     default:
7803       llvm_unreachable("Invalid vector element type for padd optimization.");
7804   }
7805
7806   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7807   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7808   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7809 }
7810
7811 static SDValue findMUL_LOHI(SDValue V) {
7812   if (V->getOpcode() == ISD::UMUL_LOHI ||
7813       V->getOpcode() == ISD::SMUL_LOHI)
7814     return V;
7815   return SDValue();
7816 }
7817
7818 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7819                                      TargetLowering::DAGCombinerInfo &DCI,
7820                                      const ARMSubtarget *Subtarget) {
7821
7822   if (Subtarget->isThumb1Only()) return SDValue();
7823
7824   // Only perform the checks after legalize when the pattern is available.
7825   if (DCI.isBeforeLegalize()) return SDValue();
7826
7827   // Look for multiply add opportunities.
7828   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7829   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7830   // a glue link from the first add to the second add.
7831   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7832   // a S/UMLAL instruction.
7833   //          loAdd   UMUL_LOHI
7834   //            \    / :lo    \ :hi
7835   //             \  /          \          [no multiline comment]
7836   //              ADDC         |  hiAdd
7837   //                 \ :glue  /  /
7838   //                  \      /  /
7839   //                    ADDE
7840   //
7841   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7842   SDValue AddcOp0 = AddcNode->getOperand(0);
7843   SDValue AddcOp1 = AddcNode->getOperand(1);
7844
7845   // Check if the two operands are from the same mul_lohi node.
7846   if (AddcOp0.getNode() == AddcOp1.getNode())
7847     return SDValue();
7848
7849   assert(AddcNode->getNumValues() == 2 &&
7850          AddcNode->getValueType(0) == MVT::i32 &&
7851          "Expect ADDC with two result values. First: i32");
7852
7853   // Check that we have a glued ADDC node.
7854   if (AddcNode->getValueType(1) != MVT::Glue)
7855     return SDValue();
7856
7857   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7858   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7859       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7860       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7861       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7862     return SDValue();
7863
7864   // Look for the glued ADDE.
7865   SDNode* AddeNode = AddcNode->getGluedUser();
7866   if (!AddeNode)
7867     return SDValue();
7868
7869   // Make sure it is really an ADDE.
7870   if (AddeNode->getOpcode() != ISD::ADDE)
7871     return SDValue();
7872
7873   assert(AddeNode->getNumOperands() == 3 &&
7874          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7875          "ADDE node has the wrong inputs");
7876
7877   // Check for the triangle shape.
7878   SDValue AddeOp0 = AddeNode->getOperand(0);
7879   SDValue AddeOp1 = AddeNode->getOperand(1);
7880
7881   // Make sure that the ADDE operands are not coming from the same node.
7882   if (AddeOp0.getNode() == AddeOp1.getNode())
7883     return SDValue();
7884
7885   // Find the MUL_LOHI node walking up ADDE's operands.
7886   bool IsLeftOperandMUL = false;
7887   SDValue MULOp = findMUL_LOHI(AddeOp0);
7888   if (MULOp == SDValue())
7889    MULOp = findMUL_LOHI(AddeOp1);
7890   else
7891     IsLeftOperandMUL = true;
7892   if (MULOp == SDValue())
7893      return SDValue();
7894
7895   // Figure out the right opcode.
7896   unsigned Opc = MULOp->getOpcode();
7897   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7898
7899   // Figure out the high and low input values to the MLAL node.
7900   SDValue* HiMul = &MULOp;
7901   SDValue* HiAdd = nullptr;
7902   SDValue* LoMul = nullptr;
7903   SDValue* LowAdd = nullptr;
7904
7905   if (IsLeftOperandMUL)
7906     HiAdd = &AddeOp1;
7907   else
7908     HiAdd = &AddeOp0;
7909
7910
7911   if (AddcOp0->getOpcode() == Opc) {
7912     LoMul = &AddcOp0;
7913     LowAdd = &AddcOp1;
7914   }
7915   if (AddcOp1->getOpcode() == Opc) {
7916     LoMul = &AddcOp1;
7917     LowAdd = &AddcOp0;
7918   }
7919
7920   if (!LoMul)
7921     return SDValue();
7922
7923   if (LoMul->getNode() != HiMul->getNode())
7924     return SDValue();
7925
7926   // Create the merged node.
7927   SelectionDAG &DAG = DCI.DAG;
7928
7929   // Build operand list.
7930   SmallVector<SDValue, 8> Ops;
7931   Ops.push_back(LoMul->getOperand(0));
7932   Ops.push_back(LoMul->getOperand(1));
7933   Ops.push_back(*LowAdd);
7934   Ops.push_back(*HiAdd);
7935
7936   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7937                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7938
7939   // Replace the ADDs' nodes uses by the MLA node's values.
7940   SDValue HiMLALResult(MLALNode.getNode(), 1);
7941   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7942
7943   SDValue LoMLALResult(MLALNode.getNode(), 0);
7944   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7945
7946   // Return original node to notify the driver to stop replacing.
7947   SDValue resNode(AddcNode, 0);
7948   return resNode;
7949 }
7950
7951 /// PerformADDCCombine - Target-specific dag combine transform from
7952 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7953 static SDValue PerformADDCCombine(SDNode *N,
7954                                  TargetLowering::DAGCombinerInfo &DCI,
7955                                  const ARMSubtarget *Subtarget) {
7956
7957   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7958
7959 }
7960
7961 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7962 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7963 /// called with the default operands, and if that fails, with commuted
7964 /// operands.
7965 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7966                                           TargetLowering::DAGCombinerInfo &DCI,
7967                                           const ARMSubtarget *Subtarget){
7968
7969   // Attempt to create vpaddl for this add.
7970   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7971   if (Result.getNode())
7972     return Result;
7973
7974   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7975   if (N0.getNode()->hasOneUse()) {
7976     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7977     if (Result.getNode()) return Result;
7978   }
7979   return SDValue();
7980 }
7981
7982 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7983 ///
7984 static SDValue PerformADDCombine(SDNode *N,
7985                                  TargetLowering::DAGCombinerInfo &DCI,
7986                                  const ARMSubtarget *Subtarget) {
7987   SDValue N0 = N->getOperand(0);
7988   SDValue N1 = N->getOperand(1);
7989
7990   // First try with the default operand order.
7991   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7992   if (Result.getNode())
7993     return Result;
7994
7995   // If that didn't work, try again with the operands commuted.
7996   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7997 }
7998
7999 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8000 ///
8001 static SDValue PerformSUBCombine(SDNode *N,
8002                                  TargetLowering::DAGCombinerInfo &DCI) {
8003   SDValue N0 = N->getOperand(0);
8004   SDValue N1 = N->getOperand(1);
8005
8006   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8007   if (N1.getNode()->hasOneUse()) {
8008     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8009     if (Result.getNode()) return Result;
8010   }
8011
8012   return SDValue();
8013 }
8014
8015 /// PerformVMULCombine
8016 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8017 /// special multiplier accumulator forwarding.
8018 ///   vmul d3, d0, d2
8019 ///   vmla d3, d1, d2
8020 /// is faster than
8021 ///   vadd d3, d0, d1
8022 ///   vmul d3, d3, d2
8023 //  However, for (A + B) * (A + B),
8024 //    vadd d2, d0, d1
8025 //    vmul d3, d0, d2
8026 //    vmla d3, d1, d2
8027 //  is slower than
8028 //    vadd d2, d0, d1
8029 //    vmul d3, d2, d2
8030 static SDValue PerformVMULCombine(SDNode *N,
8031                                   TargetLowering::DAGCombinerInfo &DCI,
8032                                   const ARMSubtarget *Subtarget) {
8033   if (!Subtarget->hasVMLxForwarding())
8034     return SDValue();
8035
8036   SelectionDAG &DAG = DCI.DAG;
8037   SDValue N0 = N->getOperand(0);
8038   SDValue N1 = N->getOperand(1);
8039   unsigned Opcode = N0.getOpcode();
8040   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8041       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8042     Opcode = N1.getOpcode();
8043     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8044         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8045       return SDValue();
8046     std::swap(N0, N1);
8047   }
8048
8049   if (N0 == N1)
8050     return SDValue();
8051
8052   EVT VT = N->getValueType(0);
8053   SDLoc DL(N);
8054   SDValue N00 = N0->getOperand(0);
8055   SDValue N01 = N0->getOperand(1);
8056   return DAG.getNode(Opcode, DL, VT,
8057                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8058                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8059 }
8060
8061 static SDValue PerformMULCombine(SDNode *N,
8062                                  TargetLowering::DAGCombinerInfo &DCI,
8063                                  const ARMSubtarget *Subtarget) {
8064   SelectionDAG &DAG = DCI.DAG;
8065
8066   if (Subtarget->isThumb1Only())
8067     return SDValue();
8068
8069   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8070     return SDValue();
8071
8072   EVT VT = N->getValueType(0);
8073   if (VT.is64BitVector() || VT.is128BitVector())
8074     return PerformVMULCombine(N, DCI, Subtarget);
8075   if (VT != MVT::i32)
8076     return SDValue();
8077
8078   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8079   if (!C)
8080     return SDValue();
8081
8082   int64_t MulAmt = C->getSExtValue();
8083   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8084
8085   ShiftAmt = ShiftAmt & (32 - 1);
8086   SDValue V = N->getOperand(0);
8087   SDLoc DL(N);
8088
8089   SDValue Res;
8090   MulAmt >>= ShiftAmt;
8091
8092   if (MulAmt >= 0) {
8093     if (isPowerOf2_32(MulAmt - 1)) {
8094       // (mul x, 2^N + 1) => (add (shl x, N), x)
8095       Res = DAG.getNode(ISD::ADD, DL, VT,
8096                         V,
8097                         DAG.getNode(ISD::SHL, DL, VT,
8098                                     V,
8099                                     DAG.getConstant(Log2_32(MulAmt - 1),
8100                                                     MVT::i32)));
8101     } else if (isPowerOf2_32(MulAmt + 1)) {
8102       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8103       Res = DAG.getNode(ISD::SUB, DL, VT,
8104                         DAG.getNode(ISD::SHL, DL, VT,
8105                                     V,
8106                                     DAG.getConstant(Log2_32(MulAmt + 1),
8107                                                     MVT::i32)),
8108                         V);
8109     } else
8110       return SDValue();
8111   } else {
8112     uint64_t MulAmtAbs = -MulAmt;
8113     if (isPowerOf2_32(MulAmtAbs + 1)) {
8114       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8115       Res = DAG.getNode(ISD::SUB, DL, VT,
8116                         V,
8117                         DAG.getNode(ISD::SHL, DL, VT,
8118                                     V,
8119                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8120                                                     MVT::i32)));
8121     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8122       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8123       Res = DAG.getNode(ISD::ADD, DL, VT,
8124                         V,
8125                         DAG.getNode(ISD::SHL, DL, VT,
8126                                     V,
8127                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8128                                                     MVT::i32)));
8129       Res = DAG.getNode(ISD::SUB, DL, VT,
8130                         DAG.getConstant(0, MVT::i32),Res);
8131
8132     } else
8133       return SDValue();
8134   }
8135
8136   if (ShiftAmt != 0)
8137     Res = DAG.getNode(ISD::SHL, DL, VT,
8138                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8139
8140   // Do not add new nodes to DAG combiner worklist.
8141   DCI.CombineTo(N, Res, false);
8142   return SDValue();
8143 }
8144
8145 static SDValue PerformANDCombine(SDNode *N,
8146                                  TargetLowering::DAGCombinerInfo &DCI,
8147                                  const ARMSubtarget *Subtarget) {
8148
8149   // Attempt to use immediate-form VBIC
8150   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8151   SDLoc dl(N);
8152   EVT VT = N->getValueType(0);
8153   SelectionDAG &DAG = DCI.DAG;
8154
8155   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8156     return SDValue();
8157
8158   APInt SplatBits, SplatUndef;
8159   unsigned SplatBitSize;
8160   bool HasAnyUndefs;
8161   if (BVN &&
8162       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8163     if (SplatBitSize <= 64) {
8164       EVT VbicVT;
8165       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8166                                       SplatUndef.getZExtValue(), SplatBitSize,
8167                                       DAG, VbicVT, VT.is128BitVector(),
8168                                       OtherModImm);
8169       if (Val.getNode()) {
8170         SDValue Input =
8171           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8172         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8173         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8174       }
8175     }
8176   }
8177
8178   if (!Subtarget->isThumb1Only()) {
8179     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8180     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8181     if (Result.getNode())
8182       return Result;
8183   }
8184
8185   return SDValue();
8186 }
8187
8188 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8189 static SDValue PerformORCombine(SDNode *N,
8190                                 TargetLowering::DAGCombinerInfo &DCI,
8191                                 const ARMSubtarget *Subtarget) {
8192   // Attempt to use immediate-form VORR
8193   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8194   SDLoc dl(N);
8195   EVT VT = N->getValueType(0);
8196   SelectionDAG &DAG = DCI.DAG;
8197
8198   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8199     return SDValue();
8200
8201   APInt SplatBits, SplatUndef;
8202   unsigned SplatBitSize;
8203   bool HasAnyUndefs;
8204   if (BVN && Subtarget->hasNEON() &&
8205       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8206     if (SplatBitSize <= 64) {
8207       EVT VorrVT;
8208       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8209                                       SplatUndef.getZExtValue(), SplatBitSize,
8210                                       DAG, VorrVT, VT.is128BitVector(),
8211                                       OtherModImm);
8212       if (Val.getNode()) {
8213         SDValue Input =
8214           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8215         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8216         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8217       }
8218     }
8219   }
8220
8221   if (!Subtarget->isThumb1Only()) {
8222     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8223     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8224     if (Result.getNode())
8225       return Result;
8226   }
8227
8228   // The code below optimizes (or (and X, Y), Z).
8229   // The AND operand needs to have a single user to make these optimizations
8230   // profitable.
8231   SDValue N0 = N->getOperand(0);
8232   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8233     return SDValue();
8234   SDValue N1 = N->getOperand(1);
8235
8236   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8237   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8238       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8239     APInt SplatUndef;
8240     unsigned SplatBitSize;
8241     bool HasAnyUndefs;
8242
8243     APInt SplatBits0, SplatBits1;
8244     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8245     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8246     // Ensure that the second operand of both ands are constants
8247     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8248                                       HasAnyUndefs) && !HasAnyUndefs) {
8249         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8250                                           HasAnyUndefs) && !HasAnyUndefs) {
8251             // Ensure that the bit width of the constants are the same and that
8252             // the splat arguments are logical inverses as per the pattern we
8253             // are trying to simplify.
8254             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8255                 SplatBits0 == ~SplatBits1) {
8256                 // Canonicalize the vector type to make instruction selection
8257                 // simpler.
8258                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8259                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8260                                              N0->getOperand(1),
8261                                              N0->getOperand(0),
8262                                              N1->getOperand(0));
8263                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8264             }
8265         }
8266     }
8267   }
8268
8269   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8270   // reasonable.
8271
8272   // BFI is only available on V6T2+
8273   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8274     return SDValue();
8275
8276   SDLoc DL(N);
8277   // 1) or (and A, mask), val => ARMbfi A, val, mask
8278   //      iff (val & mask) == val
8279   //
8280   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8281   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8282   //          && mask == ~mask2
8283   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8284   //          && ~mask == mask2
8285   //  (i.e., copy a bitfield value into another bitfield of the same width)
8286
8287   if (VT != MVT::i32)
8288     return SDValue();
8289
8290   SDValue N00 = N0.getOperand(0);
8291
8292   // The value and the mask need to be constants so we can verify this is
8293   // actually a bitfield set. If the mask is 0xffff, we can do better
8294   // via a movt instruction, so don't use BFI in that case.
8295   SDValue MaskOp = N0.getOperand(1);
8296   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8297   if (!MaskC)
8298     return SDValue();
8299   unsigned Mask = MaskC->getZExtValue();
8300   if (Mask == 0xffff)
8301     return SDValue();
8302   SDValue Res;
8303   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8304   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8305   if (N1C) {
8306     unsigned Val = N1C->getZExtValue();
8307     if ((Val & ~Mask) != Val)
8308       return SDValue();
8309
8310     if (ARM::isBitFieldInvertedMask(Mask)) {
8311       Val >>= countTrailingZeros(~Mask);
8312
8313       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8314                         DAG.getConstant(Val, MVT::i32),
8315                         DAG.getConstant(Mask, MVT::i32));
8316
8317       // Do not add new nodes to DAG combiner worklist.
8318       DCI.CombineTo(N, Res, false);
8319       return SDValue();
8320     }
8321   } else if (N1.getOpcode() == ISD::AND) {
8322     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8323     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8324     if (!N11C)
8325       return SDValue();
8326     unsigned Mask2 = N11C->getZExtValue();
8327
8328     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8329     // as is to match.
8330     if (ARM::isBitFieldInvertedMask(Mask) &&
8331         (Mask == ~Mask2)) {
8332       // The pack halfword instruction works better for masks that fit it,
8333       // so use that when it's available.
8334       if (Subtarget->hasT2ExtractPack() &&
8335           (Mask == 0xffff || Mask == 0xffff0000))
8336         return SDValue();
8337       // 2a
8338       unsigned amt = countTrailingZeros(Mask2);
8339       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8340                         DAG.getConstant(amt, MVT::i32));
8341       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8342                         DAG.getConstant(Mask, MVT::i32));
8343       // Do not add new nodes to DAG combiner worklist.
8344       DCI.CombineTo(N, Res, false);
8345       return SDValue();
8346     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8347                (~Mask == Mask2)) {
8348       // The pack halfword instruction works better for masks that fit it,
8349       // so use that when it's available.
8350       if (Subtarget->hasT2ExtractPack() &&
8351           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8352         return SDValue();
8353       // 2b
8354       unsigned lsb = countTrailingZeros(Mask);
8355       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8356                         DAG.getConstant(lsb, MVT::i32));
8357       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8358                         DAG.getConstant(Mask2, MVT::i32));
8359       // Do not add new nodes to DAG combiner worklist.
8360       DCI.CombineTo(N, Res, false);
8361       return SDValue();
8362     }
8363   }
8364
8365   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8366       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8367       ARM::isBitFieldInvertedMask(~Mask)) {
8368     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8369     // where lsb(mask) == #shamt and masked bits of B are known zero.
8370     SDValue ShAmt = N00.getOperand(1);
8371     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8372     unsigned LSB = countTrailingZeros(Mask);
8373     if (ShAmtC != LSB)
8374       return SDValue();
8375
8376     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8377                       DAG.getConstant(~Mask, MVT::i32));
8378
8379     // Do not add new nodes to DAG combiner worklist.
8380     DCI.CombineTo(N, Res, false);
8381   }
8382
8383   return SDValue();
8384 }
8385
8386 static SDValue PerformXORCombine(SDNode *N,
8387                                  TargetLowering::DAGCombinerInfo &DCI,
8388                                  const ARMSubtarget *Subtarget) {
8389   EVT VT = N->getValueType(0);
8390   SelectionDAG &DAG = DCI.DAG;
8391
8392   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8393     return SDValue();
8394
8395   if (!Subtarget->isThumb1Only()) {
8396     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8397     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8398     if (Result.getNode())
8399       return Result;
8400   }
8401
8402   return SDValue();
8403 }
8404
8405 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8406 /// the bits being cleared by the AND are not demanded by the BFI.
8407 static SDValue PerformBFICombine(SDNode *N,
8408                                  TargetLowering::DAGCombinerInfo &DCI) {
8409   SDValue N1 = N->getOperand(1);
8410   if (N1.getOpcode() == ISD::AND) {
8411     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8412     if (!N11C)
8413       return SDValue();
8414     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8415     unsigned LSB = countTrailingZeros(~InvMask);
8416     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8417     unsigned Mask = (1 << Width)-1;
8418     unsigned Mask2 = N11C->getZExtValue();
8419     if ((Mask & (~Mask2)) == 0)
8420       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8421                              N->getOperand(0), N1.getOperand(0),
8422                              N->getOperand(2));
8423   }
8424   return SDValue();
8425 }
8426
8427 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8428 /// ARMISD::VMOVRRD.
8429 static SDValue PerformVMOVRRDCombine(SDNode *N,
8430                                      TargetLowering::DAGCombinerInfo &DCI) {
8431   // vmovrrd(vmovdrr x, y) -> x,y
8432   SDValue InDouble = N->getOperand(0);
8433   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8434     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8435
8436   // vmovrrd(load f64) -> (load i32), (load i32)
8437   SDNode *InNode = InDouble.getNode();
8438   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8439       InNode->getValueType(0) == MVT::f64 &&
8440       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8441       !cast<LoadSDNode>(InNode)->isVolatile()) {
8442     // TODO: Should this be done for non-FrameIndex operands?
8443     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8444
8445     SelectionDAG &DAG = DCI.DAG;
8446     SDLoc DL(LD);
8447     SDValue BasePtr = LD->getBasePtr();
8448     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8449                                  LD->getPointerInfo(), LD->isVolatile(),
8450                                  LD->isNonTemporal(), LD->isInvariant(),
8451                                  LD->getAlignment());
8452
8453     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8454                                     DAG.getConstant(4, MVT::i32));
8455     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8456                                  LD->getPointerInfo(), LD->isVolatile(),
8457                                  LD->isNonTemporal(), LD->isInvariant(),
8458                                  std::min(4U, LD->getAlignment() / 2));
8459
8460     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8461     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8462       std::swap (NewLD1, NewLD2);
8463     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8464     return Result;
8465   }
8466
8467   return SDValue();
8468 }
8469
8470 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8471 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8472 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8473   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8474   SDValue Op0 = N->getOperand(0);
8475   SDValue Op1 = N->getOperand(1);
8476   if (Op0.getOpcode() == ISD::BITCAST)
8477     Op0 = Op0.getOperand(0);
8478   if (Op1.getOpcode() == ISD::BITCAST)
8479     Op1 = Op1.getOperand(0);
8480   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8481       Op0.getNode() == Op1.getNode() &&
8482       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8483     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8484                        N->getValueType(0), Op0.getOperand(0));
8485   return SDValue();
8486 }
8487
8488 /// PerformSTORECombine - Target-specific dag combine xforms for
8489 /// ISD::STORE.
8490 static SDValue PerformSTORECombine(SDNode *N,
8491                                    TargetLowering::DAGCombinerInfo &DCI) {
8492   StoreSDNode *St = cast<StoreSDNode>(N);
8493   if (St->isVolatile())
8494     return SDValue();
8495
8496   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8497   // pack all of the elements in one place.  Next, store to memory in fewer
8498   // chunks.
8499   SDValue StVal = St->getValue();
8500   EVT VT = StVal.getValueType();
8501   if (St->isTruncatingStore() && VT.isVector()) {
8502     SelectionDAG &DAG = DCI.DAG;
8503     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8504     EVT StVT = St->getMemoryVT();
8505     unsigned NumElems = VT.getVectorNumElements();
8506     assert(StVT != VT && "Cannot truncate to the same type");
8507     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8508     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8509
8510     // From, To sizes and ElemCount must be pow of two
8511     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8512
8513     // We are going to use the original vector elt for storing.
8514     // Accumulated smaller vector elements must be a multiple of the store size.
8515     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8516
8517     unsigned SizeRatio  = FromEltSz / ToEltSz;
8518     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8519
8520     // Create a type on which we perform the shuffle.
8521     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8522                                      NumElems*SizeRatio);
8523     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8524
8525     SDLoc DL(St);
8526     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8527     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8528     for (unsigned i = 0; i < NumElems; ++i)
8529       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8530
8531     // Can't shuffle using an illegal type.
8532     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8533
8534     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8535                                 DAG.getUNDEF(WideVec.getValueType()),
8536                                 ShuffleVec.data());
8537     // At this point all of the data is stored at the bottom of the
8538     // register. We now need to save it to mem.
8539
8540     // Find the largest store unit
8541     MVT StoreType = MVT::i8;
8542     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8543          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8544       MVT Tp = (MVT::SimpleValueType)tp;
8545       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8546         StoreType = Tp;
8547     }
8548     // Didn't find a legal store type.
8549     if (!TLI.isTypeLegal(StoreType))
8550       return SDValue();
8551
8552     // Bitcast the original vector into a vector of store-size units
8553     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8554             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8555     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8556     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8557     SmallVector<SDValue, 8> Chains;
8558     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8559                                         TLI.getPointerTy());
8560     SDValue BasePtr = St->getBasePtr();
8561
8562     // Perform one or more big stores into memory.
8563     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8564     for (unsigned I = 0; I < E; I++) {
8565       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8566                                    StoreType, ShuffWide,
8567                                    DAG.getIntPtrConstant(I));
8568       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8569                                 St->getPointerInfo(), St->isVolatile(),
8570                                 St->isNonTemporal(), St->getAlignment());
8571       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8572                             Increment);
8573       Chains.push_back(Ch);
8574     }
8575     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8576   }
8577
8578   if (!ISD::isNormalStore(St))
8579     return SDValue();
8580
8581   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8582   // ARM stores of arguments in the same cache line.
8583   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8584       StVal.getNode()->hasOneUse()) {
8585     SelectionDAG  &DAG = DCI.DAG;
8586     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8587     SDLoc DL(St);
8588     SDValue BasePtr = St->getBasePtr();
8589     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8590                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8591                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8592                                   St->isNonTemporal(), St->getAlignment());
8593
8594     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8595                                     DAG.getConstant(4, MVT::i32));
8596     return DAG.getStore(NewST1.getValue(0), DL,
8597                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8598                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8599                         St->isNonTemporal(),
8600                         std::min(4U, St->getAlignment() / 2));
8601   }
8602
8603   if (StVal.getValueType() != MVT::i64 ||
8604       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8605     return SDValue();
8606
8607   // Bitcast an i64 store extracted from a vector to f64.
8608   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8609   SelectionDAG &DAG = DCI.DAG;
8610   SDLoc dl(StVal);
8611   SDValue IntVec = StVal.getOperand(0);
8612   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8613                                  IntVec.getValueType().getVectorNumElements());
8614   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8615   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8616                                Vec, StVal.getOperand(1));
8617   dl = SDLoc(N);
8618   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8619   // Make the DAGCombiner fold the bitcasts.
8620   DCI.AddToWorklist(Vec.getNode());
8621   DCI.AddToWorklist(ExtElt.getNode());
8622   DCI.AddToWorklist(V.getNode());
8623   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8624                       St->getPointerInfo(), St->isVolatile(),
8625                       St->isNonTemporal(), St->getAlignment(),
8626                       St->getAAInfo());
8627 }
8628
8629 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8630 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8631 /// i64 vector to have f64 elements, since the value can then be loaded
8632 /// directly into a VFP register.
8633 static bool hasNormalLoadOperand(SDNode *N) {
8634   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8635   for (unsigned i = 0; i < NumElts; ++i) {
8636     SDNode *Elt = N->getOperand(i).getNode();
8637     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8638       return true;
8639   }
8640   return false;
8641 }
8642
8643 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8644 /// ISD::BUILD_VECTOR.
8645 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8646                                           TargetLowering::DAGCombinerInfo &DCI){
8647   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8648   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8649   // into a pair of GPRs, which is fine when the value is used as a scalar,
8650   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8651   SelectionDAG &DAG = DCI.DAG;
8652   if (N->getNumOperands() == 2) {
8653     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8654     if (RV.getNode())
8655       return RV;
8656   }
8657
8658   // Load i64 elements as f64 values so that type legalization does not split
8659   // them up into i32 values.
8660   EVT VT = N->getValueType(0);
8661   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8662     return SDValue();
8663   SDLoc dl(N);
8664   SmallVector<SDValue, 8> Ops;
8665   unsigned NumElts = VT.getVectorNumElements();
8666   for (unsigned i = 0; i < NumElts; ++i) {
8667     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8668     Ops.push_back(V);
8669     // Make the DAGCombiner fold the bitcast.
8670     DCI.AddToWorklist(V.getNode());
8671   }
8672   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8673   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8674   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8675 }
8676
8677 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8678 static SDValue
8679 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8680   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8681   // At that time, we may have inserted bitcasts from integer to float.
8682   // If these bitcasts have survived DAGCombine, change the lowering of this
8683   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8684   // force to use floating point types.
8685
8686   // Make sure we can change the type of the vector.
8687   // This is possible iff:
8688   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8689   //    1.1. Vector is used only once.
8690   //    1.2. Use is a bit convert to an integer type.
8691   // 2. The size of its operands are 32-bits (64-bits are not legal).
8692   EVT VT = N->getValueType(0);
8693   EVT EltVT = VT.getVectorElementType();
8694
8695   // Check 1.1. and 2.
8696   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8697     return SDValue();
8698
8699   // By construction, the input type must be float.
8700   assert(EltVT == MVT::f32 && "Unexpected type!");
8701
8702   // Check 1.2.
8703   SDNode *Use = *N->use_begin();
8704   if (Use->getOpcode() != ISD::BITCAST ||
8705       Use->getValueType(0).isFloatingPoint())
8706     return SDValue();
8707
8708   // Check profitability.
8709   // Model is, if more than half of the relevant operands are bitcast from
8710   // i32, turn the build_vector into a sequence of insert_vector_elt.
8711   // Relevant operands are everything that is not statically
8712   // (i.e., at compile time) bitcasted.
8713   unsigned NumOfBitCastedElts = 0;
8714   unsigned NumElts = VT.getVectorNumElements();
8715   unsigned NumOfRelevantElts = NumElts;
8716   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8717     SDValue Elt = N->getOperand(Idx);
8718     if (Elt->getOpcode() == ISD::BITCAST) {
8719       // Assume only bit cast to i32 will go away.
8720       if (Elt->getOperand(0).getValueType() == MVT::i32)
8721         ++NumOfBitCastedElts;
8722     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8723       // Constants are statically casted, thus do not count them as
8724       // relevant operands.
8725       --NumOfRelevantElts;
8726   }
8727
8728   // Check if more than half of the elements require a non-free bitcast.
8729   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8730     return SDValue();
8731
8732   SelectionDAG &DAG = DCI.DAG;
8733   // Create the new vector type.
8734   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8735   // Check if the type is legal.
8736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8737   if (!TLI.isTypeLegal(VecVT))
8738     return SDValue();
8739
8740   // Combine:
8741   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8742   // => BITCAST INSERT_VECTOR_ELT
8743   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8744   //                      (BITCAST EN), N.
8745   SDValue Vec = DAG.getUNDEF(VecVT);
8746   SDLoc dl(N);
8747   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8748     SDValue V = N->getOperand(Idx);
8749     if (V.getOpcode() == ISD::UNDEF)
8750       continue;
8751     if (V.getOpcode() == ISD::BITCAST &&
8752         V->getOperand(0).getValueType() == MVT::i32)
8753       // Fold obvious case.
8754       V = V.getOperand(0);
8755     else {
8756       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8757       // Make the DAGCombiner fold the bitcasts.
8758       DCI.AddToWorklist(V.getNode());
8759     }
8760     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8761     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8762   }
8763   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8764   // Make the DAGCombiner fold the bitcasts.
8765   DCI.AddToWorklist(Vec.getNode());
8766   return Vec;
8767 }
8768
8769 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8770 /// ISD::INSERT_VECTOR_ELT.
8771 static SDValue PerformInsertEltCombine(SDNode *N,
8772                                        TargetLowering::DAGCombinerInfo &DCI) {
8773   // Bitcast an i64 load inserted into a vector to f64.
8774   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8775   EVT VT = N->getValueType(0);
8776   SDNode *Elt = N->getOperand(1).getNode();
8777   if (VT.getVectorElementType() != MVT::i64 ||
8778       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8779     return SDValue();
8780
8781   SelectionDAG &DAG = DCI.DAG;
8782   SDLoc dl(N);
8783   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8784                                  VT.getVectorNumElements());
8785   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8786   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8787   // Make the DAGCombiner fold the bitcasts.
8788   DCI.AddToWorklist(Vec.getNode());
8789   DCI.AddToWorklist(V.getNode());
8790   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8791                                Vec, V, N->getOperand(2));
8792   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8793 }
8794
8795 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8796 /// ISD::VECTOR_SHUFFLE.
8797 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8798   // The LLVM shufflevector instruction does not require the shuffle mask
8799   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8800   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8801   // operands do not match the mask length, they are extended by concatenating
8802   // them with undef vectors.  That is probably the right thing for other
8803   // targets, but for NEON it is better to concatenate two double-register
8804   // size vector operands into a single quad-register size vector.  Do that
8805   // transformation here:
8806   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8807   //   shuffle(concat(v1, v2), undef)
8808   SDValue Op0 = N->getOperand(0);
8809   SDValue Op1 = N->getOperand(1);
8810   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8811       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8812       Op0.getNumOperands() != 2 ||
8813       Op1.getNumOperands() != 2)
8814     return SDValue();
8815   SDValue Concat0Op1 = Op0.getOperand(1);
8816   SDValue Concat1Op1 = Op1.getOperand(1);
8817   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8818       Concat1Op1.getOpcode() != ISD::UNDEF)
8819     return SDValue();
8820   // Skip the transformation if any of the types are illegal.
8821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8822   EVT VT = N->getValueType(0);
8823   if (!TLI.isTypeLegal(VT) ||
8824       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8825       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8826     return SDValue();
8827
8828   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8829                                   Op0.getOperand(0), Op1.getOperand(0));
8830   // Translate the shuffle mask.
8831   SmallVector<int, 16> NewMask;
8832   unsigned NumElts = VT.getVectorNumElements();
8833   unsigned HalfElts = NumElts/2;
8834   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8835   for (unsigned n = 0; n < NumElts; ++n) {
8836     int MaskElt = SVN->getMaskElt(n);
8837     int NewElt = -1;
8838     if (MaskElt < (int)HalfElts)
8839       NewElt = MaskElt;
8840     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8841       NewElt = HalfElts + MaskElt - NumElts;
8842     NewMask.push_back(NewElt);
8843   }
8844   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8845                               DAG.getUNDEF(VT), NewMask.data());
8846 }
8847
8848 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8849 /// NEON load/store intrinsics to merge base address updates.
8850 static SDValue CombineBaseUpdate(SDNode *N,
8851                                  TargetLowering::DAGCombinerInfo &DCI) {
8852   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8853     return SDValue();
8854
8855   SelectionDAG &DAG = DCI.DAG;
8856   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8857                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8858   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8859   SDValue Addr = N->getOperand(AddrOpIdx);
8860
8861   // Search for a use of the address operand that is an increment.
8862   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8863          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8864     SDNode *User = *UI;
8865     if (User->getOpcode() != ISD::ADD ||
8866         UI.getUse().getResNo() != Addr.getResNo())
8867       continue;
8868
8869     // Check that the add is independent of the load/store.  Otherwise, folding
8870     // it would create a cycle.
8871     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8872       continue;
8873
8874     // Find the new opcode for the updating load/store.
8875     bool isLoad = true;
8876     bool isLaneOp = false;
8877     unsigned NewOpc = 0;
8878     unsigned NumVecs = 0;
8879     if (isIntrinsic) {
8880       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8881       switch (IntNo) {
8882       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8883       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8884         NumVecs = 1; break;
8885       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8886         NumVecs = 2; break;
8887       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8888         NumVecs = 3; break;
8889       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8890         NumVecs = 4; break;
8891       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8892         NumVecs = 2; isLaneOp = true; break;
8893       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8894         NumVecs = 3; isLaneOp = true; break;
8895       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8896         NumVecs = 4; isLaneOp = true; break;
8897       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8898         NumVecs = 1; isLoad = false; break;
8899       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8900         NumVecs = 2; isLoad = false; break;
8901       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8902         NumVecs = 3; isLoad = false; break;
8903       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8904         NumVecs = 4; isLoad = false; break;
8905       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8906         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8907       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8908         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8909       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8910         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8911       }
8912     } else {
8913       isLaneOp = true;
8914       switch (N->getOpcode()) {
8915       default: llvm_unreachable("unexpected opcode for Neon base update");
8916       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8917       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8918       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8919       }
8920     }
8921
8922     // Find the size of memory referenced by the load/store.
8923     EVT VecTy;
8924     if (isLoad)
8925       VecTy = N->getValueType(0);
8926     else
8927       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8928     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8929     if (isLaneOp)
8930       NumBytes /= VecTy.getVectorNumElements();
8931
8932     // If the increment is a constant, it must match the memory ref size.
8933     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8934     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8935       uint64_t IncVal = CInc->getZExtValue();
8936       if (IncVal != NumBytes)
8937         continue;
8938     } else if (NumBytes >= 3 * 16) {
8939       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8940       // separate instructions that make it harder to use a non-constant update.
8941       continue;
8942     }
8943
8944     // Create the new updating load/store node.
8945     EVT Tys[6];
8946     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8947     unsigned n;
8948     for (n = 0; n < NumResultVecs; ++n)
8949       Tys[n] = VecTy;
8950     Tys[n++] = MVT::i32;
8951     Tys[n] = MVT::Other;
8952     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8953     SmallVector<SDValue, 8> Ops;
8954     Ops.push_back(N->getOperand(0)); // incoming chain
8955     Ops.push_back(N->getOperand(AddrOpIdx));
8956     Ops.push_back(Inc);
8957     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8958       Ops.push_back(N->getOperand(i));
8959     }
8960     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8961     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8962                                            Ops, MemInt->getMemoryVT(),
8963                                            MemInt->getMemOperand());
8964
8965     // Update the uses.
8966     std::vector<SDValue> NewResults;
8967     for (unsigned i = 0; i < NumResultVecs; ++i) {
8968       NewResults.push_back(SDValue(UpdN.getNode(), i));
8969     }
8970     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8971     DCI.CombineTo(N, NewResults);
8972     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8973
8974     break;
8975   }
8976   return SDValue();
8977 }
8978
8979 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8980 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8981 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8982 /// return true.
8983 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8984   SelectionDAG &DAG = DCI.DAG;
8985   EVT VT = N->getValueType(0);
8986   // vldN-dup instructions only support 64-bit vectors for N > 1.
8987   if (!VT.is64BitVector())
8988     return false;
8989
8990   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8991   SDNode *VLD = N->getOperand(0).getNode();
8992   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8993     return false;
8994   unsigned NumVecs = 0;
8995   unsigned NewOpc = 0;
8996   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8997   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8998     NumVecs = 2;
8999     NewOpc = ARMISD::VLD2DUP;
9000   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9001     NumVecs = 3;
9002     NewOpc = ARMISD::VLD3DUP;
9003   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9004     NumVecs = 4;
9005     NewOpc = ARMISD::VLD4DUP;
9006   } else {
9007     return false;
9008   }
9009
9010   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9011   // numbers match the load.
9012   unsigned VLDLaneNo =
9013     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9014   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9015        UI != UE; ++UI) {
9016     // Ignore uses of the chain result.
9017     if (UI.getUse().getResNo() == NumVecs)
9018       continue;
9019     SDNode *User = *UI;
9020     if (User->getOpcode() != ARMISD::VDUPLANE ||
9021         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9022       return false;
9023   }
9024
9025   // Create the vldN-dup node.
9026   EVT Tys[5];
9027   unsigned n;
9028   for (n = 0; n < NumVecs; ++n)
9029     Tys[n] = VT;
9030   Tys[n] = MVT::Other;
9031   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9032   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9033   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9034   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9035                                            Ops, VLDMemInt->getMemoryVT(),
9036                                            VLDMemInt->getMemOperand());
9037
9038   // Update the uses.
9039   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9040        UI != UE; ++UI) {
9041     unsigned ResNo = UI.getUse().getResNo();
9042     // Ignore uses of the chain result.
9043     if (ResNo == NumVecs)
9044       continue;
9045     SDNode *User = *UI;
9046     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9047   }
9048
9049   // Now the vldN-lane intrinsic is dead except for its chain result.
9050   // Update uses of the chain.
9051   std::vector<SDValue> VLDDupResults;
9052   for (unsigned n = 0; n < NumVecs; ++n)
9053     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9054   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9055   DCI.CombineTo(VLD, VLDDupResults);
9056
9057   return true;
9058 }
9059
9060 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9061 /// ARMISD::VDUPLANE.
9062 static SDValue PerformVDUPLANECombine(SDNode *N,
9063                                       TargetLowering::DAGCombinerInfo &DCI) {
9064   SDValue Op = N->getOperand(0);
9065
9066   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9067   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9068   if (CombineVLDDUP(N, DCI))
9069     return SDValue(N, 0);
9070
9071   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9072   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9073   while (Op.getOpcode() == ISD::BITCAST)
9074     Op = Op.getOperand(0);
9075   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9076     return SDValue();
9077
9078   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9079   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9080   // The canonical VMOV for a zero vector uses a 32-bit element size.
9081   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9082   unsigned EltBits;
9083   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9084     EltSize = 8;
9085   EVT VT = N->getValueType(0);
9086   if (EltSize > VT.getVectorElementType().getSizeInBits())
9087     return SDValue();
9088
9089   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9090 }
9091
9092 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9093 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9094 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9095 {
9096   integerPart cN;
9097   integerPart c0 = 0;
9098   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9099        I != E; I++) {
9100     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9101     if (!C)
9102       return false;
9103
9104     bool isExact;
9105     APFloat APF = C->getValueAPF();
9106     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9107         != APFloat::opOK || !isExact)
9108       return false;
9109
9110     c0 = (I == 0) ? cN : c0;
9111     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9112       return false;
9113   }
9114   C = c0;
9115   return true;
9116 }
9117
9118 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9119 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9120 /// when the VMUL has a constant operand that is a power of 2.
9121 ///
9122 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9123 ///  vmul.f32        d16, d17, d16
9124 ///  vcvt.s32.f32    d16, d16
9125 /// becomes:
9126 ///  vcvt.s32.f32    d16, d16, #3
9127 static SDValue PerformVCVTCombine(SDNode *N,
9128                                   TargetLowering::DAGCombinerInfo &DCI,
9129                                   const ARMSubtarget *Subtarget) {
9130   SelectionDAG &DAG = DCI.DAG;
9131   SDValue Op = N->getOperand(0);
9132
9133   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9134       Op.getOpcode() != ISD::FMUL)
9135     return SDValue();
9136
9137   uint64_t C;
9138   SDValue N0 = Op->getOperand(0);
9139   SDValue ConstVec = Op->getOperand(1);
9140   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9141
9142   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9143       !isConstVecPow2(ConstVec, isSigned, C))
9144     return SDValue();
9145
9146   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9147   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9148   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9149     // These instructions only exist converting from f32 to i32. We can handle
9150     // smaller integers by generating an extra truncate, but larger ones would
9151     // be lossy.
9152     return SDValue();
9153   }
9154
9155   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9156     Intrinsic::arm_neon_vcvtfp2fxu;
9157   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9158   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9159                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9160                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9161                                  DAG.getConstant(Log2_64(C), MVT::i32));
9162
9163   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9164     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9165
9166   return FixConv;
9167 }
9168
9169 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9170 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9171 /// when the VDIV has a constant operand that is a power of 2.
9172 ///
9173 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9174 ///  vcvt.f32.s32    d16, d16
9175 ///  vdiv.f32        d16, d17, d16
9176 /// becomes:
9177 ///  vcvt.f32.s32    d16, d16, #3
9178 static SDValue PerformVDIVCombine(SDNode *N,
9179                                   TargetLowering::DAGCombinerInfo &DCI,
9180                                   const ARMSubtarget *Subtarget) {
9181   SelectionDAG &DAG = DCI.DAG;
9182   SDValue Op = N->getOperand(0);
9183   unsigned OpOpcode = Op.getNode()->getOpcode();
9184
9185   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9186       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9187     return SDValue();
9188
9189   uint64_t C;
9190   SDValue ConstVec = N->getOperand(1);
9191   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9192
9193   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9194       !isConstVecPow2(ConstVec, isSigned, C))
9195     return SDValue();
9196
9197   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9198   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9199   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9200     // These instructions only exist converting from i32 to f32. We can handle
9201     // smaller integers by generating an extra extend, but larger ones would
9202     // be lossy.
9203     return SDValue();
9204   }
9205
9206   SDValue ConvInput = Op.getOperand(0);
9207   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9208   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9209     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9210                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9211                             ConvInput);
9212
9213   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9214     Intrinsic::arm_neon_vcvtfxu2fp;
9215   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9216                      Op.getValueType(),
9217                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9218                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9219 }
9220
9221 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9222 /// operand of a vector shift operation, where all the elements of the
9223 /// build_vector must have the same constant integer value.
9224 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9225   // Ignore bit_converts.
9226   while (Op.getOpcode() == ISD::BITCAST)
9227     Op = Op.getOperand(0);
9228   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9229   APInt SplatBits, SplatUndef;
9230   unsigned SplatBitSize;
9231   bool HasAnyUndefs;
9232   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9233                                       HasAnyUndefs, ElementBits) ||
9234       SplatBitSize > ElementBits)
9235     return false;
9236   Cnt = SplatBits.getSExtValue();
9237   return true;
9238 }
9239
9240 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9241 /// operand of a vector shift left operation.  That value must be in the range:
9242 ///   0 <= Value < ElementBits for a left shift; or
9243 ///   0 <= Value <= ElementBits for a long left shift.
9244 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9245   assert(VT.isVector() && "vector shift count is not a vector type");
9246   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9247   if (! getVShiftImm(Op, ElementBits, Cnt))
9248     return false;
9249   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9250 }
9251
9252 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9253 /// operand of a vector shift right operation.  For a shift opcode, the value
9254 /// is positive, but for an intrinsic the value count must be negative. The
9255 /// absolute value must be in the range:
9256 ///   1 <= |Value| <= ElementBits for a right shift; or
9257 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9258 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9259                          int64_t &Cnt) {
9260   assert(VT.isVector() && "vector shift count is not a vector type");
9261   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9262   if (! getVShiftImm(Op, ElementBits, Cnt))
9263     return false;
9264   if (isIntrinsic)
9265     Cnt = -Cnt;
9266   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9267 }
9268
9269 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9270 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9271   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9272   switch (IntNo) {
9273   default:
9274     // Don't do anything for most intrinsics.
9275     break;
9276
9277   // Vector shifts: check for immediate versions and lower them.
9278   // Note: This is done during DAG combining instead of DAG legalizing because
9279   // the build_vectors for 64-bit vector element shift counts are generally
9280   // not legal, and it is hard to see their values after they get legalized to
9281   // loads from a constant pool.
9282   case Intrinsic::arm_neon_vshifts:
9283   case Intrinsic::arm_neon_vshiftu:
9284   case Intrinsic::arm_neon_vrshifts:
9285   case Intrinsic::arm_neon_vrshiftu:
9286   case Intrinsic::arm_neon_vrshiftn:
9287   case Intrinsic::arm_neon_vqshifts:
9288   case Intrinsic::arm_neon_vqshiftu:
9289   case Intrinsic::arm_neon_vqshiftsu:
9290   case Intrinsic::arm_neon_vqshiftns:
9291   case Intrinsic::arm_neon_vqshiftnu:
9292   case Intrinsic::arm_neon_vqshiftnsu:
9293   case Intrinsic::arm_neon_vqrshiftns:
9294   case Intrinsic::arm_neon_vqrshiftnu:
9295   case Intrinsic::arm_neon_vqrshiftnsu: {
9296     EVT VT = N->getOperand(1).getValueType();
9297     int64_t Cnt;
9298     unsigned VShiftOpc = 0;
9299
9300     switch (IntNo) {
9301     case Intrinsic::arm_neon_vshifts:
9302     case Intrinsic::arm_neon_vshiftu:
9303       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9304         VShiftOpc = ARMISD::VSHL;
9305         break;
9306       }
9307       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9308         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9309                      ARMISD::VSHRs : ARMISD::VSHRu);
9310         break;
9311       }
9312       return SDValue();
9313
9314     case Intrinsic::arm_neon_vrshifts:
9315     case Intrinsic::arm_neon_vrshiftu:
9316       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9317         break;
9318       return SDValue();
9319
9320     case Intrinsic::arm_neon_vqshifts:
9321     case Intrinsic::arm_neon_vqshiftu:
9322       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9323         break;
9324       return SDValue();
9325
9326     case Intrinsic::arm_neon_vqshiftsu:
9327       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9328         break;
9329       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9330
9331     case Intrinsic::arm_neon_vrshiftn:
9332     case Intrinsic::arm_neon_vqshiftns:
9333     case Intrinsic::arm_neon_vqshiftnu:
9334     case Intrinsic::arm_neon_vqshiftnsu:
9335     case Intrinsic::arm_neon_vqrshiftns:
9336     case Intrinsic::arm_neon_vqrshiftnu:
9337     case Intrinsic::arm_neon_vqrshiftnsu:
9338       // Narrowing shifts require an immediate right shift.
9339       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9340         break;
9341       llvm_unreachable("invalid shift count for narrowing vector shift "
9342                        "intrinsic");
9343
9344     default:
9345       llvm_unreachable("unhandled vector shift");
9346     }
9347
9348     switch (IntNo) {
9349     case Intrinsic::arm_neon_vshifts:
9350     case Intrinsic::arm_neon_vshiftu:
9351       // Opcode already set above.
9352       break;
9353     case Intrinsic::arm_neon_vrshifts:
9354       VShiftOpc = ARMISD::VRSHRs; break;
9355     case Intrinsic::arm_neon_vrshiftu:
9356       VShiftOpc = ARMISD::VRSHRu; break;
9357     case Intrinsic::arm_neon_vrshiftn:
9358       VShiftOpc = ARMISD::VRSHRN; break;
9359     case Intrinsic::arm_neon_vqshifts:
9360       VShiftOpc = ARMISD::VQSHLs; break;
9361     case Intrinsic::arm_neon_vqshiftu:
9362       VShiftOpc = ARMISD::VQSHLu; break;
9363     case Intrinsic::arm_neon_vqshiftsu:
9364       VShiftOpc = ARMISD::VQSHLsu; break;
9365     case Intrinsic::arm_neon_vqshiftns:
9366       VShiftOpc = ARMISD::VQSHRNs; break;
9367     case Intrinsic::arm_neon_vqshiftnu:
9368       VShiftOpc = ARMISD::VQSHRNu; break;
9369     case Intrinsic::arm_neon_vqshiftnsu:
9370       VShiftOpc = ARMISD::VQSHRNsu; break;
9371     case Intrinsic::arm_neon_vqrshiftns:
9372       VShiftOpc = ARMISD::VQRSHRNs; break;
9373     case Intrinsic::arm_neon_vqrshiftnu:
9374       VShiftOpc = ARMISD::VQRSHRNu; break;
9375     case Intrinsic::arm_neon_vqrshiftnsu:
9376       VShiftOpc = ARMISD::VQRSHRNsu; break;
9377     }
9378
9379     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9380                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9381   }
9382
9383   case Intrinsic::arm_neon_vshiftins: {
9384     EVT VT = N->getOperand(1).getValueType();
9385     int64_t Cnt;
9386     unsigned VShiftOpc = 0;
9387
9388     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9389       VShiftOpc = ARMISD::VSLI;
9390     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9391       VShiftOpc = ARMISD::VSRI;
9392     else {
9393       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9394     }
9395
9396     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9397                        N->getOperand(1), N->getOperand(2),
9398                        DAG.getConstant(Cnt, MVT::i32));
9399   }
9400
9401   case Intrinsic::arm_neon_vqrshifts:
9402   case Intrinsic::arm_neon_vqrshiftu:
9403     // No immediate versions of these to check for.
9404     break;
9405   }
9406
9407   return SDValue();
9408 }
9409
9410 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9411 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9412 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9413 /// vector element shift counts are generally not legal, and it is hard to see
9414 /// their values after they get legalized to loads from a constant pool.
9415 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9416                                    const ARMSubtarget *ST) {
9417   EVT VT = N->getValueType(0);
9418   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9419     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9420     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9421     SDValue N1 = N->getOperand(1);
9422     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9423       SDValue N0 = N->getOperand(0);
9424       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9425           DAG.MaskedValueIsZero(N0.getOperand(0),
9426                                 APInt::getHighBitsSet(32, 16)))
9427         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9428     }
9429   }
9430
9431   // Nothing to be done for scalar shifts.
9432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9433   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9434     return SDValue();
9435
9436   assert(ST->hasNEON() && "unexpected vector shift");
9437   int64_t Cnt;
9438
9439   switch (N->getOpcode()) {
9440   default: llvm_unreachable("unexpected shift opcode");
9441
9442   case ISD::SHL:
9443     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9444       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9445                          DAG.getConstant(Cnt, MVT::i32));
9446     break;
9447
9448   case ISD::SRA:
9449   case ISD::SRL:
9450     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9451       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9452                             ARMISD::VSHRs : ARMISD::VSHRu);
9453       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9454                          DAG.getConstant(Cnt, MVT::i32));
9455     }
9456   }
9457   return SDValue();
9458 }
9459
9460 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9461 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9462 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9463                                     const ARMSubtarget *ST) {
9464   SDValue N0 = N->getOperand(0);
9465
9466   // Check for sign- and zero-extensions of vector extract operations of 8-
9467   // and 16-bit vector elements.  NEON supports these directly.  They are
9468   // handled during DAG combining because type legalization will promote them
9469   // to 32-bit types and it is messy to recognize the operations after that.
9470   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9471     SDValue Vec = N0.getOperand(0);
9472     SDValue Lane = N0.getOperand(1);
9473     EVT VT = N->getValueType(0);
9474     EVT EltVT = N0.getValueType();
9475     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9476
9477     if (VT == MVT::i32 &&
9478         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9479         TLI.isTypeLegal(Vec.getValueType()) &&
9480         isa<ConstantSDNode>(Lane)) {
9481
9482       unsigned Opc = 0;
9483       switch (N->getOpcode()) {
9484       default: llvm_unreachable("unexpected opcode");
9485       case ISD::SIGN_EXTEND:
9486         Opc = ARMISD::VGETLANEs;
9487         break;
9488       case ISD::ZERO_EXTEND:
9489       case ISD::ANY_EXTEND:
9490         Opc = ARMISD::VGETLANEu;
9491         break;
9492       }
9493       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9494     }
9495   }
9496
9497   return SDValue();
9498 }
9499
9500 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9501 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9502 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9503                                        const ARMSubtarget *ST) {
9504   // If the target supports NEON, try to use vmax/vmin instructions for f32
9505   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9506   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9507   // a NaN; only do the transformation when it matches that behavior.
9508
9509   // For now only do this when using NEON for FP operations; if using VFP, it
9510   // is not obvious that the benefit outweighs the cost of switching to the
9511   // NEON pipeline.
9512   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9513       N->getValueType(0) != MVT::f32)
9514     return SDValue();
9515
9516   SDValue CondLHS = N->getOperand(0);
9517   SDValue CondRHS = N->getOperand(1);
9518   SDValue LHS = N->getOperand(2);
9519   SDValue RHS = N->getOperand(3);
9520   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9521
9522   unsigned Opcode = 0;
9523   bool IsReversed;
9524   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9525     IsReversed = false; // x CC y ? x : y
9526   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9527     IsReversed = true ; // x CC y ? y : x
9528   } else {
9529     return SDValue();
9530   }
9531
9532   bool IsUnordered;
9533   switch (CC) {
9534   default: break;
9535   case ISD::SETOLT:
9536   case ISD::SETOLE:
9537   case ISD::SETLT:
9538   case ISD::SETLE:
9539   case ISD::SETULT:
9540   case ISD::SETULE:
9541     // If LHS is NaN, an ordered comparison will be false and the result will
9542     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9543     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9544     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9545     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9546       break;
9547     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9548     // will return -0, so vmin can only be used for unsafe math or if one of
9549     // the operands is known to be nonzero.
9550     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9551         !DAG.getTarget().Options.UnsafeFPMath &&
9552         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9553       break;
9554     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9555     break;
9556
9557   case ISD::SETOGT:
9558   case ISD::SETOGE:
9559   case ISD::SETGT:
9560   case ISD::SETGE:
9561   case ISD::SETUGT:
9562   case ISD::SETUGE:
9563     // If LHS is NaN, an ordered comparison will be false and the result will
9564     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9565     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9566     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9567     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9568       break;
9569     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9570     // will return +0, so vmax can only be used for unsafe math or if one of
9571     // the operands is known to be nonzero.
9572     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9573         !DAG.getTarget().Options.UnsafeFPMath &&
9574         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9575       break;
9576     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9577     break;
9578   }
9579
9580   if (!Opcode)
9581     return SDValue();
9582   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9583 }
9584
9585 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9586 SDValue
9587 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9588   SDValue Cmp = N->getOperand(4);
9589   if (Cmp.getOpcode() != ARMISD::CMPZ)
9590     // Only looking at EQ and NE cases.
9591     return SDValue();
9592
9593   EVT VT = N->getValueType(0);
9594   SDLoc dl(N);
9595   SDValue LHS = Cmp.getOperand(0);
9596   SDValue RHS = Cmp.getOperand(1);
9597   SDValue FalseVal = N->getOperand(0);
9598   SDValue TrueVal = N->getOperand(1);
9599   SDValue ARMcc = N->getOperand(2);
9600   ARMCC::CondCodes CC =
9601     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9602
9603   // Simplify
9604   //   mov     r1, r0
9605   //   cmp     r1, x
9606   //   mov     r0, y
9607   //   moveq   r0, x
9608   // to
9609   //   cmp     r0, x
9610   //   movne   r0, y
9611   //
9612   //   mov     r1, r0
9613   //   cmp     r1, x
9614   //   mov     r0, x
9615   //   movne   r0, y
9616   // to
9617   //   cmp     r0, x
9618   //   movne   r0, y
9619   /// FIXME: Turn this into a target neutral optimization?
9620   SDValue Res;
9621   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9622     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9623                       N->getOperand(3), Cmp);
9624   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9625     SDValue ARMcc;
9626     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9627     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9628                       N->getOperand(3), NewCmp);
9629   }
9630
9631   if (Res.getNode()) {
9632     APInt KnownZero, KnownOne;
9633     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9634     // Capture demanded bits information that would be otherwise lost.
9635     if (KnownZero == 0xfffffffe)
9636       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9637                         DAG.getValueType(MVT::i1));
9638     else if (KnownZero == 0xffffff00)
9639       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9640                         DAG.getValueType(MVT::i8));
9641     else if (KnownZero == 0xffff0000)
9642       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9643                         DAG.getValueType(MVT::i16));
9644   }
9645
9646   return Res;
9647 }
9648
9649 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9650                                              DAGCombinerInfo &DCI) const {
9651   switch (N->getOpcode()) {
9652   default: break;
9653   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9654   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9655   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9656   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9657   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9658   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9659   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9660   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9661   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9662   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9663   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9664   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9665   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9666   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9667   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9668   case ISD::FP_TO_SINT:
9669   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9670   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9671   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9672   case ISD::SHL:
9673   case ISD::SRA:
9674   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9675   case ISD::SIGN_EXTEND:
9676   case ISD::ZERO_EXTEND:
9677   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9678   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9679   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9680   case ARMISD::VLD2DUP:
9681   case ARMISD::VLD3DUP:
9682   case ARMISD::VLD4DUP:
9683     return CombineBaseUpdate(N, DCI);
9684   case ARMISD::BUILD_VECTOR:
9685     return PerformARMBUILD_VECTORCombine(N, DCI);
9686   case ISD::INTRINSIC_VOID:
9687   case ISD::INTRINSIC_W_CHAIN:
9688     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9689     case Intrinsic::arm_neon_vld1:
9690     case Intrinsic::arm_neon_vld2:
9691     case Intrinsic::arm_neon_vld3:
9692     case Intrinsic::arm_neon_vld4:
9693     case Intrinsic::arm_neon_vld2lane:
9694     case Intrinsic::arm_neon_vld3lane:
9695     case Intrinsic::arm_neon_vld4lane:
9696     case Intrinsic::arm_neon_vst1:
9697     case Intrinsic::arm_neon_vst2:
9698     case Intrinsic::arm_neon_vst3:
9699     case Intrinsic::arm_neon_vst4:
9700     case Intrinsic::arm_neon_vst2lane:
9701     case Intrinsic::arm_neon_vst3lane:
9702     case Intrinsic::arm_neon_vst4lane:
9703       return CombineBaseUpdate(N, DCI);
9704     default: break;
9705     }
9706     break;
9707   }
9708   return SDValue();
9709 }
9710
9711 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9712                                                           EVT VT) const {
9713   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9714 }
9715
9716 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9717                                                        unsigned,
9718                                                        unsigned,
9719                                                        bool *Fast) const {
9720   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9721   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9722
9723   switch (VT.getSimpleVT().SimpleTy) {
9724   default:
9725     return false;
9726   case MVT::i8:
9727   case MVT::i16:
9728   case MVT::i32: {
9729     // Unaligned access can use (for example) LRDB, LRDH, LDR
9730     if (AllowsUnaligned) {
9731       if (Fast)
9732         *Fast = Subtarget->hasV7Ops();
9733       return true;
9734     }
9735     return false;
9736   }
9737   case MVT::f64:
9738   case MVT::v2f64: {
9739     // For any little-endian targets with neon, we can support unaligned ld/st
9740     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9741     // A big-endian target may also explicitly support unaligned accesses
9742     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9743       if (Fast)
9744         *Fast = true;
9745       return true;
9746     }
9747     return false;
9748   }
9749   }
9750 }
9751
9752 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9753                        unsigned AlignCheck) {
9754   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9755           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9756 }
9757
9758 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9759                                            unsigned DstAlign, unsigned SrcAlign,
9760                                            bool IsMemset, bool ZeroMemset,
9761                                            bool MemcpyStrSrc,
9762                                            MachineFunction &MF) const {
9763   const Function *F = MF.getFunction();
9764
9765   // See if we can use NEON instructions for this...
9766   if ((!IsMemset || ZeroMemset) &&
9767       Subtarget->hasNEON() &&
9768       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9769                                        Attribute::NoImplicitFloat)) {
9770     bool Fast;
9771     if (Size >= 16 &&
9772         (memOpAlign(SrcAlign, DstAlign, 16) ||
9773          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9774       return MVT::v2f64;
9775     } else if (Size >= 8 &&
9776                (memOpAlign(SrcAlign, DstAlign, 8) ||
9777                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9778                  Fast))) {
9779       return MVT::f64;
9780     }
9781   }
9782
9783   // Lowering to i32/i16 if the size permits.
9784   if (Size >= 4)
9785     return MVT::i32;
9786   else if (Size >= 2)
9787     return MVT::i16;
9788
9789   // Let the target-independent logic figure it out.
9790   return MVT::Other;
9791 }
9792
9793 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9794   if (Val.getOpcode() != ISD::LOAD)
9795     return false;
9796
9797   EVT VT1 = Val.getValueType();
9798   if (!VT1.isSimple() || !VT1.isInteger() ||
9799       !VT2.isSimple() || !VT2.isInteger())
9800     return false;
9801
9802   switch (VT1.getSimpleVT().SimpleTy) {
9803   default: break;
9804   case MVT::i1:
9805   case MVT::i8:
9806   case MVT::i16:
9807     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9808     return true;
9809   }
9810
9811   return false;
9812 }
9813
9814 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9815   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9816     return false;
9817
9818   if (!isTypeLegal(EVT::getEVT(Ty1)))
9819     return false;
9820
9821   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9822
9823   // Assuming the caller doesn't have a zeroext or signext return parameter,
9824   // truncation all the way down to i1 is valid.
9825   return true;
9826 }
9827
9828
9829 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9830   if (V < 0)
9831     return false;
9832
9833   unsigned Scale = 1;
9834   switch (VT.getSimpleVT().SimpleTy) {
9835   default: return false;
9836   case MVT::i1:
9837   case MVT::i8:
9838     // Scale == 1;
9839     break;
9840   case MVT::i16:
9841     // Scale == 2;
9842     Scale = 2;
9843     break;
9844   case MVT::i32:
9845     // Scale == 4;
9846     Scale = 4;
9847     break;
9848   }
9849
9850   if ((V & (Scale - 1)) != 0)
9851     return false;
9852   V /= Scale;
9853   return V == (V & ((1LL << 5) - 1));
9854 }
9855
9856 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9857                                       const ARMSubtarget *Subtarget) {
9858   bool isNeg = false;
9859   if (V < 0) {
9860     isNeg = true;
9861     V = - V;
9862   }
9863
9864   switch (VT.getSimpleVT().SimpleTy) {
9865   default: return false;
9866   case MVT::i1:
9867   case MVT::i8:
9868   case MVT::i16:
9869   case MVT::i32:
9870     // + imm12 or - imm8
9871     if (isNeg)
9872       return V == (V & ((1LL << 8) - 1));
9873     return V == (V & ((1LL << 12) - 1));
9874   case MVT::f32:
9875   case MVT::f64:
9876     // Same as ARM mode. FIXME: NEON?
9877     if (!Subtarget->hasVFP2())
9878       return false;
9879     if ((V & 3) != 0)
9880       return false;
9881     V >>= 2;
9882     return V == (V & ((1LL << 8) - 1));
9883   }
9884 }
9885
9886 /// isLegalAddressImmediate - Return true if the integer value can be used
9887 /// as the offset of the target addressing mode for load / store of the
9888 /// given type.
9889 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9890                                     const ARMSubtarget *Subtarget) {
9891   if (V == 0)
9892     return true;
9893
9894   if (!VT.isSimple())
9895     return false;
9896
9897   if (Subtarget->isThumb1Only())
9898     return isLegalT1AddressImmediate(V, VT);
9899   else if (Subtarget->isThumb2())
9900     return isLegalT2AddressImmediate(V, VT, Subtarget);
9901
9902   // ARM mode.
9903   if (V < 0)
9904     V = - V;
9905   switch (VT.getSimpleVT().SimpleTy) {
9906   default: return false;
9907   case MVT::i1:
9908   case MVT::i8:
9909   case MVT::i32:
9910     // +- imm12
9911     return V == (V & ((1LL << 12) - 1));
9912   case MVT::i16:
9913     // +- imm8
9914     return V == (V & ((1LL << 8) - 1));
9915   case MVT::f32:
9916   case MVT::f64:
9917     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9918       return false;
9919     if ((V & 3) != 0)
9920       return false;
9921     V >>= 2;
9922     return V == (V & ((1LL << 8) - 1));
9923   }
9924 }
9925
9926 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9927                                                       EVT VT) const {
9928   int Scale = AM.Scale;
9929   if (Scale < 0)
9930     return false;
9931
9932   switch (VT.getSimpleVT().SimpleTy) {
9933   default: return false;
9934   case MVT::i1:
9935   case MVT::i8:
9936   case MVT::i16:
9937   case MVT::i32:
9938     if (Scale == 1)
9939       return true;
9940     // r + r << imm
9941     Scale = Scale & ~1;
9942     return Scale == 2 || Scale == 4 || Scale == 8;
9943   case MVT::i64:
9944     // r + r
9945     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9946       return true;
9947     return false;
9948   case MVT::isVoid:
9949     // Note, we allow "void" uses (basically, uses that aren't loads or
9950     // stores), because arm allows folding a scale into many arithmetic
9951     // operations.  This should be made more precise and revisited later.
9952
9953     // Allow r << imm, but the imm has to be a multiple of two.
9954     if (Scale & 1) return false;
9955     return isPowerOf2_32(Scale);
9956   }
9957 }
9958
9959 /// isLegalAddressingMode - Return true if the addressing mode represented
9960 /// by AM is legal for this target, for a load/store of the specified type.
9961 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9962                                               Type *Ty) const {
9963   EVT VT = getValueType(Ty, true);
9964   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9965     return false;
9966
9967   // Can never fold addr of global into load/store.
9968   if (AM.BaseGV)
9969     return false;
9970
9971   switch (AM.Scale) {
9972   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9973     break;
9974   case 1:
9975     if (Subtarget->isThumb1Only())
9976       return false;
9977     // FALL THROUGH.
9978   default:
9979     // ARM doesn't support any R+R*scale+imm addr modes.
9980     if (AM.BaseOffs)
9981       return false;
9982
9983     if (!VT.isSimple())
9984       return false;
9985
9986     if (Subtarget->isThumb2())
9987       return isLegalT2ScaledAddressingMode(AM, VT);
9988
9989     int Scale = AM.Scale;
9990     switch (VT.getSimpleVT().SimpleTy) {
9991     default: return false;
9992     case MVT::i1:
9993     case MVT::i8:
9994     case MVT::i32:
9995       if (Scale < 0) Scale = -Scale;
9996       if (Scale == 1)
9997         return true;
9998       // r + r << imm
9999       return isPowerOf2_32(Scale & ~1);
10000     case MVT::i16:
10001     case MVT::i64:
10002       // r + r
10003       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10004         return true;
10005       return false;
10006
10007     case MVT::isVoid:
10008       // Note, we allow "void" uses (basically, uses that aren't loads or
10009       // stores), because arm allows folding a scale into many arithmetic
10010       // operations.  This should be made more precise and revisited later.
10011
10012       // Allow r << imm, but the imm has to be a multiple of two.
10013       if (Scale & 1) return false;
10014       return isPowerOf2_32(Scale);
10015     }
10016   }
10017   return true;
10018 }
10019
10020 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10021 /// icmp immediate, that is the target has icmp instructions which can compare
10022 /// a register against the immediate without having to materialize the
10023 /// immediate into a register.
10024 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10025   // Thumb2 and ARM modes can use cmn for negative immediates.
10026   if (!Subtarget->isThumb())
10027     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10028   if (Subtarget->isThumb2())
10029     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10030   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10031   return Imm >= 0 && Imm <= 255;
10032 }
10033
10034 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10035 /// *or sub* immediate, that is the target has add or sub instructions which can
10036 /// add a register with the immediate without having to materialize the
10037 /// immediate into a register.
10038 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10039   // Same encoding for add/sub, just flip the sign.
10040   int64_t AbsImm = llvm::abs64(Imm);
10041   if (!Subtarget->isThumb())
10042     return ARM_AM::getSOImmVal(AbsImm) != -1;
10043   if (Subtarget->isThumb2())
10044     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10045   // Thumb1 only has 8-bit unsigned immediate.
10046   return AbsImm >= 0 && AbsImm <= 255;
10047 }
10048
10049 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10050                                       bool isSEXTLoad, SDValue &Base,
10051                                       SDValue &Offset, bool &isInc,
10052                                       SelectionDAG &DAG) {
10053   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10054     return false;
10055
10056   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10057     // AddressingMode 3
10058     Base = Ptr->getOperand(0);
10059     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10060       int RHSC = (int)RHS->getZExtValue();
10061       if (RHSC < 0 && RHSC > -256) {
10062         assert(Ptr->getOpcode() == ISD::ADD);
10063         isInc = false;
10064         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10065         return true;
10066       }
10067     }
10068     isInc = (Ptr->getOpcode() == ISD::ADD);
10069     Offset = Ptr->getOperand(1);
10070     return true;
10071   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10072     // AddressingMode 2
10073     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10074       int RHSC = (int)RHS->getZExtValue();
10075       if (RHSC < 0 && RHSC > -0x1000) {
10076         assert(Ptr->getOpcode() == ISD::ADD);
10077         isInc = false;
10078         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10079         Base = Ptr->getOperand(0);
10080         return true;
10081       }
10082     }
10083
10084     if (Ptr->getOpcode() == ISD::ADD) {
10085       isInc = true;
10086       ARM_AM::ShiftOpc ShOpcVal=
10087         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10088       if (ShOpcVal != ARM_AM::no_shift) {
10089         Base = Ptr->getOperand(1);
10090         Offset = Ptr->getOperand(0);
10091       } else {
10092         Base = Ptr->getOperand(0);
10093         Offset = Ptr->getOperand(1);
10094       }
10095       return true;
10096     }
10097
10098     isInc = (Ptr->getOpcode() == ISD::ADD);
10099     Base = Ptr->getOperand(0);
10100     Offset = Ptr->getOperand(1);
10101     return true;
10102   }
10103
10104   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10105   return false;
10106 }
10107
10108 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10109                                      bool isSEXTLoad, SDValue &Base,
10110                                      SDValue &Offset, bool &isInc,
10111                                      SelectionDAG &DAG) {
10112   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10113     return false;
10114
10115   Base = Ptr->getOperand(0);
10116   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10117     int RHSC = (int)RHS->getZExtValue();
10118     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10119       assert(Ptr->getOpcode() == ISD::ADD);
10120       isInc = false;
10121       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10122       return true;
10123     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10124       isInc = Ptr->getOpcode() == ISD::ADD;
10125       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10126       return true;
10127     }
10128   }
10129
10130   return false;
10131 }
10132
10133 /// getPreIndexedAddressParts - returns true by value, base pointer and
10134 /// offset pointer and addressing mode by reference if the node's address
10135 /// can be legally represented as pre-indexed load / store address.
10136 bool
10137 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10138                                              SDValue &Offset,
10139                                              ISD::MemIndexedMode &AM,
10140                                              SelectionDAG &DAG) const {
10141   if (Subtarget->isThumb1Only())
10142     return false;
10143
10144   EVT VT;
10145   SDValue Ptr;
10146   bool isSEXTLoad = false;
10147   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10148     Ptr = LD->getBasePtr();
10149     VT  = LD->getMemoryVT();
10150     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10151   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10152     Ptr = ST->getBasePtr();
10153     VT  = ST->getMemoryVT();
10154   } else
10155     return false;
10156
10157   bool isInc;
10158   bool isLegal = false;
10159   if (Subtarget->isThumb2())
10160     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10161                                        Offset, isInc, DAG);
10162   else
10163     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10164                                         Offset, isInc, DAG);
10165   if (!isLegal)
10166     return false;
10167
10168   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10169   return true;
10170 }
10171
10172 /// getPostIndexedAddressParts - returns true by value, base pointer and
10173 /// offset pointer and addressing mode by reference if this node can be
10174 /// combined with a load / store to form a post-indexed load / store.
10175 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10176                                                    SDValue &Base,
10177                                                    SDValue &Offset,
10178                                                    ISD::MemIndexedMode &AM,
10179                                                    SelectionDAG &DAG) const {
10180   if (Subtarget->isThumb1Only())
10181     return false;
10182
10183   EVT VT;
10184   SDValue Ptr;
10185   bool isSEXTLoad = false;
10186   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10187     VT  = LD->getMemoryVT();
10188     Ptr = LD->getBasePtr();
10189     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10190   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10191     VT  = ST->getMemoryVT();
10192     Ptr = ST->getBasePtr();
10193   } else
10194     return false;
10195
10196   bool isInc;
10197   bool isLegal = false;
10198   if (Subtarget->isThumb2())
10199     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10200                                        isInc, DAG);
10201   else
10202     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10203                                         isInc, DAG);
10204   if (!isLegal)
10205     return false;
10206
10207   if (Ptr != Base) {
10208     // Swap base ptr and offset to catch more post-index load / store when
10209     // it's legal. In Thumb2 mode, offset must be an immediate.
10210     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10211         !Subtarget->isThumb2())
10212       std::swap(Base, Offset);
10213
10214     // Post-indexed load / store update the base pointer.
10215     if (Ptr != Base)
10216       return false;
10217   }
10218
10219   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10220   return true;
10221 }
10222
10223 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10224                                                       APInt &KnownZero,
10225                                                       APInt &KnownOne,
10226                                                       const SelectionDAG &DAG,
10227                                                       unsigned Depth) const {
10228   unsigned BitWidth = KnownOne.getBitWidth();
10229   KnownZero = KnownOne = APInt(BitWidth, 0);
10230   switch (Op.getOpcode()) {
10231   default: break;
10232   case ARMISD::ADDC:
10233   case ARMISD::ADDE:
10234   case ARMISD::SUBC:
10235   case ARMISD::SUBE:
10236     // These nodes' second result is a boolean
10237     if (Op.getResNo() == 0)
10238       break;
10239     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10240     break;
10241   case ARMISD::CMOV: {
10242     // Bits are known zero/one if known on the LHS and RHS.
10243     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10244     if (KnownZero == 0 && KnownOne == 0) return;
10245
10246     APInt KnownZeroRHS, KnownOneRHS;
10247     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10248     KnownZero &= KnownZeroRHS;
10249     KnownOne  &= KnownOneRHS;
10250     return;
10251   }
10252   case ISD::INTRINSIC_W_CHAIN: {
10253     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10254     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10255     switch (IntID) {
10256     default: return;
10257     case Intrinsic::arm_ldaex:
10258     case Intrinsic::arm_ldrex: {
10259       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10260       unsigned MemBits = VT.getScalarType().getSizeInBits();
10261       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10262       return;
10263     }
10264     }
10265   }
10266   }
10267 }
10268
10269 //===----------------------------------------------------------------------===//
10270 //                           ARM Inline Assembly Support
10271 //===----------------------------------------------------------------------===//
10272
10273 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10274   // Looking for "rev" which is V6+.
10275   if (!Subtarget->hasV6Ops())
10276     return false;
10277
10278   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10279   std::string AsmStr = IA->getAsmString();
10280   SmallVector<StringRef, 4> AsmPieces;
10281   SplitString(AsmStr, AsmPieces, ";\n");
10282
10283   switch (AsmPieces.size()) {
10284   default: return false;
10285   case 1:
10286     AsmStr = AsmPieces[0];
10287     AsmPieces.clear();
10288     SplitString(AsmStr, AsmPieces, " \t,");
10289
10290     // rev $0, $1
10291     if (AsmPieces.size() == 3 &&
10292         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10293         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10294       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10295       if (Ty && Ty->getBitWidth() == 32)
10296         return IntrinsicLowering::LowerToByteSwap(CI);
10297     }
10298     break;
10299   }
10300
10301   return false;
10302 }
10303
10304 /// getConstraintType - Given a constraint letter, return the type of
10305 /// constraint it is for this target.
10306 ARMTargetLowering::ConstraintType
10307 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10308   if (Constraint.size() == 1) {
10309     switch (Constraint[0]) {
10310     default:  break;
10311     case 'l': return C_RegisterClass;
10312     case 'w': return C_RegisterClass;
10313     case 'h': return C_RegisterClass;
10314     case 'x': return C_RegisterClass;
10315     case 't': return C_RegisterClass;
10316     case 'j': return C_Other; // Constant for movw.
10317       // An address with a single base register. Due to the way we
10318       // currently handle addresses it is the same as an 'r' memory constraint.
10319     case 'Q': return C_Memory;
10320     }
10321   } else if (Constraint.size() == 2) {
10322     switch (Constraint[0]) {
10323     default: break;
10324     // All 'U+' constraints are addresses.
10325     case 'U': return C_Memory;
10326     }
10327   }
10328   return TargetLowering::getConstraintType(Constraint);
10329 }
10330
10331 /// Examine constraint type and operand type and determine a weight value.
10332 /// This object must already have been set up with the operand type
10333 /// and the current alternative constraint selected.
10334 TargetLowering::ConstraintWeight
10335 ARMTargetLowering::getSingleConstraintMatchWeight(
10336     AsmOperandInfo &info, const char *constraint) const {
10337   ConstraintWeight weight = CW_Invalid;
10338   Value *CallOperandVal = info.CallOperandVal;
10339     // If we don't have a value, we can't do a match,
10340     // but allow it at the lowest weight.
10341   if (!CallOperandVal)
10342     return CW_Default;
10343   Type *type = CallOperandVal->getType();
10344   // Look at the constraint type.
10345   switch (*constraint) {
10346   default:
10347     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10348     break;
10349   case 'l':
10350     if (type->isIntegerTy()) {
10351       if (Subtarget->isThumb())
10352         weight = CW_SpecificReg;
10353       else
10354         weight = CW_Register;
10355     }
10356     break;
10357   case 'w':
10358     if (type->isFloatingPointTy())
10359       weight = CW_Register;
10360     break;
10361   }
10362   return weight;
10363 }
10364
10365 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10366 RCPair
10367 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10368                                                 MVT VT) const {
10369   if (Constraint.size() == 1) {
10370     // GCC ARM Constraint Letters
10371     switch (Constraint[0]) {
10372     case 'l': // Low regs or general regs.
10373       if (Subtarget->isThumb())
10374         return RCPair(0U, &ARM::tGPRRegClass);
10375       return RCPair(0U, &ARM::GPRRegClass);
10376     case 'h': // High regs or no regs.
10377       if (Subtarget->isThumb())
10378         return RCPair(0U, &ARM::hGPRRegClass);
10379       break;
10380     case 'r':
10381       return RCPair(0U, &ARM::GPRRegClass);
10382     case 'w':
10383       if (VT == MVT::Other)
10384         break;
10385       if (VT == MVT::f32)
10386         return RCPair(0U, &ARM::SPRRegClass);
10387       if (VT.getSizeInBits() == 64)
10388         return RCPair(0U, &ARM::DPRRegClass);
10389       if (VT.getSizeInBits() == 128)
10390         return RCPair(0U, &ARM::QPRRegClass);
10391       break;
10392     case 'x':
10393       if (VT == MVT::Other)
10394         break;
10395       if (VT == MVT::f32)
10396         return RCPair(0U, &ARM::SPR_8RegClass);
10397       if (VT.getSizeInBits() == 64)
10398         return RCPair(0U, &ARM::DPR_8RegClass);
10399       if (VT.getSizeInBits() == 128)
10400         return RCPair(0U, &ARM::QPR_8RegClass);
10401       break;
10402     case 't':
10403       if (VT == MVT::f32)
10404         return RCPair(0U, &ARM::SPRRegClass);
10405       break;
10406     }
10407   }
10408   if (StringRef("{cc}").equals_lower(Constraint))
10409     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10410
10411   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10412 }
10413
10414 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10415 /// vector.  If it is invalid, don't add anything to Ops.
10416 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10417                                                      std::string &Constraint,
10418                                                      std::vector<SDValue>&Ops,
10419                                                      SelectionDAG &DAG) const {
10420   SDValue Result;
10421
10422   // Currently only support length 1 constraints.
10423   if (Constraint.length() != 1) return;
10424
10425   char ConstraintLetter = Constraint[0];
10426   switch (ConstraintLetter) {
10427   default: break;
10428   case 'j':
10429   case 'I': case 'J': case 'K': case 'L':
10430   case 'M': case 'N': case 'O':
10431     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10432     if (!C)
10433       return;
10434
10435     int64_t CVal64 = C->getSExtValue();
10436     int CVal = (int) CVal64;
10437     // None of these constraints allow values larger than 32 bits.  Check
10438     // that the value fits in an int.
10439     if (CVal != CVal64)
10440       return;
10441
10442     switch (ConstraintLetter) {
10443       case 'j':
10444         // Constant suitable for movw, must be between 0 and
10445         // 65535.
10446         if (Subtarget->hasV6T2Ops())
10447           if (CVal >= 0 && CVal <= 65535)
10448             break;
10449         return;
10450       case 'I':
10451         if (Subtarget->isThumb1Only()) {
10452           // This must be a constant between 0 and 255, for ADD
10453           // immediates.
10454           if (CVal >= 0 && CVal <= 255)
10455             break;
10456         } else if (Subtarget->isThumb2()) {
10457           // A constant that can be used as an immediate value in a
10458           // data-processing instruction.
10459           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10460             break;
10461         } else {
10462           // A constant that can be used as an immediate value in a
10463           // data-processing instruction.
10464           if (ARM_AM::getSOImmVal(CVal) != -1)
10465             break;
10466         }
10467         return;
10468
10469       case 'J':
10470         if (Subtarget->isThumb()) {  // FIXME thumb2
10471           // This must be a constant between -255 and -1, for negated ADD
10472           // immediates. This can be used in GCC with an "n" modifier that
10473           // prints the negated value, for use with SUB instructions. It is
10474           // not useful otherwise but is implemented for compatibility.
10475           if (CVal >= -255 && CVal <= -1)
10476             break;
10477         } else {
10478           // This must be a constant between -4095 and 4095. It is not clear
10479           // what this constraint is intended for. Implemented for
10480           // compatibility with GCC.
10481           if (CVal >= -4095 && CVal <= 4095)
10482             break;
10483         }
10484         return;
10485
10486       case 'K':
10487         if (Subtarget->isThumb1Only()) {
10488           // A 32-bit value where only one byte has a nonzero value. Exclude
10489           // zero to match GCC. This constraint is used by GCC internally for
10490           // constants that can be loaded with a move/shift combination.
10491           // It is not useful otherwise but is implemented for compatibility.
10492           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10493             break;
10494         } else if (Subtarget->isThumb2()) {
10495           // A constant whose bitwise inverse can be used as an immediate
10496           // value in a data-processing instruction. This can be used in GCC
10497           // with a "B" modifier that prints the inverted value, for use with
10498           // BIC and MVN instructions. It is not useful otherwise but is
10499           // implemented for compatibility.
10500           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10501             break;
10502         } else {
10503           // A constant whose bitwise inverse can be used as an immediate
10504           // value in a data-processing instruction. This can be used in GCC
10505           // with a "B" modifier that prints the inverted value, for use with
10506           // BIC and MVN instructions. It is not useful otherwise but is
10507           // implemented for compatibility.
10508           if (ARM_AM::getSOImmVal(~CVal) != -1)
10509             break;
10510         }
10511         return;
10512
10513       case 'L':
10514         if (Subtarget->isThumb1Only()) {
10515           // This must be a constant between -7 and 7,
10516           // for 3-operand ADD/SUB immediate instructions.
10517           if (CVal >= -7 && CVal < 7)
10518             break;
10519         } else if (Subtarget->isThumb2()) {
10520           // A constant whose negation can be used as an immediate value in a
10521           // data-processing instruction. This can be used in GCC with an "n"
10522           // modifier that prints the negated value, for use with SUB
10523           // instructions. It is not useful otherwise but is implemented for
10524           // compatibility.
10525           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10526             break;
10527         } else {
10528           // A constant whose negation can be used as an immediate value in a
10529           // data-processing instruction. This can be used in GCC with an "n"
10530           // modifier that prints the negated value, for use with SUB
10531           // instructions. It is not useful otherwise but is implemented for
10532           // compatibility.
10533           if (ARM_AM::getSOImmVal(-CVal) != -1)
10534             break;
10535         }
10536         return;
10537
10538       case 'M':
10539         if (Subtarget->isThumb()) { // FIXME thumb2
10540           // This must be a multiple of 4 between 0 and 1020, for
10541           // ADD sp + immediate.
10542           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10543             break;
10544         } else {
10545           // A power of two or a constant between 0 and 32.  This is used in
10546           // GCC for the shift amount on shifted register operands, but it is
10547           // useful in general for any shift amounts.
10548           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10549             break;
10550         }
10551         return;
10552
10553       case 'N':
10554         if (Subtarget->isThumb()) {  // FIXME thumb2
10555           // This must be a constant between 0 and 31, for shift amounts.
10556           if (CVal >= 0 && CVal <= 31)
10557             break;
10558         }
10559         return;
10560
10561       case 'O':
10562         if (Subtarget->isThumb()) {  // FIXME thumb2
10563           // This must be a multiple of 4 between -508 and 508, for
10564           // ADD/SUB sp = sp + immediate.
10565           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10566             break;
10567         }
10568         return;
10569     }
10570     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10571     break;
10572   }
10573
10574   if (Result.getNode()) {
10575     Ops.push_back(Result);
10576     return;
10577   }
10578   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10579 }
10580
10581 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10582   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10583   unsigned Opcode = Op->getOpcode();
10584   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10585       "Invalid opcode for Div/Rem lowering");
10586   bool isSigned = (Opcode == ISD::SDIVREM);
10587   EVT VT = Op->getValueType(0);
10588   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10589
10590   RTLIB::Libcall LC;
10591   switch (VT.getSimpleVT().SimpleTy) {
10592   default: llvm_unreachable("Unexpected request for libcall!");
10593   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10594   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10595   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10596   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10597   }
10598
10599   SDValue InChain = DAG.getEntryNode();
10600
10601   TargetLowering::ArgListTy Args;
10602   TargetLowering::ArgListEntry Entry;
10603   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10604     EVT ArgVT = Op->getOperand(i).getValueType();
10605     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10606     Entry.Node = Op->getOperand(i);
10607     Entry.Ty = ArgTy;
10608     Entry.isSExt = isSigned;
10609     Entry.isZExt = !isSigned;
10610     Args.push_back(Entry);
10611   }
10612
10613   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10614                                          getPointerTy());
10615
10616   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10617
10618   SDLoc dl(Op);
10619   TargetLowering::CallLoweringInfo CLI(DAG);
10620   CLI.setDebugLoc(dl).setChain(InChain)
10621     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10622     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10623
10624   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10625   return CallInfo.first;
10626 }
10627
10628 SDValue
10629 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10630   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10631   SDLoc DL(Op);
10632
10633   // Get the inputs.
10634   SDValue Chain = Op.getOperand(0);
10635   SDValue Size  = Op.getOperand(1);
10636
10637   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10638                               DAG.getConstant(2, MVT::i32));
10639
10640   SDValue Flag;
10641   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10642   Flag = Chain.getValue(1);
10643
10644   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10645   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10646
10647   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10648   Chain = NewSP.getValue(1);
10649
10650   SDValue Ops[2] = { NewSP, Chain };
10651   return DAG.getMergeValues(Ops, DL);
10652 }
10653
10654 bool
10655 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10656   // The ARM target isn't yet aware of offsets.
10657   return false;
10658 }
10659
10660 bool ARM::isBitFieldInvertedMask(unsigned v) {
10661   if (v == 0xffffffff)
10662     return false;
10663
10664   // there can be 1's on either or both "outsides", all the "inside"
10665   // bits must be 0's
10666   unsigned TO = CountTrailingOnes_32(v);
10667   unsigned LO = CountLeadingOnes_32(v);
10668   v = (v >> TO) << TO;
10669   v = (v << LO) >> LO;
10670   return v == 0;
10671 }
10672
10673 /// isFPImmLegal - Returns true if the target can instruction select the
10674 /// specified FP immediate natively. If false, the legalizer will
10675 /// materialize the FP immediate as a load from a constant pool.
10676 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10677   if (!Subtarget->hasVFP3())
10678     return false;
10679   if (VT == MVT::f32)
10680     return ARM_AM::getFP32Imm(Imm) != -1;
10681   if (VT == MVT::f64)
10682     return ARM_AM::getFP64Imm(Imm) != -1;
10683   return false;
10684 }
10685
10686 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10687 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10688 /// specified in the intrinsic calls.
10689 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10690                                            const CallInst &I,
10691                                            unsigned Intrinsic) const {
10692   switch (Intrinsic) {
10693   case Intrinsic::arm_neon_vld1:
10694   case Intrinsic::arm_neon_vld2:
10695   case Intrinsic::arm_neon_vld3:
10696   case Intrinsic::arm_neon_vld4:
10697   case Intrinsic::arm_neon_vld2lane:
10698   case Intrinsic::arm_neon_vld3lane:
10699   case Intrinsic::arm_neon_vld4lane: {
10700     Info.opc = ISD::INTRINSIC_W_CHAIN;
10701     // Conservatively set memVT to the entire set of vectors loaded.
10702     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10703     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10704     Info.ptrVal = I.getArgOperand(0);
10705     Info.offset = 0;
10706     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10707     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10708     Info.vol = false; // volatile loads with NEON intrinsics not supported
10709     Info.readMem = true;
10710     Info.writeMem = false;
10711     return true;
10712   }
10713   case Intrinsic::arm_neon_vst1:
10714   case Intrinsic::arm_neon_vst2:
10715   case Intrinsic::arm_neon_vst3:
10716   case Intrinsic::arm_neon_vst4:
10717   case Intrinsic::arm_neon_vst2lane:
10718   case Intrinsic::arm_neon_vst3lane:
10719   case Intrinsic::arm_neon_vst4lane: {
10720     Info.opc = ISD::INTRINSIC_VOID;
10721     // Conservatively set memVT to the entire set of vectors stored.
10722     unsigned NumElts = 0;
10723     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10724       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10725       if (!ArgTy->isVectorTy())
10726         break;
10727       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10728     }
10729     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10730     Info.ptrVal = I.getArgOperand(0);
10731     Info.offset = 0;
10732     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10733     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10734     Info.vol = false; // volatile stores with NEON intrinsics not supported
10735     Info.readMem = false;
10736     Info.writeMem = true;
10737     return true;
10738   }
10739   case Intrinsic::arm_ldaex:
10740   case Intrinsic::arm_ldrex: {
10741     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10742     Info.opc = ISD::INTRINSIC_W_CHAIN;
10743     Info.memVT = MVT::getVT(PtrTy->getElementType());
10744     Info.ptrVal = I.getArgOperand(0);
10745     Info.offset = 0;
10746     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10747     Info.vol = true;
10748     Info.readMem = true;
10749     Info.writeMem = false;
10750     return true;
10751   }
10752   case Intrinsic::arm_stlex:
10753   case Intrinsic::arm_strex: {
10754     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10755     Info.opc = ISD::INTRINSIC_W_CHAIN;
10756     Info.memVT = MVT::getVT(PtrTy->getElementType());
10757     Info.ptrVal = I.getArgOperand(1);
10758     Info.offset = 0;
10759     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10760     Info.vol = true;
10761     Info.readMem = false;
10762     Info.writeMem = true;
10763     return true;
10764   }
10765   case Intrinsic::arm_stlexd:
10766   case Intrinsic::arm_strexd: {
10767     Info.opc = ISD::INTRINSIC_W_CHAIN;
10768     Info.memVT = MVT::i64;
10769     Info.ptrVal = I.getArgOperand(2);
10770     Info.offset = 0;
10771     Info.align = 8;
10772     Info.vol = true;
10773     Info.readMem = false;
10774     Info.writeMem = true;
10775     return true;
10776   }
10777   case Intrinsic::arm_ldaexd:
10778   case Intrinsic::arm_ldrexd: {
10779     Info.opc = ISD::INTRINSIC_W_CHAIN;
10780     Info.memVT = MVT::i64;
10781     Info.ptrVal = I.getArgOperand(0);
10782     Info.offset = 0;
10783     Info.align = 8;
10784     Info.vol = true;
10785     Info.readMem = true;
10786     Info.writeMem = false;
10787     return true;
10788   }
10789   default:
10790     break;
10791   }
10792
10793   return false;
10794 }
10795
10796 /// \brief Returns true if it is beneficial to convert a load of a constant
10797 /// to just the constant itself.
10798 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10799                                                           Type *Ty) const {
10800   assert(Ty->isIntegerTy());
10801
10802   unsigned Bits = Ty->getPrimitiveSizeInBits();
10803   if (Bits == 0 || Bits > 32)
10804     return false;
10805   return true;
10806 }
10807
10808 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10809   // Loads and stores less than 64-bits are already atomic; ones above that
10810   // are doomed anyway, so defer to the default libcall and blame the OS when
10811   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10812   // anything for those.
10813   bool IsMClass = Subtarget->isMClass();
10814   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10815     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10816     return Size == 64 && !IsMClass;
10817   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10818     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10819   }
10820
10821   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10822   // and up to 64 bits on the non-M profiles
10823   unsigned AtomicLimit = IsMClass ? 32 : 64;
10824   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10825 }
10826
10827 // This has so far only been implemented for MachO.
10828 bool ARMTargetLowering::useLoadStackGuardNode() const {
10829   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10830 }
10831
10832 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10833                                          AtomicOrdering Ord) const {
10834   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10835   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10836   bool IsAcquire =
10837       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10838
10839   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10840   // intrinsic must return {i32, i32} and we have to recombine them into a
10841   // single i64 here.
10842   if (ValTy->getPrimitiveSizeInBits() == 64) {
10843     Intrinsic::ID Int =
10844         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10845     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10846
10847     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10848     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10849
10850     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10851     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10852     if (!Subtarget->isLittle())
10853       std::swap (Lo, Hi);
10854     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10855     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10856     return Builder.CreateOr(
10857         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10858   }
10859
10860   Type *Tys[] = { Addr->getType() };
10861   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10862   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10863
10864   return Builder.CreateTruncOrBitCast(
10865       Builder.CreateCall(Ldrex, Addr),
10866       cast<PointerType>(Addr->getType())->getElementType());
10867 }
10868
10869 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10870                                                Value *Addr,
10871                                                AtomicOrdering Ord) const {
10872   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10873   bool IsRelease =
10874       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10875
10876   // Since the intrinsics must have legal type, the i64 intrinsics take two
10877   // parameters: "i32, i32". We must marshal Val into the appropriate form
10878   // before the call.
10879   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10880     Intrinsic::ID Int =
10881         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10882     Function *Strex = Intrinsic::getDeclaration(M, Int);
10883     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10884
10885     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10886     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10887     if (!Subtarget->isLittle())
10888       std::swap (Lo, Hi);
10889     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10890     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10891   }
10892
10893   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10894   Type *Tys[] = { Addr->getType() };
10895   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10896
10897   return Builder.CreateCall2(
10898       Strex, Builder.CreateZExtOrBitCast(
10899                  Val, Strex->getFunctionType()->getParamType(0)),
10900       Addr);
10901 }
10902
10903 enum HABaseType {
10904   HA_UNKNOWN = 0,
10905   HA_FLOAT,
10906   HA_DOUBLE,
10907   HA_VECT64,
10908   HA_VECT128
10909 };
10910
10911 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10912                                    uint64_t &Members) {
10913   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10914     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10915       uint64_t SubMembers = 0;
10916       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10917         return false;
10918       Members += SubMembers;
10919     }
10920   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10921     uint64_t SubMembers = 0;
10922     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10923       return false;
10924     Members += SubMembers * AT->getNumElements();
10925   } else if (Ty->isFloatTy()) {
10926     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10927       return false;
10928     Members = 1;
10929     Base = HA_FLOAT;
10930   } else if (Ty->isDoubleTy()) {
10931     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10932       return false;
10933     Members = 1;
10934     Base = HA_DOUBLE;
10935   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10936     Members = 1;
10937     switch (Base) {
10938     case HA_FLOAT:
10939     case HA_DOUBLE:
10940       return false;
10941     case HA_VECT64:
10942       return VT->getBitWidth() == 64;
10943     case HA_VECT128:
10944       return VT->getBitWidth() == 128;
10945     case HA_UNKNOWN:
10946       switch (VT->getBitWidth()) {
10947       case 64:
10948         Base = HA_VECT64;
10949         return true;
10950       case 128:
10951         Base = HA_VECT128;
10952         return true;
10953       default:
10954         return false;
10955       }
10956     }
10957   }
10958
10959   return (Members > 0 && Members <= 4);
10960 }
10961
10962 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10963 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10964     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10965   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10966       CallingConv::ARM_AAPCS_VFP)
10967     return false;
10968
10969   HABaseType Base = HA_UNKNOWN;
10970   uint64_t Members = 0;
10971   bool result = isHomogeneousAggregate(Ty, Base, Members);
10972   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10973   return result;
10974 }