OSDN Git Service

Add support for the 'h' constraint.
[android-x86/external-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 #define DEBUG_TYPE "arm-isel"
16 #include "ARM.h"
17 #include "ARMAddressingModes.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMISelLowering.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "ARMPerfectShuffle.h"
23 #include "ARMRegisterInfo.h"
24 #include "ARMSubtarget.h"
25 #include "ARMTargetMachine.h"
26 #include "ARMTargetObjectFile.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Instruction.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Type.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/IntrinsicLowering.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/PseudoSourceValue.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <sstream>
54 using namespace llvm;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58
59 // This option should go away when tail calls fully work.
60 static cl::opt<bool>
61 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
62   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
63   cl::init(false));
64
65 cl::opt<bool>
66 EnableARMLongCalls("arm-long-calls", cl::Hidden,
67   cl::desc("Generate calls via indirect call instructions"),
68   cl::init(false));
69
70 static cl::opt<bool>
71 ARMInterworking("arm-interworking", cl::Hidden,
72   cl::desc("Enable / disable ARM interworking (for debugging only)"),
73   cl::init(true));
74
75 namespace llvm {
76   class ARMCCState : public CCState {
77   public:
78     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
79                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
80                LLVMContext &C, ParmContext PC)
81         : CCState(CC, isVarArg, MF, TM, locs, C) {
82       assert(((PC == Call) || (PC == Prologue)) &&
83              "ARMCCState users must specify whether their context is call"
84              "or prologue generation.");
85       CallOrPrologue = PC;
86     }
87   };
88 }
89
90 // The APCS parameter registers.
91 static const unsigned GPRArgRegs[] = {
92   ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 };
94
95 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
96                                        EVT PromotedBitwiseVT) {
97   if (VT != PromotedLdStVT) {
98     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
99     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
100                        PromotedLdStVT.getSimpleVT());
101
102     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
103     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
104                        PromotedLdStVT.getSimpleVT());
105   }
106
107   EVT ElemTy = VT.getVectorElementType();
108   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
109     setOperationAction(ISD::VSETCC, VT.getSimpleVT(), Custom);
110   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
111   if (ElemTy != MVT::i32) {
112     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
113     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
114     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
115     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
116   }
117   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
118   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
119   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
120   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
121   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
122   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
125     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
126     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
127     setLoadExtAction(ISD::SEXTLOAD, VT.getSimpleVT(), Expand);
128     setLoadExtAction(ISD::ZEXTLOAD, VT.getSimpleVT(), Expand);
129     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
130          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
131       setTruncStoreAction(VT.getSimpleVT(),
132                           (MVT::SimpleValueType)InnerVT, Expand);
133   }
134   setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
135
136   // Promote all bit-wise operations.
137   if (VT.isInteger() && VT != PromotedBitwiseVT) {
138     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
139     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
140                        PromotedBitwiseVT.getSimpleVT());
141     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
142     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
143                        PromotedBitwiseVT.getSimpleVT());
144     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
145     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
146                        PromotedBitwiseVT.getSimpleVT());
147   }
148
149   // Neon does not support vector divide/remainder operations.
150   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
154   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
155   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
156 }
157
158 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
159   addRegisterClass(VT, ARM::DPRRegisterClass);
160   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
161 }
162
163 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
164   addRegisterClass(VT, ARM::QPRRegisterClass);
165   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
166 }
167
168 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
169   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
170     return new TargetLoweringObjectFileMachO();
171
172   return new ARMElfTargetObjectFile();
173 }
174
175 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
176     : TargetLowering(TM, createTLOF(TM)) {
177   Subtarget = &TM.getSubtarget<ARMSubtarget>();
178   RegInfo = TM.getRegisterInfo();
179   Itins = TM.getInstrItineraryData();
180
181   if (Subtarget->isTargetDarwin()) {
182     // Uses VFP for Thumb libfuncs if available.
183     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
184       // Single-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
186       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
187       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
188       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
189
190       // Double-precision floating-point arithmetic.
191       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
192       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
193       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
194       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
195
196       // Single-precision comparisons.
197       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
198       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
199       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
200       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
201       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
202       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
203       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
204       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
205
206       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
213       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
214
215       // Double-precision comparisons.
216       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
217       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
218       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
219       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
220       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
221       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
222       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
223       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
224
225       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
232       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
233
234       // Floating-point to integer conversions.
235       // i64 conversions are done via library routines even when generating VFP
236       // instructions, so use the same ones.
237       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
238       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
239       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
240       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
241
242       // Conversions between floating types.
243       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
244       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
245
246       // Integer to floating-point conversions.
247       // i64 conversions are done via library routines even when generating VFP
248       // instructions, so use the same ones.
249       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
250       // e.g., __floatunsidf vs. __floatunssidfvfp.
251       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
252       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
253       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
254       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
255     }
256   }
257
258   // These libcalls are not available in 32-bit.
259   setLibcallName(RTLIB::SHL_I128, 0);
260   setLibcallName(RTLIB::SRL_I128, 0);
261   setLibcallName(RTLIB::SRA_I128, 0);
262
263   if (Subtarget->isAAPCS_ABI()) {
264     // Double-precision floating-point arithmetic helper functions
265     // RTABI chapter 4.1.2, Table 2
266     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
267     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
268     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
269     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
270     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
271     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
274
275     // Double-precision floating-point comparison helper functions
276     // RTABI chapter 4.1.2, Table 3
277     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
278     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
279     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
280     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
281     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
282     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
284     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
285     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
286     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
287     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
288     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
289     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
290     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
291     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
292     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
293     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
301
302     // Single-precision floating-point arithmetic helper functions
303     // RTABI chapter 4.1.2, Table 4
304     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
305     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
306     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
307     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
308     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
309     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
312
313     // Single-precision floating-point comparison helper functions
314     // RTABI chapter 4.1.2, Table 5
315     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
316     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
317     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
318     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
319     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
320     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
322     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
323     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
324     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
325     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
326     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
327     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
328     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
329     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
330     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
331     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
339
340     // Floating-point to integer conversions.
341     // RTABI chapter 4.1.2, Table 6
342     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
343     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
345     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
346     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
347     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
348     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
349     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
350     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
358
359     // Conversions between floating types.
360     // RTABI chapter 4.1.2, Table 7
361     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
362     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
363     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
364     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
365
366     // Integer to floating-point conversions.
367     // RTABI chapter 4.1.2, Table 8
368     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
369     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
370     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
371     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
372     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
373     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
374     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
375     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384
385     // Long long helper functions
386     // RTABI chapter 4.2, Table 9
387     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
388     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
389     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
390     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
391     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
392     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
393     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
398     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
399
400     // Integer division functions
401     // RTABI chapter 4.3.1
402     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
403     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
404     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
405     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
407     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
408     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
414
415     // Memory operations
416     // RTABI chapter 4.3.4
417     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
418     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
419     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
420   }
421
422   if (Subtarget->isThumb1Only())
423     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
424   else
425     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
426   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
427     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
428     if (!Subtarget->isFPOnlySP())
429       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
430
431     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
432   }
433
434   if (Subtarget->hasNEON()) {
435     addDRTypeForNEON(MVT::v2f32);
436     addDRTypeForNEON(MVT::v8i8);
437     addDRTypeForNEON(MVT::v4i16);
438     addDRTypeForNEON(MVT::v2i32);
439     addDRTypeForNEON(MVT::v1i64);
440
441     addQRTypeForNEON(MVT::v4f32);
442     addQRTypeForNEON(MVT::v2f64);
443     addQRTypeForNEON(MVT::v16i8);
444     addQRTypeForNEON(MVT::v8i16);
445     addQRTypeForNEON(MVT::v4i32);
446     addQRTypeForNEON(MVT::v2i64);
447
448     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
449     // neither Neon nor VFP support any arithmetic operations on it.
450     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
451     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
452     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
453     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
454     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
455     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
456     setOperationAction(ISD::VSETCC, MVT::v2f64, Expand);
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     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
470     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
471     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
474
475     setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
476
477     // Neon does not support some operations on v1i64 and v2i64 types.
478     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
479     // Custom handling for some quad-vector types to detect VMULL.
480     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
481     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
482     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
483     // Custom handling for some vector types to avoid expensive expansions
484     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
485     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
486     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
487     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
488     setOperationAction(ISD::VSETCC, MVT::v1i64, Expand);
489     setOperationAction(ISD::VSETCC, MVT::v2i64, Expand);
490     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
491     // a destination type that is wider than the source.
492     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
493     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
494
495     setTargetDAGCombine(ISD::INTRINSIC_VOID);
496     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
497     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
498     setTargetDAGCombine(ISD::SHL);
499     setTargetDAGCombine(ISD::SRL);
500     setTargetDAGCombine(ISD::SRA);
501     setTargetDAGCombine(ISD::SIGN_EXTEND);
502     setTargetDAGCombine(ISD::ZERO_EXTEND);
503     setTargetDAGCombine(ISD::ANY_EXTEND);
504     setTargetDAGCombine(ISD::SELECT_CC);
505     setTargetDAGCombine(ISD::BUILD_VECTOR);
506     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
507     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
508     setTargetDAGCombine(ISD::STORE);
509     setTargetDAGCombine(ISD::FP_TO_SINT);
510     setTargetDAGCombine(ISD::FP_TO_UINT);
511     setTargetDAGCombine(ISD::FDIV);
512   }
513
514   computeRegisterProperties();
515
516   // ARM does not have f32 extending load.
517   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
518
519   // ARM does not have i1 sign extending load.
520   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
521
522   // ARM supports all 4 flavors of integer indexed load / store.
523   if (!Subtarget->isThumb1Only()) {
524     for (unsigned im = (unsigned)ISD::PRE_INC;
525          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
526       setIndexedLoadAction(im,  MVT::i1,  Legal);
527       setIndexedLoadAction(im,  MVT::i8,  Legal);
528       setIndexedLoadAction(im,  MVT::i16, Legal);
529       setIndexedLoadAction(im,  MVT::i32, Legal);
530       setIndexedStoreAction(im, MVT::i1,  Legal);
531       setIndexedStoreAction(im, MVT::i8,  Legal);
532       setIndexedStoreAction(im, MVT::i16, Legal);
533       setIndexedStoreAction(im, MVT::i32, Legal);
534     }
535   }
536
537   // i64 operation support.
538   setOperationAction(ISD::MUL,     MVT::i64, Expand);
539   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
540   if (Subtarget->isThumb1Only()) {
541     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
542     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
543   }
544   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops())
545     setOperationAction(ISD::MULHS, MVT::i32, Expand);
546
547   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
548   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
549   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
550   setOperationAction(ISD::SRL,       MVT::i64, Custom);
551   setOperationAction(ISD::SRA,       MVT::i64, Custom);
552
553   // ARM does not have ROTL.
554   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
555   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
556   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
557   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
558     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
559
560   // Only ARMv6 has BSWAP.
561   if (!Subtarget->hasV6Ops())
562     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
563
564   // These are expanded into libcalls.
565   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
566     // v7M has a hardware divider
567     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
568     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
569   }
570   setOperationAction(ISD::SREM,  MVT::i32, Expand);
571   setOperationAction(ISD::UREM,  MVT::i32, Expand);
572   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
573   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
574
575   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
576   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
577   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
578   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
579   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
580
581   setOperationAction(ISD::TRAP, MVT::Other, Legal);
582
583   // Use the default implementation.
584   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
585   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
586   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
587   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
588   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
589   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
590   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
591   setOperationAction(ISD::EXCEPTIONADDR,      MVT::i32,   Expand);
592   setExceptionPointerRegister(ARM::R0);
593   setExceptionSelectorRegister(ARM::R1);
594
595   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
596   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
597   // the default expansion.
598   if (Subtarget->hasDataBarrier() ||
599       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
600     // membarrier needs custom lowering; the rest are legal and handled
601     // normally.
602     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
603   } else {
604     // Set them all for expansion, which will force libcalls.
605     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
606     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i8,  Expand);
607     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i16, Expand);
608     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
609     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i8,  Expand);
610     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i16, Expand);
611     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
612     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i8,  Expand);
613     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i16, Expand);
614     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
615     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i8,  Expand);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i16, Expand);
617     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
618     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i8,  Expand);
619     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i16, Expand);
620     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
621     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i8,  Expand);
622     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i16, Expand);
623     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
624     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i8,  Expand);
625     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i16, Expand);
626     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
627     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i8,  Expand);
628     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i16, Expand);
629     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
630     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i8,  Expand);
631     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i16, Expand);
632     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
633     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i8,  Expand);
634     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i16, Expand);
635     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
636     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i8,  Expand);
637     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i16, Expand);
638     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
639     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i8,  Expand);
640     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i16, Expand);
641     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
642     // Since the libcalls include locking, fold in the fences
643     setShouldFoldAtomicFences(true);
644   }
645   // 64-bit versions are always libcalls (for now)
646   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Expand);
647   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Expand);
648   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Expand);
649   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Expand);
650   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Expand);
651   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Expand);
652   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Expand);
653   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Expand);
654
655   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
656
657   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
658   if (!Subtarget->hasV6Ops()) {
659     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
660     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
661   }
662   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
663
664   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
665     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
666     // iff target supports vfp2.
667     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
668     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
669   }
670
671   // We want to custom lower some of our intrinsics.
672   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
673   if (Subtarget->isTargetDarwin()) {
674     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
675     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
676     setOperationAction(ISD::EH_SJLJ_DISPATCHSETUP, MVT::Other, Custom);
677     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
678   }
679
680   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
681   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
682   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
683   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
684   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
685   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
686   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
687   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
688   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
689
690   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
691   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
692   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
693   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
694   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
695
696   // We don't support sin/cos/fmod/copysign/pow
697   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
698   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
699   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
700   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
701   setOperationAction(ISD::FREM,      MVT::f64, Expand);
702   setOperationAction(ISD::FREM,      MVT::f32, Expand);
703   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
704     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
705     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
706   }
707   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
708   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
709
710   // Various VFP goodness
711   if (!UseSoftFloat && !Subtarget->isThumb1Only()) {
712     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
713     if (Subtarget->hasVFP2()) {
714       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
715       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
716       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
717       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
718     }
719     // Special handling for half-precision FP.
720     if (!Subtarget->hasFP16()) {
721       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
722       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
723     }
724   }
725
726   // We have target-specific dag combine patterns for the following nodes:
727   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
728   setTargetDAGCombine(ISD::ADD);
729   setTargetDAGCombine(ISD::SUB);
730   setTargetDAGCombine(ISD::MUL);
731
732   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON())
733     setTargetDAGCombine(ISD::OR);
734   if (Subtarget->hasNEON())
735     setTargetDAGCombine(ISD::AND);
736
737   setStackPointerRegisterToSaveRestore(ARM::SP);
738
739   if (UseSoftFloat || Subtarget->isThumb1Only() || !Subtarget->hasVFP2())
740     setSchedulingPreference(Sched::RegPressure);
741   else
742     setSchedulingPreference(Sched::Hybrid);
743
744   //// temporary - rewrite interface to use type
745   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
746
747   // On ARM arguments smaller than 4 bytes are extended, so all arguments
748   // are at least 4 bytes aligned.
749   setMinStackArgumentAlignment(4);
750
751   benefitFromCodePlacementOpt = true;
752
753   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
754 }
755
756 // FIXME: It might make sense to define the representative register class as the
757 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
758 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
759 // SPR's representative would be DPR_VFP2. This should work well if register
760 // pressure tracking were modified such that a register use would increment the
761 // pressure of the register class's representative and all of it's super
762 // classes' representatives transitively. We have not implemented this because
763 // of the difficulty prior to coalescing of modeling operand register classes
764 // due to the common occurrence of cross class copies and subregister insertions
765 // and extractions.
766 std::pair<const TargetRegisterClass*, uint8_t>
767 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
768   const TargetRegisterClass *RRC = 0;
769   uint8_t Cost = 1;
770   switch (VT.getSimpleVT().SimpleTy) {
771   default:
772     return TargetLowering::findRepresentativeClass(VT);
773   // Use DPR as representative register class for all floating point
774   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
775   // the cost is 1 for both f32 and f64.
776   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
777   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
778     RRC = ARM::DPRRegisterClass;
779     // When NEON is used for SP, only half of the register file is available
780     // because operations that define both SP and DP results will be constrained
781     // to the VFP2 class (D0-D15). We currently model this constraint prior to
782     // coalescing by double-counting the SP regs. See the FIXME above.
783     if (Subtarget->useNEONForSinglePrecisionFP())
784       Cost = 2;
785     break;
786   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
787   case MVT::v4f32: case MVT::v2f64:
788     RRC = ARM::DPRRegisterClass;
789     Cost = 2;
790     break;
791   case MVT::v4i64:
792     RRC = ARM::DPRRegisterClass;
793     Cost = 4;
794     break;
795   case MVT::v8i64:
796     RRC = ARM::DPRRegisterClass;
797     Cost = 8;
798     break;
799   }
800   return std::make_pair(RRC, Cost);
801 }
802
803 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
804   switch (Opcode) {
805   default: return 0;
806   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
807   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
808   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
809   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
810   case ARMISD::CALL:          return "ARMISD::CALL";
811   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
812   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
813   case ARMISD::tCALL:         return "ARMISD::tCALL";
814   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
815   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
816   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
817   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
818   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
819   case ARMISD::CMP:           return "ARMISD::CMP";
820   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
821   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
822   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
823   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
824   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
825   case ARMISD::CMOV:          return "ARMISD::CMOV";
826
827   case ARMISD::RBIT:          return "ARMISD::RBIT";
828
829   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
830   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
831   case ARMISD::SITOF:         return "ARMISD::SITOF";
832   case ARMISD::UITOF:         return "ARMISD::UITOF";
833
834   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
835   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
836   case ARMISD::RRX:           return "ARMISD::RRX";
837
838   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
839   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
840
841   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
842   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
843   case ARMISD::EH_SJLJ_DISPATCHSETUP:return "ARMISD::EH_SJLJ_DISPATCHSETUP";
844
845   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
846
847   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
848
849   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
850
851   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
852   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
853
854   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
855
856   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
857   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
858   case ARMISD::VCGE:          return "ARMISD::VCGE";
859   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
860   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
861   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
862   case ARMISD::VCGT:          return "ARMISD::VCGT";
863   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
864   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
865   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
866   case ARMISD::VTST:          return "ARMISD::VTST";
867
868   case ARMISD::VSHL:          return "ARMISD::VSHL";
869   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
870   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
871   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
872   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
873   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
874   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
875   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
876   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
877   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
878   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
879   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
880   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
881   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
882   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
883   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
884   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
885   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
886   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
887   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
888   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
889   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
890   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
891   case ARMISD::VDUP:          return "ARMISD::VDUP";
892   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
893   case ARMISD::VEXT:          return "ARMISD::VEXT";
894   case ARMISD::VREV64:        return "ARMISD::VREV64";
895   case ARMISD::VREV32:        return "ARMISD::VREV32";
896   case ARMISD::VREV16:        return "ARMISD::VREV16";
897   case ARMISD::VZIP:          return "ARMISD::VZIP";
898   case ARMISD::VUZP:          return "ARMISD::VUZP";
899   case ARMISD::VTRN:          return "ARMISD::VTRN";
900   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
901   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
902   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
903   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
904   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
905   case ARMISD::FMAX:          return "ARMISD::FMAX";
906   case ARMISD::FMIN:          return "ARMISD::FMIN";
907   case ARMISD::BFI:           return "ARMISD::BFI";
908   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
909   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
910   case ARMISD::VBSL:          return "ARMISD::VBSL";
911   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
912   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
913   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
914   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
915   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
916   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
917   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
918   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
919   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
920   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
921   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
922   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
923   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
924   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
925   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
926   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
927   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
928   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
929   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
930   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
931   }
932 }
933
934 /// getRegClassFor - Return the register class that should be used for the
935 /// specified value type.
936 TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
937   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
938   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
939   // load / store 4 to 8 consecutive D registers.
940   if (Subtarget->hasNEON()) {
941     if (VT == MVT::v4i64)
942       return ARM::QQPRRegisterClass;
943     else if (VT == MVT::v8i64)
944       return ARM::QQQQPRRegisterClass;
945   }
946   return TargetLowering::getRegClassFor(VT);
947 }
948
949 // Create a fast isel object.
950 FastISel *
951 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
952   return ARM::createFastISel(funcInfo);
953 }
954
955 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
956 /// be used for loads / stores from the global.
957 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
958   return (Subtarget->isThumb1Only() ? 127 : 4095);
959 }
960
961 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
962   unsigned NumVals = N->getNumValues();
963   if (!NumVals)
964     return Sched::RegPressure;
965
966   for (unsigned i = 0; i != NumVals; ++i) {
967     EVT VT = N->getValueType(i);
968     if (VT == MVT::Glue || VT == MVT::Other)
969       continue;
970     if (VT.isFloatingPoint() || VT.isVector())
971       return Sched::Latency;
972   }
973
974   if (!N->isMachineOpcode())
975     return Sched::RegPressure;
976
977   // Load are scheduled for latency even if there instruction itinerary
978   // is not available.
979   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
980   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
981
982   if (MCID.getNumDefs() == 0)
983     return Sched::RegPressure;
984   if (!Itins->isEmpty() &&
985       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
986     return Sched::Latency;
987
988   return Sched::RegPressure;
989 }
990
991 //===----------------------------------------------------------------------===//
992 // Lowering Code
993 //===----------------------------------------------------------------------===//
994
995 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
996 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
997   switch (CC) {
998   default: llvm_unreachable("Unknown condition code!");
999   case ISD::SETNE:  return ARMCC::NE;
1000   case ISD::SETEQ:  return ARMCC::EQ;
1001   case ISD::SETGT:  return ARMCC::GT;
1002   case ISD::SETGE:  return ARMCC::GE;
1003   case ISD::SETLT:  return ARMCC::LT;
1004   case ISD::SETLE:  return ARMCC::LE;
1005   case ISD::SETUGT: return ARMCC::HI;
1006   case ISD::SETUGE: return ARMCC::HS;
1007   case ISD::SETULT: return ARMCC::LO;
1008   case ISD::SETULE: return ARMCC::LS;
1009   }
1010 }
1011
1012 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1013 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1014                         ARMCC::CondCodes &CondCode2) {
1015   CondCode2 = ARMCC::AL;
1016   switch (CC) {
1017   default: llvm_unreachable("Unknown FP condition!");
1018   case ISD::SETEQ:
1019   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1020   case ISD::SETGT:
1021   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1022   case ISD::SETGE:
1023   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1024   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1025   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1026   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1027   case ISD::SETO:   CondCode = ARMCC::VC; break;
1028   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1029   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1030   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1031   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1032   case ISD::SETLT:
1033   case ISD::SETULT: CondCode = ARMCC::LT; break;
1034   case ISD::SETLE:
1035   case ISD::SETULE: CondCode = ARMCC::LE; break;
1036   case ISD::SETNE:
1037   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1038   }
1039 }
1040
1041 //===----------------------------------------------------------------------===//
1042 //                      Calling Convention Implementation
1043 //===----------------------------------------------------------------------===//
1044
1045 #include "ARMGenCallingConv.inc"
1046
1047 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1048 /// given CallingConvention value.
1049 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1050                                                  bool Return,
1051                                                  bool isVarArg) const {
1052   switch (CC) {
1053   default:
1054     llvm_unreachable("Unsupported calling convention");
1055   case CallingConv::Fast:
1056     if (Subtarget->hasVFP2() && !isVarArg) {
1057       if (!Subtarget->isAAPCS_ABI())
1058         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1059       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1060       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1061     }
1062     // Fallthrough
1063   case CallingConv::C: {
1064     // Use target triple & subtarget features to do actual dispatch.
1065     if (!Subtarget->isAAPCS_ABI())
1066       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1067     else if (Subtarget->hasVFP2() &&
1068              FloatABIType == FloatABI::Hard && !isVarArg)
1069       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1070     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1071   }
1072   case CallingConv::ARM_AAPCS_VFP:
1073     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1074   case CallingConv::ARM_AAPCS:
1075     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1076   case CallingConv::ARM_APCS:
1077     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1078   }
1079 }
1080
1081 /// LowerCallResult - Lower the result values of a call into the
1082 /// appropriate copies out of appropriate physical registers.
1083 SDValue
1084 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1085                                    CallingConv::ID CallConv, bool isVarArg,
1086                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1087                                    DebugLoc dl, SelectionDAG &DAG,
1088                                    SmallVectorImpl<SDValue> &InVals) const {
1089
1090   // Assign locations to each value returned by this call.
1091   SmallVector<CCValAssign, 16> RVLocs;
1092   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1093                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1094   CCInfo.AnalyzeCallResult(Ins,
1095                            CCAssignFnForNode(CallConv, /* Return*/ true,
1096                                              isVarArg));
1097
1098   // Copy all of the result registers out of their specified physreg.
1099   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1100     CCValAssign VA = RVLocs[i];
1101
1102     SDValue Val;
1103     if (VA.needsCustom()) {
1104       // Handle f64 or half of a v2f64.
1105       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1106                                       InFlag);
1107       Chain = Lo.getValue(1);
1108       InFlag = Lo.getValue(2);
1109       VA = RVLocs[++i]; // skip ahead to next loc
1110       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1111                                       InFlag);
1112       Chain = Hi.getValue(1);
1113       InFlag = Hi.getValue(2);
1114       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1115
1116       if (VA.getLocVT() == MVT::v2f64) {
1117         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1118         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1119                           DAG.getConstant(0, MVT::i32));
1120
1121         VA = RVLocs[++i]; // skip ahead to next loc
1122         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1123         Chain = Lo.getValue(1);
1124         InFlag = Lo.getValue(2);
1125         VA = RVLocs[++i]; // skip ahead to next loc
1126         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1127         Chain = Hi.getValue(1);
1128         InFlag = Hi.getValue(2);
1129         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1130         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1131                           DAG.getConstant(1, MVT::i32));
1132       }
1133     } else {
1134       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1135                                InFlag);
1136       Chain = Val.getValue(1);
1137       InFlag = Val.getValue(2);
1138     }
1139
1140     switch (VA.getLocInfo()) {
1141     default: llvm_unreachable("Unknown loc info!");
1142     case CCValAssign::Full: break;
1143     case CCValAssign::BCvt:
1144       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1145       break;
1146     }
1147
1148     InVals.push_back(Val);
1149   }
1150
1151   return Chain;
1152 }
1153
1154 /// LowerMemOpCallTo - Store the argument to the stack.
1155 SDValue
1156 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1157                                     SDValue StackPtr, SDValue Arg,
1158                                     DebugLoc dl, SelectionDAG &DAG,
1159                                     const CCValAssign &VA,
1160                                     ISD::ArgFlagsTy Flags) const {
1161   unsigned LocMemOffset = VA.getLocMemOffset();
1162   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1163   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1164   return DAG.getStore(Chain, dl, Arg, PtrOff,
1165                       MachinePointerInfo::getStack(LocMemOffset),
1166                       false, false, 0);
1167 }
1168
1169 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1170                                          SDValue Chain, SDValue &Arg,
1171                                          RegsToPassVector &RegsToPass,
1172                                          CCValAssign &VA, CCValAssign &NextVA,
1173                                          SDValue &StackPtr,
1174                                          SmallVector<SDValue, 8> &MemOpChains,
1175                                          ISD::ArgFlagsTy Flags) const {
1176
1177   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1178                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1179   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1180
1181   if (NextVA.isRegLoc())
1182     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1183   else {
1184     assert(NextVA.isMemLoc());
1185     if (StackPtr.getNode() == 0)
1186       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1187
1188     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1189                                            dl, DAG, NextVA,
1190                                            Flags));
1191   }
1192 }
1193
1194 /// LowerCall - Lowering a call into a callseq_start <-
1195 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1196 /// nodes.
1197 SDValue
1198 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1199                              CallingConv::ID CallConv, bool isVarArg,
1200                              bool &isTailCall,
1201                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1202                              const SmallVectorImpl<SDValue> &OutVals,
1203                              const SmallVectorImpl<ISD::InputArg> &Ins,
1204                              DebugLoc dl, SelectionDAG &DAG,
1205                              SmallVectorImpl<SDValue> &InVals) const {
1206   MachineFunction &MF = DAG.getMachineFunction();
1207   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1208   bool IsSibCall = false;
1209   // Temporarily disable tail calls so things don't break.
1210   if (!EnableARMTailCalls)
1211     isTailCall = false;
1212   if (isTailCall) {
1213     // Check if it's really possible to do a tail call.
1214     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1215                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1216                                                    Outs, OutVals, Ins, DAG);
1217     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1218     // detected sibcalls.
1219     if (isTailCall) {
1220       ++NumTailCalls;
1221       IsSibCall = true;
1222     }
1223   }
1224
1225   // Analyze operands of the call, assigning locations to each operand.
1226   SmallVector<CCValAssign, 16> ArgLocs;
1227   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1228                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1229   CCInfo.AnalyzeCallOperands(Outs,
1230                              CCAssignFnForNode(CallConv, /* Return*/ false,
1231                                                isVarArg));
1232
1233   // Get a count of how many bytes are to be pushed on the stack.
1234   unsigned NumBytes = CCInfo.getNextStackOffset();
1235
1236   // For tail calls, memory operands are available in our caller's stack.
1237   if (IsSibCall)
1238     NumBytes = 0;
1239
1240   // Adjust the stack pointer for the new arguments...
1241   // These operations are automatically eliminated by the prolog/epilog pass
1242   if (!IsSibCall)
1243     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1244
1245   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1246
1247   RegsToPassVector RegsToPass;
1248   SmallVector<SDValue, 8> MemOpChains;
1249
1250   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1251   // of tail call optimization, arguments are handled later.
1252   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1253        i != e;
1254        ++i, ++realArgIdx) {
1255     CCValAssign &VA = ArgLocs[i];
1256     SDValue Arg = OutVals[realArgIdx];
1257     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1258     bool isByVal = Flags.isByVal();
1259
1260     // Promote the value if needed.
1261     switch (VA.getLocInfo()) {
1262     default: llvm_unreachable("Unknown loc info!");
1263     case CCValAssign::Full: break;
1264     case CCValAssign::SExt:
1265       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1266       break;
1267     case CCValAssign::ZExt:
1268       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1269       break;
1270     case CCValAssign::AExt:
1271       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1272       break;
1273     case CCValAssign::BCvt:
1274       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1275       break;
1276     }
1277
1278     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1279     if (VA.needsCustom()) {
1280       if (VA.getLocVT() == MVT::v2f64) {
1281         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1282                                   DAG.getConstant(0, MVT::i32));
1283         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1284                                   DAG.getConstant(1, MVT::i32));
1285
1286         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1287                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1288
1289         VA = ArgLocs[++i]; // skip ahead to next loc
1290         if (VA.isRegLoc()) {
1291           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1292                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1293         } else {
1294           assert(VA.isMemLoc());
1295
1296           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1297                                                  dl, DAG, VA, Flags));
1298         }
1299       } else {
1300         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1301                          StackPtr, MemOpChains, Flags);
1302       }
1303     } else if (VA.isRegLoc()) {
1304       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1305     } else if (isByVal) {
1306       assert(VA.isMemLoc());
1307       unsigned offset = 0;
1308
1309       // True if this byval aggregate will be split between registers
1310       // and memory.
1311       if (CCInfo.isFirstByValRegValid()) {
1312         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1313         unsigned int i, j;
1314         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1315           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1316           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1317           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1318                                      MachinePointerInfo(),
1319                                      false, false, 0);
1320           MemOpChains.push_back(Load.getValue(1));
1321           RegsToPass.push_back(std::make_pair(j, Load));
1322         }
1323         offset = ARM::R4 - CCInfo.getFirstByValReg();
1324         CCInfo.clearFirstByValReg();
1325       }
1326
1327       unsigned LocMemOffset = VA.getLocMemOffset();
1328       SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1329       SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1330                                 StkPtrOff);
1331       SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1332       SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1333       SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1334                                          MVT::i32);
1335       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1336                                           Flags.getByValAlign(),
1337                                           /*isVolatile=*/false,
1338                                           /*AlwaysInline=*/false,
1339                                           MachinePointerInfo(0),
1340                                           MachinePointerInfo(0)));
1341
1342     } else if (!IsSibCall) {
1343       assert(VA.isMemLoc());
1344
1345       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1346                                              dl, DAG, VA, Flags));
1347     }
1348   }
1349
1350   if (!MemOpChains.empty())
1351     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1352                         &MemOpChains[0], MemOpChains.size());
1353
1354   // Build a sequence of copy-to-reg nodes chained together with token chain
1355   // and flag operands which copy the outgoing args into the appropriate regs.
1356   SDValue InFlag;
1357   // Tail call byval lowering might overwrite argument registers so in case of
1358   // tail call optimization the copies to registers are lowered later.
1359   if (!isTailCall)
1360     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1361       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1362                                RegsToPass[i].second, InFlag);
1363       InFlag = Chain.getValue(1);
1364     }
1365
1366   // For tail calls lower the arguments to the 'real' stack slot.
1367   if (isTailCall) {
1368     // Force all the incoming stack arguments to be loaded from the stack
1369     // before any new outgoing arguments are stored to the stack, because the
1370     // outgoing stack slots may alias the incoming argument stack slots, and
1371     // the alias isn't otherwise explicit. This is slightly more conservative
1372     // than necessary, because it means that each store effectively depends
1373     // on every argument instead of just those arguments it would clobber.
1374
1375     // Do not flag preceding copytoreg stuff together with the following stuff.
1376     InFlag = SDValue();
1377     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1378       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1379                                RegsToPass[i].second, InFlag);
1380       InFlag = Chain.getValue(1);
1381     }
1382     InFlag =SDValue();
1383   }
1384
1385   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1386   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1387   // node so that legalize doesn't hack it.
1388   bool isDirect = false;
1389   bool isARMFunc = false;
1390   bool isLocalARMFunc = false;
1391   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1392
1393   if (EnableARMLongCalls) {
1394     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1395             && "long-calls with non-static relocation model!");
1396     // Handle a global address or an external symbol. If it's not one of
1397     // those, the target's already in a register, so we don't need to do
1398     // anything extra.
1399     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1400       const GlobalValue *GV = G->getGlobal();
1401       // Create a constant pool entry for the callee address
1402       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1403       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1404                                                            ARMPCLabelIndex,
1405                                                            ARMCP::CPValue, 0);
1406       // Get the address of the callee into a register
1407       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1408       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1409       Callee = DAG.getLoad(getPointerTy(), dl,
1410                            DAG.getEntryNode(), CPAddr,
1411                            MachinePointerInfo::getConstantPool(),
1412                            false, false, 0);
1413     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1414       const char *Sym = S->getSymbol();
1415
1416       // Create a constant pool entry for the callee address
1417       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1418       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1419                                                        Sym, ARMPCLabelIndex, 0);
1420       // Get the address of the callee into a register
1421       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1422       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1423       Callee = DAG.getLoad(getPointerTy(), dl,
1424                            DAG.getEntryNode(), CPAddr,
1425                            MachinePointerInfo::getConstantPool(),
1426                            false, false, 0);
1427     }
1428   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1429     const GlobalValue *GV = G->getGlobal();
1430     isDirect = true;
1431     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1432     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1433                    getTargetMachine().getRelocationModel() != Reloc::Static;
1434     isARMFunc = !Subtarget->isThumb() || isStub;
1435     // ARM call to a local ARM function is predicable.
1436     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1437     // tBX takes a register source operand.
1438     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1439       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1440       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1441                                                            ARMPCLabelIndex,
1442                                                            ARMCP::CPValue, 4);
1443       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1444       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1445       Callee = DAG.getLoad(getPointerTy(), dl,
1446                            DAG.getEntryNode(), CPAddr,
1447                            MachinePointerInfo::getConstantPool(),
1448                            false, false, 0);
1449       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1450       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1451                            getPointerTy(), Callee, PICLabel);
1452     } else {
1453       // On ELF targets for PIC code, direct calls should go through the PLT
1454       unsigned OpFlags = 0;
1455       if (Subtarget->isTargetELF() &&
1456                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1457         OpFlags = ARMII::MO_PLT;
1458       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1459     }
1460   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1461     isDirect = true;
1462     bool isStub = Subtarget->isTargetDarwin() &&
1463                   getTargetMachine().getRelocationModel() != Reloc::Static;
1464     isARMFunc = !Subtarget->isThumb() || isStub;
1465     // tBX takes a register source operand.
1466     const char *Sym = S->getSymbol();
1467     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1468       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1469       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1470                                                        Sym, ARMPCLabelIndex, 4);
1471       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1472       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1473       Callee = DAG.getLoad(getPointerTy(), dl,
1474                            DAG.getEntryNode(), CPAddr,
1475                            MachinePointerInfo::getConstantPool(),
1476                            false, false, 0);
1477       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1478       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1479                            getPointerTy(), Callee, PICLabel);
1480     } else {
1481       unsigned OpFlags = 0;
1482       // On ELF targets for PIC code, direct calls should go through the PLT
1483       if (Subtarget->isTargetELF() &&
1484                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1485         OpFlags = ARMII::MO_PLT;
1486       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1487     }
1488   }
1489
1490   // FIXME: handle tail calls differently.
1491   unsigned CallOpc;
1492   if (Subtarget->isThumb()) {
1493     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1494       CallOpc = ARMISD::CALL_NOLINK;
1495     else
1496       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1497   } else {
1498     CallOpc = (isDirect || Subtarget->hasV5TOps())
1499       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1500       : ARMISD::CALL_NOLINK;
1501   }
1502
1503   std::vector<SDValue> Ops;
1504   Ops.push_back(Chain);
1505   Ops.push_back(Callee);
1506
1507   // Add argument registers to the end of the list so that they are known live
1508   // into the call.
1509   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1510     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1511                                   RegsToPass[i].second.getValueType()));
1512
1513   if (InFlag.getNode())
1514     Ops.push_back(InFlag);
1515
1516   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1517   if (isTailCall)
1518     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1519
1520   // Returns a chain and a flag for retval copy to use.
1521   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1522   InFlag = Chain.getValue(1);
1523
1524   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1525                              DAG.getIntPtrConstant(0, true), InFlag);
1526   if (!Ins.empty())
1527     InFlag = Chain.getValue(1);
1528
1529   // Handle result values, copying them out of physregs into vregs that we
1530   // return.
1531   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1532                          dl, DAG, InVals);
1533 }
1534
1535 /// HandleByVal - Every parameter *after* a byval parameter is passed
1536 /// on the stack.  Remember the next parameter register to allocate,
1537 /// and then confiscate the rest of the parameter registers to insure
1538 /// this.
1539 void
1540 llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1541   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1542   assert((State->getCallOrPrologue() == Prologue ||
1543           State->getCallOrPrologue() == Call) &&
1544          "unhandled ParmContext");
1545   if ((!State->isFirstByValRegValid()) &&
1546       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1547     State->setFirstByValReg(reg);
1548     // At a call site, a byval parameter that is split between
1549     // registers and memory needs its size truncated here.  In a
1550     // function prologue, such byval parameters are reassembled in
1551     // memory, and are not truncated.
1552     if (State->getCallOrPrologue() == Call) {
1553       unsigned excess = 4 * (ARM::R4 - reg);
1554       assert(size >= excess && "expected larger existing stack allocation");
1555       size -= excess;
1556     }
1557   }
1558   // Confiscate any remaining parameter registers to preclude their
1559   // assignment to subsequent parameters.
1560   while (State->AllocateReg(GPRArgRegs, 4))
1561     ;
1562 }
1563
1564 /// MatchingStackOffset - Return true if the given stack call argument is
1565 /// already available in the same position (relatively) of the caller's
1566 /// incoming argument stack.
1567 static
1568 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1569                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1570                          const ARMInstrInfo *TII) {
1571   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1572   int FI = INT_MAX;
1573   if (Arg.getOpcode() == ISD::CopyFromReg) {
1574     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1575     if (!TargetRegisterInfo::isVirtualRegister(VR))
1576       return false;
1577     MachineInstr *Def = MRI->getVRegDef(VR);
1578     if (!Def)
1579       return false;
1580     if (!Flags.isByVal()) {
1581       if (!TII->isLoadFromStackSlot(Def, FI))
1582         return false;
1583     } else {
1584       return false;
1585     }
1586   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1587     if (Flags.isByVal())
1588       // ByVal argument is passed in as a pointer but it's now being
1589       // dereferenced. e.g.
1590       // define @foo(%struct.X* %A) {
1591       //   tail call @bar(%struct.X* byval %A)
1592       // }
1593       return false;
1594     SDValue Ptr = Ld->getBasePtr();
1595     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1596     if (!FINode)
1597       return false;
1598     FI = FINode->getIndex();
1599   } else
1600     return false;
1601
1602   assert(FI != INT_MAX);
1603   if (!MFI->isFixedObjectIndex(FI))
1604     return false;
1605   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1606 }
1607
1608 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1609 /// for tail call optimization. Targets which want to do tail call
1610 /// optimization should implement this function.
1611 bool
1612 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1613                                                      CallingConv::ID CalleeCC,
1614                                                      bool isVarArg,
1615                                                      bool isCalleeStructRet,
1616                                                      bool isCallerStructRet,
1617                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1618                                     const SmallVectorImpl<SDValue> &OutVals,
1619                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1620                                                      SelectionDAG& DAG) const {
1621   const Function *CallerF = DAG.getMachineFunction().getFunction();
1622   CallingConv::ID CallerCC = CallerF->getCallingConv();
1623   bool CCMatch = CallerCC == CalleeCC;
1624
1625   // Look for obvious safe cases to perform tail call optimization that do not
1626   // require ABI changes. This is what gcc calls sibcall.
1627
1628   // Do not sibcall optimize vararg calls unless the call site is not passing
1629   // any arguments.
1630   if (isVarArg && !Outs.empty())
1631     return false;
1632
1633   // Also avoid sibcall optimization if either caller or callee uses struct
1634   // return semantics.
1635   if (isCalleeStructRet || isCallerStructRet)
1636     return false;
1637
1638   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1639   // emitEpilogue is not ready for them.
1640   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1641   // LR.  This means if we need to reload LR, it takes an extra instructions,
1642   // which outweighs the value of the tail call; but here we don't know yet
1643   // whether LR is going to be used.  Probably the right approach is to
1644   // generate the tail call here and turn it back into CALL/RET in
1645   // emitEpilogue if LR is used.
1646
1647   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1648   // but we need to make sure there are enough registers; the only valid
1649   // registers are the 4 used for parameters.  We don't currently do this
1650   // case.
1651   if (Subtarget->isThumb1Only())
1652     return false;
1653
1654   // If the calling conventions do not match, then we'd better make sure the
1655   // results are returned in the same way as what the caller expects.
1656   if (!CCMatch) {
1657     SmallVector<CCValAssign, 16> RVLocs1;
1658     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1659                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1660     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1661
1662     SmallVector<CCValAssign, 16> RVLocs2;
1663     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1664                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1665     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1666
1667     if (RVLocs1.size() != RVLocs2.size())
1668       return false;
1669     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1670       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1671         return false;
1672       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1673         return false;
1674       if (RVLocs1[i].isRegLoc()) {
1675         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1676           return false;
1677       } else {
1678         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1679           return false;
1680       }
1681     }
1682   }
1683
1684   // If the callee takes no arguments then go on to check the results of the
1685   // call.
1686   if (!Outs.empty()) {
1687     // Check if stack adjustment is needed. For now, do not do this if any
1688     // argument is passed on the stack.
1689     SmallVector<CCValAssign, 16> ArgLocs;
1690     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1691                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1692     CCInfo.AnalyzeCallOperands(Outs,
1693                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1694     if (CCInfo.getNextStackOffset()) {
1695       MachineFunction &MF = DAG.getMachineFunction();
1696
1697       // Check if the arguments are already laid out in the right way as
1698       // the caller's fixed stack objects.
1699       MachineFrameInfo *MFI = MF.getFrameInfo();
1700       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1701       const ARMInstrInfo *TII =
1702         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1703       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1704            i != e;
1705            ++i, ++realArgIdx) {
1706         CCValAssign &VA = ArgLocs[i];
1707         EVT RegVT = VA.getLocVT();
1708         SDValue Arg = OutVals[realArgIdx];
1709         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1710         if (VA.getLocInfo() == CCValAssign::Indirect)
1711           return false;
1712         if (VA.needsCustom()) {
1713           // f64 and vector types are split into multiple registers or
1714           // register/stack-slot combinations.  The types will not match
1715           // the registers; give up on memory f64 refs until we figure
1716           // out what to do about this.
1717           if (!VA.isRegLoc())
1718             return false;
1719           if (!ArgLocs[++i].isRegLoc())
1720             return false;
1721           if (RegVT == MVT::v2f64) {
1722             if (!ArgLocs[++i].isRegLoc())
1723               return false;
1724             if (!ArgLocs[++i].isRegLoc())
1725               return false;
1726           }
1727         } else if (!VA.isRegLoc()) {
1728           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1729                                    MFI, MRI, TII))
1730             return false;
1731         }
1732       }
1733     }
1734   }
1735
1736   return true;
1737 }
1738
1739 SDValue
1740 ARMTargetLowering::LowerReturn(SDValue Chain,
1741                                CallingConv::ID CallConv, bool isVarArg,
1742                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1743                                const SmallVectorImpl<SDValue> &OutVals,
1744                                DebugLoc dl, SelectionDAG &DAG) const {
1745
1746   // CCValAssign - represent the assignment of the return value to a location.
1747   SmallVector<CCValAssign, 16> RVLocs;
1748
1749   // CCState - Info about the registers and stack slots.
1750   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1751                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1752
1753   // Analyze outgoing return values.
1754   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1755                                                isVarArg));
1756
1757   // If this is the first return lowered for this function, add
1758   // the regs to the liveout set for the function.
1759   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1760     for (unsigned i = 0; i != RVLocs.size(); ++i)
1761       if (RVLocs[i].isRegLoc())
1762         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1763   }
1764
1765   SDValue Flag;
1766
1767   // Copy the result values into the output registers.
1768   for (unsigned i = 0, realRVLocIdx = 0;
1769        i != RVLocs.size();
1770        ++i, ++realRVLocIdx) {
1771     CCValAssign &VA = RVLocs[i];
1772     assert(VA.isRegLoc() && "Can only return in registers!");
1773
1774     SDValue Arg = OutVals[realRVLocIdx];
1775
1776     switch (VA.getLocInfo()) {
1777     default: llvm_unreachable("Unknown loc info!");
1778     case CCValAssign::Full: break;
1779     case CCValAssign::BCvt:
1780       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1781       break;
1782     }
1783
1784     if (VA.needsCustom()) {
1785       if (VA.getLocVT() == MVT::v2f64) {
1786         // Extract the first half and return it in two registers.
1787         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1788                                    DAG.getConstant(0, MVT::i32));
1789         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1790                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1791
1792         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1793         Flag = Chain.getValue(1);
1794         VA = RVLocs[++i]; // skip ahead to next loc
1795         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1796                                  HalfGPRs.getValue(1), Flag);
1797         Flag = Chain.getValue(1);
1798         VA = RVLocs[++i]; // skip ahead to next loc
1799
1800         // Extract the 2nd half and fall through to handle it as an f64 value.
1801         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1802                           DAG.getConstant(1, MVT::i32));
1803       }
1804       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1805       // available.
1806       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1807                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1808       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1809       Flag = Chain.getValue(1);
1810       VA = RVLocs[++i]; // skip ahead to next loc
1811       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1812                                Flag);
1813     } else
1814       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1815
1816     // Guarantee that all emitted copies are
1817     // stuck together, avoiding something bad.
1818     Flag = Chain.getValue(1);
1819   }
1820
1821   SDValue result;
1822   if (Flag.getNode())
1823     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1824   else // Return Void
1825     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1826
1827   return result;
1828 }
1829
1830 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1831   if (N->getNumValues() != 1)
1832     return false;
1833   if (!N->hasNUsesOfValue(1, 0))
1834     return false;
1835
1836   unsigned NumCopies = 0;
1837   SDNode* Copies[2];
1838   SDNode *Use = *N->use_begin();
1839   if (Use->getOpcode() == ISD::CopyToReg) {
1840     Copies[NumCopies++] = Use;
1841   } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1842     // f64 returned in a pair of GPRs.
1843     for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1844          UI != UE; ++UI) {
1845       if (UI->getOpcode() != ISD::CopyToReg)
1846         return false;
1847       Copies[UI.getUse().getResNo()] = *UI;
1848       ++NumCopies;
1849     }
1850   } else if (Use->getOpcode() == ISD::BITCAST) {
1851     // f32 returned in a single GPR.
1852     if (!Use->hasNUsesOfValue(1, 0))
1853       return false;
1854     Use = *Use->use_begin();
1855     if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1856       return false;
1857     Copies[NumCopies++] = Use;
1858   } else {
1859     return false;
1860   }
1861
1862   if (NumCopies != 1 && NumCopies != 2)
1863     return false;
1864
1865   bool HasRet = false;
1866   for (unsigned i = 0; i < NumCopies; ++i) {
1867     SDNode *Copy = Copies[i];
1868     for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1869          UI != UE; ++UI) {
1870       if (UI->getOpcode() == ISD::CopyToReg) {
1871         SDNode *Use = *UI;
1872         if (Use == Copies[0] || Use == Copies[1])
1873           continue;
1874         return false;
1875       }
1876       if (UI->getOpcode() != ARMISD::RET_FLAG)
1877         return false;
1878       HasRet = true;
1879     }
1880   }
1881
1882   return HasRet;
1883 }
1884
1885 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1886   if (!EnableARMTailCalls)
1887     return false;
1888
1889   if (!CI->isTailCall())
1890     return false;
1891
1892   return !Subtarget->isThumb1Only();
1893 }
1894
1895 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1896 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1897 // one of the above mentioned nodes. It has to be wrapped because otherwise
1898 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1899 // be used to form addressing mode. These wrapped nodes will be selected
1900 // into MOVi.
1901 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1902   EVT PtrVT = Op.getValueType();
1903   // FIXME there is no actual debug info here
1904   DebugLoc dl = Op.getDebugLoc();
1905   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1906   SDValue Res;
1907   if (CP->isMachineConstantPoolEntry())
1908     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1909                                     CP->getAlignment());
1910   else
1911     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1912                                     CP->getAlignment());
1913   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1914 }
1915
1916 unsigned ARMTargetLowering::getJumpTableEncoding() const {
1917   return MachineJumpTableInfo::EK_Inline;
1918 }
1919
1920 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
1921                                              SelectionDAG &DAG) const {
1922   MachineFunction &MF = DAG.getMachineFunction();
1923   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1924   unsigned ARMPCLabelIndex = 0;
1925   DebugLoc DL = Op.getDebugLoc();
1926   EVT PtrVT = getPointerTy();
1927   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1928   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1929   SDValue CPAddr;
1930   if (RelocM == Reloc::Static) {
1931     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
1932   } else {
1933     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1934     ARMPCLabelIndex = AFI->createPICLabelUId();
1935     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(BA, ARMPCLabelIndex,
1936                                                          ARMCP::CPBlockAddress,
1937                                                          PCAdj);
1938     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1939   }
1940   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
1941   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
1942                                MachinePointerInfo::getConstantPool(),
1943                                false, false, 0);
1944   if (RelocM == Reloc::Static)
1945     return Result;
1946   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1947   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
1948 }
1949
1950 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1951 SDValue
1952 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1953                                                  SelectionDAG &DAG) const {
1954   DebugLoc dl = GA->getDebugLoc();
1955   EVT PtrVT = getPointerTy();
1956   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1957   MachineFunction &MF = DAG.getMachineFunction();
1958   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1959   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1960   ARMConstantPoolValue *CPV =
1961     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1962                              ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
1963   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1964   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1965   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
1966                          MachinePointerInfo::getConstantPool(),
1967                          false, false, 0);
1968   SDValue Chain = Argument.getValue(1);
1969
1970   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1971   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1972
1973   // call __tls_get_addr.
1974   ArgListTy Args;
1975   ArgListEntry Entry;
1976   Entry.Node = Argument;
1977   Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1978   Args.push_back(Entry);
1979   // FIXME: is there useful debug info available here?
1980   std::pair<SDValue, SDValue> CallResult =
1981     LowerCallTo(Chain, (const Type *) Type::getInt32Ty(*DAG.getContext()),
1982                 false, false, false, false,
1983                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1984                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1985   return CallResult.first;
1986 }
1987
1988 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1989 // "local exec" model.
1990 SDValue
1991 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1992                                         SelectionDAG &DAG) const {
1993   const GlobalValue *GV = GA->getGlobal();
1994   DebugLoc dl = GA->getDebugLoc();
1995   SDValue Offset;
1996   SDValue Chain = DAG.getEntryNode();
1997   EVT PtrVT = getPointerTy();
1998   // Get the Thread Pointer
1999   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2000
2001   if (GV->isDeclaration()) {
2002     MachineFunction &MF = DAG.getMachineFunction();
2003     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2004     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2005     // Initial exec model.
2006     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2007     ARMConstantPoolValue *CPV =
2008       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
2009                                ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF, true);
2010     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2011     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2012     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2013                          MachinePointerInfo::getConstantPool(),
2014                          false, false, 0);
2015     Chain = Offset.getValue(1);
2016
2017     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2018     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2019
2020     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2021                          MachinePointerInfo::getConstantPool(),
2022                          false, false, 0);
2023   } else {
2024     // local exec model
2025     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMCP::TPOFF);
2026     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2027     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2028     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2029                          MachinePointerInfo::getConstantPool(),
2030                          false, false, 0);
2031   }
2032
2033   // The address of the thread local variable is the add of the thread
2034   // pointer with the offset of the variable.
2035   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2036 }
2037
2038 SDValue
2039 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2040   // TODO: implement the "local dynamic" model
2041   assert(Subtarget->isTargetELF() &&
2042          "TLS not implemented for non-ELF targets");
2043   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2044   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2045   // otherwise use the "Local Exec" TLS Model
2046   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2047     return LowerToTLSGeneralDynamicModel(GA, DAG);
2048   else
2049     return LowerToTLSExecModels(GA, DAG);
2050 }
2051
2052 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2053                                                  SelectionDAG &DAG) const {
2054   EVT PtrVT = getPointerTy();
2055   DebugLoc dl = Op.getDebugLoc();
2056   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2057   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2058   if (RelocM == Reloc::PIC_) {
2059     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2060     ARMConstantPoolValue *CPV =
2061       new ARMConstantPoolValue(GV, UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2062     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2063     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2064     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2065                                  CPAddr,
2066                                  MachinePointerInfo::getConstantPool(),
2067                                  false, false, 0);
2068     SDValue Chain = Result.getValue(1);
2069     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2070     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2071     if (!UseGOTOFF)
2072       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2073                            MachinePointerInfo::getGOT(), false, false, 0);
2074     return Result;
2075   }
2076
2077   // If we have T2 ops, we can materialize the address directly via movt/movw
2078   // pair. This is always cheaper.
2079   if (Subtarget->useMovt()) {
2080     ++NumMovwMovt;
2081     // FIXME: Once remat is capable of dealing with instructions with register
2082     // operands, expand this into two nodes.
2083     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2084                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2085   } else {
2086     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2087     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2088     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2089                        MachinePointerInfo::getConstantPool(),
2090                        false, false, 0);
2091   }
2092 }
2093
2094 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2095                                                     SelectionDAG &DAG) const {
2096   EVT PtrVT = getPointerTy();
2097   DebugLoc dl = Op.getDebugLoc();
2098   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2099   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2100   MachineFunction &MF = DAG.getMachineFunction();
2101   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2102
2103   // FIXME: Enable this for static codegen when tool issues are fixed.
2104   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2105     ++NumMovwMovt;
2106     // FIXME: Once remat is capable of dealing with instructions with register
2107     // operands, expand this into two nodes.
2108     if (RelocM == Reloc::Static)
2109       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2110                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2111
2112     unsigned Wrapper = (RelocM == Reloc::PIC_)
2113       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2114     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2115                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2116     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2117       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2118                            MachinePointerInfo::getGOT(), false, false, 0);
2119     return Result;
2120   }
2121
2122   unsigned ARMPCLabelIndex = 0;
2123   SDValue CPAddr;
2124   if (RelocM == Reloc::Static) {
2125     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2126   } else {
2127     ARMPCLabelIndex = AFI->createPICLabelUId();
2128     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2129     ARMConstantPoolValue *CPV =
2130       new ARMConstantPoolValue(GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj);
2131     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2132   }
2133   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2134
2135   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2136                                MachinePointerInfo::getConstantPool(),
2137                                false, false, 0);
2138   SDValue Chain = Result.getValue(1);
2139
2140   if (RelocM == Reloc::PIC_) {
2141     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2142     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2143   }
2144
2145   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2146     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2147                          false, false, 0);
2148
2149   return Result;
2150 }
2151
2152 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2153                                                     SelectionDAG &DAG) const {
2154   assert(Subtarget->isTargetELF() &&
2155          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2156   MachineFunction &MF = DAG.getMachineFunction();
2157   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2158   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2159   EVT PtrVT = getPointerTy();
2160   DebugLoc dl = Op.getDebugLoc();
2161   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2162   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
2163                                                        "_GLOBAL_OFFSET_TABLE_",
2164                                                        ARMPCLabelIndex, PCAdj);
2165   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2166   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2167   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2168                                MachinePointerInfo::getConstantPool(),
2169                                false, false, 0);
2170   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2171   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2172 }
2173
2174 SDValue
2175 ARMTargetLowering::LowerEH_SJLJ_DISPATCHSETUP(SDValue Op, SelectionDAG &DAG)
2176   const {
2177   DebugLoc dl = Op.getDebugLoc();
2178   return DAG.getNode(ARMISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
2179                      Op.getOperand(0), Op.getOperand(1));
2180 }
2181
2182 SDValue
2183 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2184   DebugLoc dl = Op.getDebugLoc();
2185   SDValue Val = DAG.getConstant(0, MVT::i32);
2186   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(0),
2187                      Op.getOperand(1), Val);
2188 }
2189
2190 SDValue
2191 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2192   DebugLoc dl = Op.getDebugLoc();
2193   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2194                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2195 }
2196
2197 SDValue
2198 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2199                                           const ARMSubtarget *Subtarget) const {
2200   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2201   DebugLoc dl = Op.getDebugLoc();
2202   switch (IntNo) {
2203   default: return SDValue();    // Don't custom lower most intrinsics.
2204   case Intrinsic::arm_thread_pointer: {
2205     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2206     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2207   }
2208   case Intrinsic::eh_sjlj_lsda: {
2209     MachineFunction &MF = DAG.getMachineFunction();
2210     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2211     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2212     EVT PtrVT = getPointerTy();
2213     DebugLoc dl = Op.getDebugLoc();
2214     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2215     SDValue CPAddr;
2216     unsigned PCAdj = (RelocM != Reloc::PIC_)
2217       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2218     ARMConstantPoolValue *CPV =
2219       new ARMConstantPoolValue(MF.getFunction(), ARMPCLabelIndex,
2220                                ARMCP::CPLSDA, PCAdj);
2221     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2222     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2223     SDValue Result =
2224       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2225                   MachinePointerInfo::getConstantPool(),
2226                   false, false, 0);
2227
2228     if (RelocM == Reloc::PIC_) {
2229       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2230       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2231     }
2232     return Result;
2233   }
2234   case Intrinsic::arm_neon_vmulls:
2235   case Intrinsic::arm_neon_vmullu: {
2236     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2237       ? ARMISD::VMULLs : ARMISD::VMULLu;
2238     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2239                        Op.getOperand(1), Op.getOperand(2));
2240   }
2241   }
2242 }
2243
2244 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2245                                const ARMSubtarget *Subtarget) {
2246   DebugLoc dl = Op.getDebugLoc();
2247   if (!Subtarget->hasDataBarrier()) {
2248     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2249     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2250     // here.
2251     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2252            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2253     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2254                        DAG.getConstant(0, MVT::i32));
2255   }
2256
2257   SDValue Op5 = Op.getOperand(5);
2258   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2259   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2260   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2261   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2262
2263   ARM_MB::MemBOpt DMBOpt;
2264   if (isDeviceBarrier)
2265     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2266   else
2267     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2268   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2269                      DAG.getConstant(DMBOpt, MVT::i32));
2270 }
2271
2272 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2273                              const ARMSubtarget *Subtarget) {
2274   // ARM pre v5TE and Thumb1 does not have preload instructions.
2275   if (!(Subtarget->isThumb2() ||
2276         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2277     // Just preserve the chain.
2278     return Op.getOperand(0);
2279
2280   DebugLoc dl = Op.getDebugLoc();
2281   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2282   if (!isRead &&
2283       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2284     // ARMv7 with MP extension has PLDW.
2285     return Op.getOperand(0);
2286
2287   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2288   if (Subtarget->isThumb()) {
2289     // Invert the bits.
2290     isRead = ~isRead & 1;
2291     isData = ~isData & 1;
2292   }
2293
2294   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2295                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2296                      DAG.getConstant(isData, MVT::i32));
2297 }
2298
2299 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2300   MachineFunction &MF = DAG.getMachineFunction();
2301   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2302
2303   // vastart just stores the address of the VarArgsFrameIndex slot into the
2304   // memory location argument.
2305   DebugLoc dl = Op.getDebugLoc();
2306   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2307   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2308   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2309   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2310                       MachinePointerInfo(SV), false, false, 0);
2311 }
2312
2313 SDValue
2314 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2315                                         SDValue &Root, SelectionDAG &DAG,
2316                                         DebugLoc dl) const {
2317   MachineFunction &MF = DAG.getMachineFunction();
2318   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2319
2320   TargetRegisterClass *RC;
2321   if (AFI->isThumb1OnlyFunction())
2322     RC = ARM::tGPRRegisterClass;
2323   else
2324     RC = ARM::GPRRegisterClass;
2325
2326   // Transform the arguments stored in physical registers into virtual ones.
2327   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2328   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2329
2330   SDValue ArgValue2;
2331   if (NextVA.isMemLoc()) {
2332     MachineFrameInfo *MFI = MF.getFrameInfo();
2333     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2334
2335     // Create load node to retrieve arguments from the stack.
2336     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2337     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2338                             MachinePointerInfo::getFixedStack(FI),
2339                             false, false, 0);
2340   } else {
2341     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2342     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2343   }
2344
2345   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2346 }
2347
2348 void
2349 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2350                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2351   const {
2352   unsigned NumGPRs;
2353   if (CCInfo.isFirstByValRegValid())
2354     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2355   else {
2356     unsigned int firstUnalloced;
2357     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2358                                                 sizeof(GPRArgRegs) /
2359                                                 sizeof(GPRArgRegs[0]));
2360     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2361   }
2362
2363   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2364   VARegSize = NumGPRs * 4;
2365   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2366 }
2367
2368 // The remaining GPRs hold either the beginning of variable-argument
2369 // data, or the beginning of an aggregate passed by value (usuall
2370 // byval).  Either way, we allocate stack slots adjacent to the data
2371 // provided by our caller, and store the unallocated registers there.
2372 // If this is a variadic function, the va_list pointer will begin with
2373 // these values; otherwise, this reassembles a (byval) structure that
2374 // was split between registers and memory.
2375 void
2376 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2377                                         DebugLoc dl, SDValue &Chain,
2378                                         unsigned ArgOffset) const {
2379   MachineFunction &MF = DAG.getMachineFunction();
2380   MachineFrameInfo *MFI = MF.getFrameInfo();
2381   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2382   unsigned firstRegToSaveIndex;
2383   if (CCInfo.isFirstByValRegValid())
2384     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2385   else {
2386     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2387       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2388   }
2389
2390   unsigned VARegSize, VARegSaveSize;
2391   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2392   if (VARegSaveSize) {
2393     // If this function is vararg, store any remaining integer argument regs
2394     // to their spots on the stack so that they may be loaded by deferencing
2395     // the result of va_next.
2396     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2397     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2398                                                      ArgOffset + VARegSaveSize
2399                                                      - VARegSize,
2400                                                      false));
2401     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2402                                     getPointerTy());
2403
2404     SmallVector<SDValue, 4> MemOps;
2405     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2406       TargetRegisterClass *RC;
2407       if (AFI->isThumb1OnlyFunction())
2408         RC = ARM::tGPRRegisterClass;
2409       else
2410         RC = ARM::GPRRegisterClass;
2411
2412       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2413       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2414       SDValue Store =
2415         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2416                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2417                      false, false, 0);
2418       MemOps.push_back(Store);
2419       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2420                         DAG.getConstant(4, getPointerTy()));
2421     }
2422     if (!MemOps.empty())
2423       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2424                           &MemOps[0], MemOps.size());
2425   } else
2426     // This will point to the next argument passed via stack.
2427     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2428 }
2429
2430 SDValue
2431 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2432                                         CallingConv::ID CallConv, bool isVarArg,
2433                                         const SmallVectorImpl<ISD::InputArg>
2434                                           &Ins,
2435                                         DebugLoc dl, SelectionDAG &DAG,
2436                                         SmallVectorImpl<SDValue> &InVals)
2437                                           const {
2438   MachineFunction &MF = DAG.getMachineFunction();
2439   MachineFrameInfo *MFI = MF.getFrameInfo();
2440
2441   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2442
2443   // Assign locations to all of the incoming arguments.
2444   SmallVector<CCValAssign, 16> ArgLocs;
2445   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2446                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2447   CCInfo.AnalyzeFormalArguments(Ins,
2448                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2449                                                   isVarArg));
2450
2451   SmallVector<SDValue, 16> ArgValues;
2452   int lastInsIndex = -1;
2453
2454   SDValue ArgValue;
2455   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2456     CCValAssign &VA = ArgLocs[i];
2457
2458     // Arguments stored in registers.
2459     if (VA.isRegLoc()) {
2460       EVT RegVT = VA.getLocVT();
2461
2462       if (VA.needsCustom()) {
2463         // f64 and vector types are split up into multiple registers or
2464         // combinations of registers and stack slots.
2465         if (VA.getLocVT() == MVT::v2f64) {
2466           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2467                                                    Chain, DAG, dl);
2468           VA = ArgLocs[++i]; // skip ahead to next loc
2469           SDValue ArgValue2;
2470           if (VA.isMemLoc()) {
2471             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2472             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2473             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2474                                     MachinePointerInfo::getFixedStack(FI),
2475                                     false, false, 0);
2476           } else {
2477             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2478                                              Chain, DAG, dl);
2479           }
2480           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2481           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2482                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2483           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2484                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2485         } else
2486           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2487
2488       } else {
2489         TargetRegisterClass *RC;
2490
2491         if (RegVT == MVT::f32)
2492           RC = ARM::SPRRegisterClass;
2493         else if (RegVT == MVT::f64)
2494           RC = ARM::DPRRegisterClass;
2495         else if (RegVT == MVT::v2f64)
2496           RC = ARM::QPRRegisterClass;
2497         else if (RegVT == MVT::i32)
2498           RC = (AFI->isThumb1OnlyFunction() ?
2499                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2500         else
2501           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2502
2503         // Transform the arguments in physical registers into virtual ones.
2504         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2505         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2506       }
2507
2508       // If this is an 8 or 16-bit value, it is really passed promoted
2509       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2510       // truncate to the right size.
2511       switch (VA.getLocInfo()) {
2512       default: llvm_unreachable("Unknown loc info!");
2513       case CCValAssign::Full: break;
2514       case CCValAssign::BCvt:
2515         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2516         break;
2517       case CCValAssign::SExt:
2518         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2519                                DAG.getValueType(VA.getValVT()));
2520         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2521         break;
2522       case CCValAssign::ZExt:
2523         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2524                                DAG.getValueType(VA.getValVT()));
2525         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2526         break;
2527       }
2528
2529       InVals.push_back(ArgValue);
2530
2531     } else { // VA.isRegLoc()
2532
2533       // sanity check
2534       assert(VA.isMemLoc());
2535       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2536
2537       int index = ArgLocs[i].getValNo();
2538
2539       // Some Ins[] entries become multiple ArgLoc[] entries.
2540       // Process them only once.
2541       if (index != lastInsIndex)
2542         {
2543           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2544           // FIXME: For now, all byval parameter objects are marked mutable.
2545           // This can be changed with more analysis.
2546           // In case of tail call optimization mark all arguments mutable.
2547           // Since they could be overwritten by lowering of arguments in case of
2548           // a tail call.
2549           if (Flags.isByVal()) {
2550             unsigned VARegSize, VARegSaveSize;
2551             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2552             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2553             unsigned Bytes = Flags.getByValSize() - VARegSize;
2554             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2555             int FI = MFI->CreateFixedObject(Bytes,
2556                                             VA.getLocMemOffset(), false);
2557             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2558           } else {
2559             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2560                                             VA.getLocMemOffset(), true);
2561
2562             // Create load nodes to retrieve arguments from the stack.
2563             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2564             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2565                                          MachinePointerInfo::getFixedStack(FI),
2566                                          false, false, 0));
2567           }
2568           lastInsIndex = index;
2569         }
2570     }
2571   }
2572
2573   // varargs
2574   if (isVarArg)
2575     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2576
2577   return Chain;
2578 }
2579
2580 /// isFloatingPointZero - Return true if this is +0.0.
2581 static bool isFloatingPointZero(SDValue Op) {
2582   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2583     return CFP->getValueAPF().isPosZero();
2584   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2585     // Maybe this has already been legalized into the constant pool?
2586     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2587       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2588       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2589         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2590           return CFP->getValueAPF().isPosZero();
2591     }
2592   }
2593   return false;
2594 }
2595
2596 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2597 /// the given operands.
2598 SDValue
2599 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2600                              SDValue &ARMcc, SelectionDAG &DAG,
2601                              DebugLoc dl) const {
2602   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2603     unsigned C = RHSC->getZExtValue();
2604     if (!isLegalICmpImmediate(C)) {
2605       // Constant does not fit, try adjusting it by one?
2606       switch (CC) {
2607       default: break;
2608       case ISD::SETLT:
2609       case ISD::SETGE:
2610         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2611           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2612           RHS = DAG.getConstant(C-1, MVT::i32);
2613         }
2614         break;
2615       case ISD::SETULT:
2616       case ISD::SETUGE:
2617         if (C != 0 && isLegalICmpImmediate(C-1)) {
2618           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2619           RHS = DAG.getConstant(C-1, MVT::i32);
2620         }
2621         break;
2622       case ISD::SETLE:
2623       case ISD::SETGT:
2624         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2625           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2626           RHS = DAG.getConstant(C+1, MVT::i32);
2627         }
2628         break;
2629       case ISD::SETULE:
2630       case ISD::SETUGT:
2631         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2632           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2633           RHS = DAG.getConstant(C+1, MVT::i32);
2634         }
2635         break;
2636       }
2637     }
2638   }
2639
2640   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2641   ARMISD::NodeType CompareType;
2642   switch (CondCode) {
2643   default:
2644     CompareType = ARMISD::CMP;
2645     break;
2646   case ARMCC::EQ:
2647   case ARMCC::NE:
2648     // Uses only Z Flag
2649     CompareType = ARMISD::CMPZ;
2650     break;
2651   }
2652   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2653   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2654 }
2655
2656 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2657 SDValue
2658 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2659                              DebugLoc dl) const {
2660   SDValue Cmp;
2661   if (!isFloatingPointZero(RHS))
2662     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2663   else
2664     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2665   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2666 }
2667
2668 /// duplicateCmp - Glue values can have only one use, so this function
2669 /// duplicates a comparison node.
2670 SDValue
2671 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2672   unsigned Opc = Cmp.getOpcode();
2673   DebugLoc DL = Cmp.getDebugLoc();
2674   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2675     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2676
2677   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2678   Cmp = Cmp.getOperand(0);
2679   Opc = Cmp.getOpcode();
2680   if (Opc == ARMISD::CMPFP)
2681     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2682   else {
2683     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2684     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2685   }
2686   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2687 }
2688
2689 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2690   SDValue Cond = Op.getOperand(0);
2691   SDValue SelectTrue = Op.getOperand(1);
2692   SDValue SelectFalse = Op.getOperand(2);
2693   DebugLoc dl = Op.getDebugLoc();
2694
2695   // Convert:
2696   //
2697   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2698   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2699   //
2700   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2701     const ConstantSDNode *CMOVTrue =
2702       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2703     const ConstantSDNode *CMOVFalse =
2704       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2705
2706     if (CMOVTrue && CMOVFalse) {
2707       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2708       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2709
2710       SDValue True;
2711       SDValue False;
2712       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2713         True = SelectTrue;
2714         False = SelectFalse;
2715       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2716         True = SelectFalse;
2717         False = SelectTrue;
2718       }
2719
2720       if (True.getNode() && False.getNode()) {
2721         EVT VT = Op.getValueType();
2722         SDValue ARMcc = Cond.getOperand(2);
2723         SDValue CCR = Cond.getOperand(3);
2724         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2725         assert(True.getValueType() == VT);
2726         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2727       }
2728     }
2729   }
2730
2731   return DAG.getSelectCC(dl, Cond,
2732                          DAG.getConstant(0, Cond.getValueType()),
2733                          SelectTrue, SelectFalse, ISD::SETNE);
2734 }
2735
2736 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2737   EVT VT = Op.getValueType();
2738   SDValue LHS = Op.getOperand(0);
2739   SDValue RHS = Op.getOperand(1);
2740   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2741   SDValue TrueVal = Op.getOperand(2);
2742   SDValue FalseVal = Op.getOperand(3);
2743   DebugLoc dl = Op.getDebugLoc();
2744
2745   if (LHS.getValueType() == MVT::i32) {
2746     SDValue ARMcc;
2747     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2748     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2749     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2750   }
2751
2752   ARMCC::CondCodes CondCode, CondCode2;
2753   FPCCToARMCC(CC, CondCode, CondCode2);
2754
2755   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2756   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2757   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2758   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2759                                ARMcc, CCR, Cmp);
2760   if (CondCode2 != ARMCC::AL) {
2761     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2762     // FIXME: Needs another CMP because flag can have but one use.
2763     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2764     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2765                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2766   }
2767   return Result;
2768 }
2769
2770 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2771 /// to morph to an integer compare sequence.
2772 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2773                            const ARMSubtarget *Subtarget) {
2774   SDNode *N = Op.getNode();
2775   if (!N->hasOneUse())
2776     // Otherwise it requires moving the value from fp to integer registers.
2777     return false;
2778   if (!N->getNumValues())
2779     return false;
2780   EVT VT = Op.getValueType();
2781   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2782     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2783     // vmrs are very slow, e.g. cortex-a8.
2784     return false;
2785
2786   if (isFloatingPointZero(Op)) {
2787     SeenZero = true;
2788     return true;
2789   }
2790   return ISD::isNormalLoad(N);
2791 }
2792
2793 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2794   if (isFloatingPointZero(Op))
2795     return DAG.getConstant(0, MVT::i32);
2796
2797   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2798     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2799                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2800                        Ld->isVolatile(), Ld->isNonTemporal(),
2801                        Ld->getAlignment());
2802
2803   llvm_unreachable("Unknown VFP cmp argument!");
2804 }
2805
2806 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2807                            SDValue &RetVal1, SDValue &RetVal2) {
2808   if (isFloatingPointZero(Op)) {
2809     RetVal1 = DAG.getConstant(0, MVT::i32);
2810     RetVal2 = DAG.getConstant(0, MVT::i32);
2811     return;
2812   }
2813
2814   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2815     SDValue Ptr = Ld->getBasePtr();
2816     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2817                           Ld->getChain(), Ptr,
2818                           Ld->getPointerInfo(),
2819                           Ld->isVolatile(), Ld->isNonTemporal(),
2820                           Ld->getAlignment());
2821
2822     EVT PtrType = Ptr.getValueType();
2823     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2824     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2825                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2826     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2827                           Ld->getChain(), NewPtr,
2828                           Ld->getPointerInfo().getWithOffset(4),
2829                           Ld->isVolatile(), Ld->isNonTemporal(),
2830                           NewAlign);
2831     return;
2832   }
2833
2834   llvm_unreachable("Unknown VFP cmp argument!");
2835 }
2836
2837 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2838 /// f32 and even f64 comparisons to integer ones.
2839 SDValue
2840 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2841   SDValue Chain = Op.getOperand(0);
2842   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2843   SDValue LHS = Op.getOperand(2);
2844   SDValue RHS = Op.getOperand(3);
2845   SDValue Dest = Op.getOperand(4);
2846   DebugLoc dl = Op.getDebugLoc();
2847
2848   bool SeenZero = false;
2849   if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2850       canChangeToInt(RHS, SeenZero, Subtarget) &&
2851       // If one of the operand is zero, it's safe to ignore the NaN case since
2852       // we only care about equality comparisons.
2853       (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2854     // If unsafe fp math optimization is enabled and there are no other uses of
2855     // the CMP operands, and the condition code is EQ or NE, we can optimize it
2856     // to an integer comparison.
2857     if (CC == ISD::SETOEQ)
2858       CC = ISD::SETEQ;
2859     else if (CC == ISD::SETUNE)
2860       CC = ISD::SETNE;
2861
2862     SDValue ARMcc;
2863     if (LHS.getValueType() == MVT::f32) {
2864       LHS = bitcastf32Toi32(LHS, DAG);
2865       RHS = bitcastf32Toi32(RHS, DAG);
2866       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2867       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2868       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2869                          Chain, Dest, ARMcc, CCR, Cmp);
2870     }
2871
2872     SDValue LHS1, LHS2;
2873     SDValue RHS1, RHS2;
2874     expandf64Toi32(LHS, DAG, LHS1, LHS2);
2875     expandf64Toi32(RHS, DAG, RHS1, RHS2);
2876     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2877     ARMcc = DAG.getConstant(CondCode, MVT::i32);
2878     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2879     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
2880     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
2881   }
2882
2883   return SDValue();
2884 }
2885
2886 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2887   SDValue Chain = Op.getOperand(0);
2888   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2889   SDValue LHS = Op.getOperand(2);
2890   SDValue RHS = Op.getOperand(3);
2891   SDValue Dest = Op.getOperand(4);
2892   DebugLoc dl = Op.getDebugLoc();
2893
2894   if (LHS.getValueType() == MVT::i32) {
2895     SDValue ARMcc;
2896     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2897     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2898     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2899                        Chain, Dest, ARMcc, CCR, Cmp);
2900   }
2901
2902   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2903
2904   if (UnsafeFPMath &&
2905       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
2906        CC == ISD::SETNE || CC == ISD::SETUNE)) {
2907     SDValue Result = OptimizeVFPBrcond(Op, DAG);
2908     if (Result.getNode())
2909       return Result;
2910   }
2911
2912   ARMCC::CondCodes CondCode, CondCode2;
2913   FPCCToARMCC(CC, CondCode, CondCode2);
2914
2915   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2916   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2917   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2918   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
2919   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
2920   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2921   if (CondCode2 != ARMCC::AL) {
2922     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
2923     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
2924     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2925   }
2926   return Res;
2927 }
2928
2929 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
2930   SDValue Chain = Op.getOperand(0);
2931   SDValue Table = Op.getOperand(1);
2932   SDValue Index = Op.getOperand(2);
2933   DebugLoc dl = Op.getDebugLoc();
2934
2935   EVT PTy = getPointerTy();
2936   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
2937   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2938   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
2939   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
2940   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
2941   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
2942   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2943   if (Subtarget->isThumb2()) {
2944     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
2945     // which does another jump to the destination. This also makes it easier
2946     // to translate it to TBB / TBH later.
2947     // FIXME: This might not work if the function is extremely large.
2948     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
2949                        Addr, Op.getOperand(2), JTI, UId);
2950   }
2951   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2952     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
2953                        MachinePointerInfo::getJumpTable(),
2954                        false, false, 0);
2955     Chain = Addr.getValue(1);
2956     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
2957     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2958   } else {
2959     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
2960                        MachinePointerInfo::getJumpTable(), false, false, 0);
2961     Chain = Addr.getValue(1);
2962     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2963   }
2964 }
2965
2966 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2967   DebugLoc dl = Op.getDebugLoc();
2968   unsigned Opc;
2969
2970   switch (Op.getOpcode()) {
2971   default:
2972     assert(0 && "Invalid opcode!");
2973   case ISD::FP_TO_SINT:
2974     Opc = ARMISD::FTOSI;
2975     break;
2976   case ISD::FP_TO_UINT:
2977     Opc = ARMISD::FTOUI;
2978     break;
2979   }
2980   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
2981   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
2982 }
2983
2984 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2985   EVT VT = Op.getValueType();
2986   DebugLoc dl = Op.getDebugLoc();
2987
2988   EVT OperandVT = Op.getOperand(0).getValueType();
2989   assert(OperandVT == MVT::v4i16 && "Invalid type for custom lowering!");
2990   if (VT != MVT::v4f32)
2991     return DAG.UnrollVectorOp(Op.getNode());
2992
2993   unsigned CastOpc;
2994   unsigned Opc;
2995   switch (Op.getOpcode()) {
2996   default:
2997     assert(0 && "Invalid opcode!");
2998   case ISD::SINT_TO_FP:
2999     CastOpc = ISD::SIGN_EXTEND;
3000     Opc = ISD::SINT_TO_FP;
3001     break;
3002   case ISD::UINT_TO_FP:
3003     CastOpc = ISD::ZERO_EXTEND;
3004     Opc = ISD::UINT_TO_FP;
3005     break;
3006   }
3007
3008   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3009   return DAG.getNode(Opc, dl, VT, Op);
3010 }
3011
3012 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3013   EVT VT = Op.getValueType();
3014   if (VT.isVector())
3015     return LowerVectorINT_TO_FP(Op, DAG);
3016
3017   DebugLoc dl = Op.getDebugLoc();
3018   unsigned Opc;
3019
3020   switch (Op.getOpcode()) {
3021   default:
3022     assert(0 && "Invalid opcode!");
3023   case ISD::SINT_TO_FP:
3024     Opc = ARMISD::SITOF;
3025     break;
3026   case ISD::UINT_TO_FP:
3027     Opc = ARMISD::UITOF;
3028     break;
3029   }
3030
3031   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3032   return DAG.getNode(Opc, dl, VT, Op);
3033 }
3034
3035 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3036   // Implement fcopysign with a fabs and a conditional fneg.
3037   SDValue Tmp0 = Op.getOperand(0);
3038   SDValue Tmp1 = Op.getOperand(1);
3039   DebugLoc dl = Op.getDebugLoc();
3040   EVT VT = Op.getValueType();
3041   EVT SrcVT = Tmp1.getValueType();
3042   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3043     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3044   bool UseNEON = !InGPR && Subtarget->hasNEON();
3045
3046   if (UseNEON) {
3047     // Use VBSL to copy the sign bit.
3048     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3049     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3050                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3051     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3052     if (VT == MVT::f64)
3053       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3054                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3055                          DAG.getConstant(32, MVT::i32));
3056     else /*if (VT == MVT::f32)*/
3057       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3058     if (SrcVT == MVT::f32) {
3059       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3060       if (VT == MVT::f64)
3061         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3062                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3063                            DAG.getConstant(32, MVT::i32));
3064     } else if (VT == MVT::f32)
3065       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3066                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3067                          DAG.getConstant(32, MVT::i32));
3068     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3069     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3070
3071     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3072                                             MVT::i32);
3073     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3074     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3075                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3076
3077     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3078                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3079                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3080     if (VT == MVT::f32) {
3081       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3082       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3083                         DAG.getConstant(0, MVT::i32));
3084     } else {
3085       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3086     }
3087
3088     return Res;
3089   }
3090
3091   // Bitcast operand 1 to i32.
3092   if (SrcVT == MVT::f64)
3093     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3094                        &Tmp1, 1).getValue(1);
3095   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3096
3097   // Or in the signbit with integer operations.
3098   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3099   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3100   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3101   if (VT == MVT::f32) {
3102     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3103                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3104     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3105                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3106   }
3107
3108   // f64: Or the high part with signbit and then combine two parts.
3109   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3110                      &Tmp0, 1);
3111   SDValue Lo = Tmp0.getValue(0);
3112   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3113   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3114   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3115 }
3116
3117 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3118   MachineFunction &MF = DAG.getMachineFunction();
3119   MachineFrameInfo *MFI = MF.getFrameInfo();
3120   MFI->setReturnAddressIsTaken(true);
3121
3122   EVT VT = Op.getValueType();
3123   DebugLoc dl = Op.getDebugLoc();
3124   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3125   if (Depth) {
3126     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3127     SDValue Offset = DAG.getConstant(4, MVT::i32);
3128     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3129                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3130                        MachinePointerInfo(), false, false, 0);
3131   }
3132
3133   // Return LR, which contains the return address. Mark it an implicit live-in.
3134   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3135   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3136 }
3137
3138 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3139   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3140   MFI->setFrameAddressIsTaken(true);
3141
3142   EVT VT = Op.getValueType();
3143   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3144   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3145   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3146     ? ARM::R7 : ARM::R11;
3147   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3148   while (Depth--)
3149     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3150                             MachinePointerInfo(),
3151                             false, false, 0);
3152   return FrameAddr;
3153 }
3154
3155 /// ExpandBITCAST - If the target supports VFP, this function is called to
3156 /// expand a bit convert where either the source or destination type is i64 to
3157 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3158 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3159 /// vectors), since the legalizer won't know what to do with that.
3160 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3162   DebugLoc dl = N->getDebugLoc();
3163   SDValue Op = N->getOperand(0);
3164
3165   // This function is only supposed to be called for i64 types, either as the
3166   // source or destination of the bit convert.
3167   EVT SrcVT = Op.getValueType();
3168   EVT DstVT = N->getValueType(0);
3169   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3170          "ExpandBITCAST called for non-i64 type");
3171
3172   // Turn i64->f64 into VMOVDRR.
3173   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3174     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3175                              DAG.getConstant(0, MVT::i32));
3176     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3177                              DAG.getConstant(1, MVT::i32));
3178     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3179                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3180   }
3181
3182   // Turn f64->i64 into VMOVRRD.
3183   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3184     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3185                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3186     // Merge the pieces into a single i64 value.
3187     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3188   }
3189
3190   return SDValue();
3191 }
3192
3193 /// getZeroVector - Returns a vector of specified type with all zero elements.
3194 /// Zero vectors are used to represent vector negation and in those cases
3195 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3196 /// not support i64 elements, so sometimes the zero vectors will need to be
3197 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3198 /// zero vector.
3199 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3200   assert(VT.isVector() && "Expected a vector type");
3201   // The canonical modified immediate encoding of a zero vector is....0!
3202   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3203   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3204   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3205   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3206 }
3207
3208 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3209 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3210 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3211                                                 SelectionDAG &DAG) const {
3212   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3213   EVT VT = Op.getValueType();
3214   unsigned VTBits = VT.getSizeInBits();
3215   DebugLoc dl = Op.getDebugLoc();
3216   SDValue ShOpLo = Op.getOperand(0);
3217   SDValue ShOpHi = Op.getOperand(1);
3218   SDValue ShAmt  = Op.getOperand(2);
3219   SDValue ARMcc;
3220   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3221
3222   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3223
3224   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3225                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3226   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3227   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3228                                    DAG.getConstant(VTBits, MVT::i32));
3229   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3230   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3231   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3232
3233   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3234   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3235                           ARMcc, DAG, dl);
3236   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3237   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3238                            CCR, Cmp);
3239
3240   SDValue Ops[2] = { Lo, Hi };
3241   return DAG.getMergeValues(Ops, 2, dl);
3242 }
3243
3244 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3245 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3246 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3247                                                SelectionDAG &DAG) const {
3248   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3249   EVT VT = Op.getValueType();
3250   unsigned VTBits = VT.getSizeInBits();
3251   DebugLoc dl = Op.getDebugLoc();
3252   SDValue ShOpLo = Op.getOperand(0);
3253   SDValue ShOpHi = Op.getOperand(1);
3254   SDValue ShAmt  = Op.getOperand(2);
3255   SDValue ARMcc;
3256
3257   assert(Op.getOpcode() == ISD::SHL_PARTS);
3258   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3259                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3260   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3261   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3262                                    DAG.getConstant(VTBits, MVT::i32));
3263   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3264   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3265
3266   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3267   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3268   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3269                           ARMcc, DAG, dl);
3270   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3271   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3272                            CCR, Cmp);
3273
3274   SDValue Ops[2] = { Lo, Hi };
3275   return DAG.getMergeValues(Ops, 2, dl);
3276 }
3277
3278 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3279                                             SelectionDAG &DAG) const {
3280   // The rounding mode is in bits 23:22 of the FPSCR.
3281   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3282   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3283   // so that the shift + and get folded into a bitfield extract.
3284   DebugLoc dl = Op.getDebugLoc();
3285   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3286                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3287                                               MVT::i32));
3288   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3289                                   DAG.getConstant(1U << 22, MVT::i32));
3290   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3291                               DAG.getConstant(22, MVT::i32));
3292   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3293                      DAG.getConstant(3, MVT::i32));
3294 }
3295
3296 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3297                          const ARMSubtarget *ST) {
3298   EVT VT = N->getValueType(0);
3299   DebugLoc dl = N->getDebugLoc();
3300
3301   if (!ST->hasV6T2Ops())
3302     return SDValue();
3303
3304   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3305   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3306 }
3307
3308 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3309                           const ARMSubtarget *ST) {
3310   EVT VT = N->getValueType(0);
3311   DebugLoc dl = N->getDebugLoc();
3312
3313   if (!VT.isVector())
3314     return SDValue();
3315
3316   // Lower vector shifts on NEON to use VSHL.
3317   assert(ST->hasNEON() && "unexpected vector shift");
3318
3319   // Left shifts translate directly to the vshiftu intrinsic.
3320   if (N->getOpcode() == ISD::SHL)
3321     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3322                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3323                        N->getOperand(0), N->getOperand(1));
3324
3325   assert((N->getOpcode() == ISD::SRA ||
3326           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3327
3328   // NEON uses the same intrinsics for both left and right shifts.  For
3329   // right shifts, the shift amounts are negative, so negate the vector of
3330   // shift amounts.
3331   EVT ShiftVT = N->getOperand(1).getValueType();
3332   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3333                                      getZeroVector(ShiftVT, DAG, dl),
3334                                      N->getOperand(1));
3335   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3336                              Intrinsic::arm_neon_vshifts :
3337                              Intrinsic::arm_neon_vshiftu);
3338   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3339                      DAG.getConstant(vshiftInt, MVT::i32),
3340                      N->getOperand(0), NegatedCount);
3341 }
3342
3343 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3344                                 const ARMSubtarget *ST) {
3345   EVT VT = N->getValueType(0);
3346   DebugLoc dl = N->getDebugLoc();
3347
3348   // We can get here for a node like i32 = ISD::SHL i32, i64
3349   if (VT != MVT::i64)
3350     return SDValue();
3351
3352   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3353          "Unknown shift to lower!");
3354
3355   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3356   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3357       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3358     return SDValue();
3359
3360   // If we are in thumb mode, we don't have RRX.
3361   if (ST->isThumb1Only()) return SDValue();
3362
3363   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3364   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3365                            DAG.getConstant(0, MVT::i32));
3366   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3367                            DAG.getConstant(1, MVT::i32));
3368
3369   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3370   // captures the result into a carry flag.
3371   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3372   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3373
3374   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3375   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3376
3377   // Merge the pieces into a single i64 value.
3378  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3379 }
3380
3381 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3382   SDValue TmpOp0, TmpOp1;
3383   bool Invert = false;
3384   bool Swap = false;
3385   unsigned Opc = 0;
3386
3387   SDValue Op0 = Op.getOperand(0);
3388   SDValue Op1 = Op.getOperand(1);
3389   SDValue CC = Op.getOperand(2);
3390   EVT VT = Op.getValueType();
3391   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3392   DebugLoc dl = Op.getDebugLoc();
3393
3394   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3395     switch (SetCCOpcode) {
3396     default: llvm_unreachable("Illegal FP comparison"); break;
3397     case ISD::SETUNE:
3398     case ISD::SETNE:  Invert = true; // Fallthrough
3399     case ISD::SETOEQ:
3400     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3401     case ISD::SETOLT:
3402     case ISD::SETLT: Swap = true; // Fallthrough
3403     case ISD::SETOGT:
3404     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3405     case ISD::SETOLE:
3406     case ISD::SETLE:  Swap = true; // Fallthrough
3407     case ISD::SETOGE:
3408     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3409     case ISD::SETUGE: Swap = true; // Fallthrough
3410     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3411     case ISD::SETUGT: Swap = true; // Fallthrough
3412     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3413     case ISD::SETUEQ: Invert = true; // Fallthrough
3414     case ISD::SETONE:
3415       // Expand this to (OLT | OGT).
3416       TmpOp0 = Op0;
3417       TmpOp1 = Op1;
3418       Opc = ISD::OR;
3419       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3420       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3421       break;
3422     case ISD::SETUO: Invert = true; // Fallthrough
3423     case ISD::SETO:
3424       // Expand this to (OLT | OGE).
3425       TmpOp0 = Op0;
3426       TmpOp1 = Op1;
3427       Opc = ISD::OR;
3428       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3429       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3430       break;
3431     }
3432   } else {
3433     // Integer comparisons.
3434     switch (SetCCOpcode) {
3435     default: llvm_unreachable("Illegal integer comparison"); break;
3436     case ISD::SETNE:  Invert = true;
3437     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3438     case ISD::SETLT:  Swap = true;
3439     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3440     case ISD::SETLE:  Swap = true;
3441     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3442     case ISD::SETULT: Swap = true;
3443     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3444     case ISD::SETULE: Swap = true;
3445     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3446     }
3447
3448     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3449     if (Opc == ARMISD::VCEQ) {
3450
3451       SDValue AndOp;
3452       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3453         AndOp = Op0;
3454       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3455         AndOp = Op1;
3456
3457       // Ignore bitconvert.
3458       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3459         AndOp = AndOp.getOperand(0);
3460
3461       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3462         Opc = ARMISD::VTST;
3463         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3464         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3465         Invert = !Invert;
3466       }
3467     }
3468   }
3469
3470   if (Swap)
3471     std::swap(Op0, Op1);
3472
3473   // If one of the operands is a constant vector zero, attempt to fold the
3474   // comparison to a specialized compare-against-zero form.
3475   SDValue SingleOp;
3476   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3477     SingleOp = Op0;
3478   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3479     if (Opc == ARMISD::VCGE)
3480       Opc = ARMISD::VCLEZ;
3481     else if (Opc == ARMISD::VCGT)
3482       Opc = ARMISD::VCLTZ;
3483     SingleOp = Op1;
3484   }
3485
3486   SDValue Result;
3487   if (SingleOp.getNode()) {
3488     switch (Opc) {
3489     case ARMISD::VCEQ:
3490       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3491     case ARMISD::VCGE:
3492       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3493     case ARMISD::VCLEZ:
3494       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3495     case ARMISD::VCGT:
3496       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3497     case ARMISD::VCLTZ:
3498       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3499     default:
3500       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3501     }
3502   } else {
3503      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3504   }
3505
3506   if (Invert)
3507     Result = DAG.getNOT(dl, Result, VT);
3508
3509   return Result;
3510 }
3511
3512 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3513 /// valid vector constant for a NEON instruction with a "modified immediate"
3514 /// operand (e.g., VMOV).  If so, return the encoded value.
3515 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3516                                  unsigned SplatBitSize, SelectionDAG &DAG,
3517                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3518   unsigned OpCmode, Imm;
3519
3520   // SplatBitSize is set to the smallest size that splats the vector, so a
3521   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3522   // immediate instructions others than VMOV do not support the 8-bit encoding
3523   // of a zero vector, and the default encoding of zero is supposed to be the
3524   // 32-bit version.
3525   if (SplatBits == 0)
3526     SplatBitSize = 32;
3527
3528   switch (SplatBitSize) {
3529   case 8:
3530     if (type != VMOVModImm)
3531       return SDValue();
3532     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3533     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3534     OpCmode = 0xe;
3535     Imm = SplatBits;
3536     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3537     break;
3538
3539   case 16:
3540     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3541     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3542     if ((SplatBits & ~0xff) == 0) {
3543       // Value = 0x00nn: Op=x, Cmode=100x.
3544       OpCmode = 0x8;
3545       Imm = SplatBits;
3546       break;
3547     }
3548     if ((SplatBits & ~0xff00) == 0) {
3549       // Value = 0xnn00: Op=x, Cmode=101x.
3550       OpCmode = 0xa;
3551       Imm = SplatBits >> 8;
3552       break;
3553     }
3554     return SDValue();
3555
3556   case 32:
3557     // NEON's 32-bit VMOV supports splat values where:
3558     // * only one byte is nonzero, or
3559     // * the least significant byte is 0xff and the second byte is nonzero, or
3560     // * the least significant 2 bytes are 0xff and the third is nonzero.
3561     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3562     if ((SplatBits & ~0xff) == 0) {
3563       // Value = 0x000000nn: Op=x, Cmode=000x.
3564       OpCmode = 0;
3565       Imm = SplatBits;
3566       break;
3567     }
3568     if ((SplatBits & ~0xff00) == 0) {
3569       // Value = 0x0000nn00: Op=x, Cmode=001x.
3570       OpCmode = 0x2;
3571       Imm = SplatBits >> 8;
3572       break;
3573     }
3574     if ((SplatBits & ~0xff0000) == 0) {
3575       // Value = 0x00nn0000: Op=x, Cmode=010x.
3576       OpCmode = 0x4;
3577       Imm = SplatBits >> 16;
3578       break;
3579     }
3580     if ((SplatBits & ~0xff000000) == 0) {
3581       // Value = 0xnn000000: Op=x, Cmode=011x.
3582       OpCmode = 0x6;
3583       Imm = SplatBits >> 24;
3584       break;
3585     }
3586
3587     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3588     if (type == OtherModImm) return SDValue();
3589
3590     if ((SplatBits & ~0xffff) == 0 &&
3591         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3592       // Value = 0x0000nnff: Op=x, Cmode=1100.
3593       OpCmode = 0xc;
3594       Imm = SplatBits >> 8;
3595       SplatBits |= 0xff;
3596       break;
3597     }
3598
3599     if ((SplatBits & ~0xffffff) == 0 &&
3600         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3601       // Value = 0x00nnffff: Op=x, Cmode=1101.
3602       OpCmode = 0xd;
3603       Imm = SplatBits >> 16;
3604       SplatBits |= 0xffff;
3605       break;
3606     }
3607
3608     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3609     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3610     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3611     // and fall through here to test for a valid 64-bit splat.  But, then the
3612     // caller would also need to check and handle the change in size.
3613     return SDValue();
3614
3615   case 64: {
3616     if (type != VMOVModImm)
3617       return SDValue();
3618     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3619     uint64_t BitMask = 0xff;
3620     uint64_t Val = 0;
3621     unsigned ImmMask = 1;
3622     Imm = 0;
3623     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3624       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3625         Val |= BitMask;
3626         Imm |= ImmMask;
3627       } else if ((SplatBits & BitMask) != 0) {
3628         return SDValue();
3629       }
3630       BitMask <<= 8;
3631       ImmMask <<= 1;
3632     }
3633     // Op=1, Cmode=1110.
3634     OpCmode = 0x1e;
3635     SplatBits = Val;
3636     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3637     break;
3638   }
3639
3640   default:
3641     llvm_unreachable("unexpected size for isNEONModifiedImm");
3642     return SDValue();
3643   }
3644
3645   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3646   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3647 }
3648
3649 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
3650                        bool &ReverseVEXT, unsigned &Imm) {
3651   unsigned NumElts = VT.getVectorNumElements();
3652   ReverseVEXT = false;
3653
3654   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3655   if (M[0] < 0)
3656     return false;
3657
3658   Imm = M[0];
3659
3660   // If this is a VEXT shuffle, the immediate value is the index of the first
3661   // element.  The other shuffle indices must be the successive elements after
3662   // the first one.
3663   unsigned ExpectedElt = Imm;
3664   for (unsigned i = 1; i < NumElts; ++i) {
3665     // Increment the expected index.  If it wraps around, it may still be
3666     // a VEXT but the source vectors must be swapped.
3667     ExpectedElt += 1;
3668     if (ExpectedElt == NumElts * 2) {
3669       ExpectedElt = 0;
3670       ReverseVEXT = true;
3671     }
3672
3673     if (M[i] < 0) continue; // ignore UNDEF indices
3674     if (ExpectedElt != static_cast<unsigned>(M[i]))
3675       return false;
3676   }
3677
3678   // Adjust the index value if the source operands will be swapped.
3679   if (ReverseVEXT)
3680     Imm -= NumElts;
3681
3682   return true;
3683 }
3684
3685 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3686 /// instruction with the specified blocksize.  (The order of the elements
3687 /// within each block of the vector is reversed.)
3688 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
3689                        unsigned BlockSize) {
3690   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3691          "Only possible block sizes for VREV are: 16, 32, 64");
3692
3693   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3694   if (EltSz == 64)
3695     return false;
3696
3697   unsigned NumElts = VT.getVectorNumElements();
3698   unsigned BlockElts = M[0] + 1;
3699   // If the first shuffle index is UNDEF, be optimistic.
3700   if (M[0] < 0)
3701     BlockElts = BlockSize / EltSz;
3702
3703   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3704     return false;
3705
3706   for (unsigned i = 0; i < NumElts; ++i) {
3707     if (M[i] < 0) continue; // ignore UNDEF indices
3708     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3709       return false;
3710   }
3711
3712   return true;
3713 }
3714
3715 static bool isVTBLMask(const SmallVectorImpl<int> &M, EVT VT) {
3716   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3717   // range, then 0 is placed into the resulting vector. So pretty much any mask
3718   // of 8 elements can work here.
3719   return VT == MVT::v8i8 && M.size() == 8;
3720 }
3721
3722 static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
3723                        unsigned &WhichResult) {
3724   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3725   if (EltSz == 64)
3726     return false;
3727
3728   unsigned NumElts = VT.getVectorNumElements();
3729   WhichResult = (M[0] == 0 ? 0 : 1);
3730   for (unsigned i = 0; i < NumElts; i += 2) {
3731     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3732         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3733       return false;
3734   }
3735   return true;
3736 }
3737
3738 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3739 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3740 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3741 static bool isVTRN_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3742                                 unsigned &WhichResult) {
3743   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3744   if (EltSz == 64)
3745     return false;
3746
3747   unsigned NumElts = VT.getVectorNumElements();
3748   WhichResult = (M[0] == 0 ? 0 : 1);
3749   for (unsigned i = 0; i < NumElts; i += 2) {
3750     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3751         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3752       return false;
3753   }
3754   return true;
3755 }
3756
3757 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
3758                        unsigned &WhichResult) {
3759   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3760   if (EltSz == 64)
3761     return false;
3762
3763   unsigned NumElts = VT.getVectorNumElements();
3764   WhichResult = (M[0] == 0 ? 0 : 1);
3765   for (unsigned i = 0; i != NumElts; ++i) {
3766     if (M[i] < 0) continue; // ignore UNDEF indices
3767     if ((unsigned) M[i] != 2 * i + WhichResult)
3768       return false;
3769   }
3770
3771   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3772   if (VT.is64BitVector() && EltSz == 32)
3773     return false;
3774
3775   return true;
3776 }
3777
3778 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3779 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3780 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3781 static bool isVUZP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3782                                 unsigned &WhichResult) {
3783   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3784   if (EltSz == 64)
3785     return false;
3786
3787   unsigned Half = VT.getVectorNumElements() / 2;
3788   WhichResult = (M[0] == 0 ? 0 : 1);
3789   for (unsigned j = 0; j != 2; ++j) {
3790     unsigned Idx = WhichResult;
3791     for (unsigned i = 0; i != Half; ++i) {
3792       int MIdx = M[i + j * Half];
3793       if (MIdx >= 0 && (unsigned) MIdx != Idx)
3794         return false;
3795       Idx += 2;
3796     }
3797   }
3798
3799   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3800   if (VT.is64BitVector() && EltSz == 32)
3801     return false;
3802
3803   return true;
3804 }
3805
3806 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
3807                        unsigned &WhichResult) {
3808   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3809   if (EltSz == 64)
3810     return false;
3811
3812   unsigned NumElts = VT.getVectorNumElements();
3813   WhichResult = (M[0] == 0 ? 0 : 1);
3814   unsigned Idx = WhichResult * NumElts / 2;
3815   for (unsigned i = 0; i != NumElts; i += 2) {
3816     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3817         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3818       return false;
3819     Idx += 1;
3820   }
3821
3822   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3823   if (VT.is64BitVector() && EltSz == 32)
3824     return false;
3825
3826   return true;
3827 }
3828
3829 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3830 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3831 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3832 static bool isVZIP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3833                                 unsigned &WhichResult) {
3834   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3835   if (EltSz == 64)
3836     return false;
3837
3838   unsigned NumElts = VT.getVectorNumElements();
3839   WhichResult = (M[0] == 0 ? 0 : 1);
3840   unsigned Idx = WhichResult * NumElts / 2;
3841   for (unsigned i = 0; i != NumElts; i += 2) {
3842     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3843         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3844       return false;
3845     Idx += 1;
3846   }
3847
3848   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3849   if (VT.is64BitVector() && EltSz == 32)
3850     return false;
3851
3852   return true;
3853 }
3854
3855 // If N is an integer constant that can be moved into a register in one
3856 // instruction, return an SDValue of such a constant (will become a MOV
3857 // instruction).  Otherwise return null.
3858 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
3859                                      const ARMSubtarget *ST, DebugLoc dl) {
3860   uint64_t Val;
3861   if (!isa<ConstantSDNode>(N))
3862     return SDValue();
3863   Val = cast<ConstantSDNode>(N)->getZExtValue();
3864
3865   if (ST->isThumb1Only()) {
3866     if (Val <= 255 || ~Val <= 255)
3867       return DAG.getConstant(Val, MVT::i32);
3868   } else {
3869     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
3870       return DAG.getConstant(Val, MVT::i32);
3871   }
3872   return SDValue();
3873 }
3874
3875 // If this is a case we can't handle, return null and let the default
3876 // expansion code take care of it.
3877 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3878                                              const ARMSubtarget *ST) const {
3879   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3880   DebugLoc dl = Op.getDebugLoc();
3881   EVT VT = Op.getValueType();
3882
3883   APInt SplatBits, SplatUndef;
3884   unsigned SplatBitSize;
3885   bool HasAnyUndefs;
3886   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3887     if (SplatBitSize <= 64) {
3888       // Check if an immediate VMOV works.
3889       EVT VmovVT;
3890       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
3891                                       SplatUndef.getZExtValue(), SplatBitSize,
3892                                       DAG, VmovVT, VT.is128BitVector(),
3893                                       VMOVModImm);
3894       if (Val.getNode()) {
3895         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
3896         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3897       }
3898
3899       // Try an immediate VMVN.
3900       uint64_t NegatedImm = (SplatBits.getZExtValue() ^
3901                              ((1LL << SplatBitSize) - 1));
3902       Val = isNEONModifiedImm(NegatedImm,
3903                                       SplatUndef.getZExtValue(), SplatBitSize,
3904                                       DAG, VmovVT, VT.is128BitVector(),
3905                                       VMVNModImm);
3906       if (Val.getNode()) {
3907         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
3908         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3909       }
3910     }
3911   }
3912
3913   // Scan through the operands to see if only one value is used.
3914   unsigned NumElts = VT.getVectorNumElements();
3915   bool isOnlyLowElement = true;
3916   bool usesOnlyOneValue = true;
3917   bool isConstant = true;
3918   SDValue Value;
3919   for (unsigned i = 0; i < NumElts; ++i) {
3920     SDValue V = Op.getOperand(i);
3921     if (V.getOpcode() == ISD::UNDEF)
3922       continue;
3923     if (i > 0)
3924       isOnlyLowElement = false;
3925     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
3926       isConstant = false;
3927
3928     if (!Value.getNode())
3929       Value = V;
3930     else if (V != Value)
3931       usesOnlyOneValue = false;
3932   }
3933
3934   if (!Value.getNode())
3935     return DAG.getUNDEF(VT);
3936
3937   if (isOnlyLowElement)
3938     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
3939
3940   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3941
3942   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
3943   // i32 and try again.
3944   if (usesOnlyOneValue && EltSize <= 32) {
3945     if (!isConstant)
3946       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
3947     if (VT.getVectorElementType().isFloatingPoint()) {
3948       SmallVector<SDValue, 8> Ops;
3949       for (unsigned i = 0; i < NumElts; ++i)
3950         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
3951                                   Op.getOperand(i)));
3952       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
3953       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
3954       Val = LowerBUILD_VECTOR(Val, DAG, ST);
3955       if (Val.getNode())
3956         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
3957     }
3958     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
3959     if (Val.getNode())
3960       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
3961   }
3962
3963   // If all elements are constants and the case above didn't get hit, fall back
3964   // to the default expansion, which will generate a load from the constant
3965   // pool.
3966   if (isConstant)
3967     return SDValue();
3968
3969   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
3970   if (NumElts >= 4) {
3971     SDValue shuffle = ReconstructShuffle(Op, DAG);
3972     if (shuffle != SDValue())
3973       return shuffle;
3974   }
3975
3976   // Vectors with 32- or 64-bit elements can be built by directly assigning
3977   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
3978   // will be legalized.
3979   if (EltSize >= 32) {
3980     // Do the expansion with floating-point types, since that is what the VFP
3981     // registers are defined to use, and since i64 is not legal.
3982     EVT EltVT = EVT::getFloatingPointVT(EltSize);
3983     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
3984     SmallVector<SDValue, 8> Ops;
3985     for (unsigned i = 0; i < NumElts; ++i)
3986       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
3987     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
3988     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
3989   }
3990
3991   return SDValue();
3992 }
3993
3994 // Gather data to see if the operation can be modelled as a
3995 // shuffle in combination with VEXTs.
3996 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
3997                                               SelectionDAG &DAG) const {
3998   DebugLoc dl = Op.getDebugLoc();
3999   EVT VT = Op.getValueType();
4000   unsigned NumElts = VT.getVectorNumElements();
4001
4002   SmallVector<SDValue, 2> SourceVecs;
4003   SmallVector<unsigned, 2> MinElts;
4004   SmallVector<unsigned, 2> MaxElts;
4005
4006   for (unsigned i = 0; i < NumElts; ++i) {
4007     SDValue V = Op.getOperand(i);
4008     if (V.getOpcode() == ISD::UNDEF)
4009       continue;
4010     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4011       // A shuffle can only come from building a vector from various
4012       // elements of other vectors.
4013       return SDValue();
4014     }
4015
4016     // Record this extraction against the appropriate vector if possible...
4017     SDValue SourceVec = V.getOperand(0);
4018     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4019     bool FoundSource = false;
4020     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4021       if (SourceVecs[j] == SourceVec) {
4022         if (MinElts[j] > EltNo)
4023           MinElts[j] = EltNo;
4024         if (MaxElts[j] < EltNo)
4025           MaxElts[j] = EltNo;
4026         FoundSource = true;
4027         break;
4028       }
4029     }
4030
4031     // Or record a new source if not...
4032     if (!FoundSource) {
4033       SourceVecs.push_back(SourceVec);
4034       MinElts.push_back(EltNo);
4035       MaxElts.push_back(EltNo);
4036     }
4037   }
4038
4039   // Currently only do something sane when at most two source vectors
4040   // involved.
4041   if (SourceVecs.size() > 2)
4042     return SDValue();
4043
4044   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4045   int VEXTOffsets[2] = {0, 0};
4046
4047   // This loop extracts the usage patterns of the source vectors
4048   // and prepares appropriate SDValues for a shuffle if possible.
4049   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4050     if (SourceVecs[i].getValueType() == VT) {
4051       // No VEXT necessary
4052       ShuffleSrcs[i] = SourceVecs[i];
4053       VEXTOffsets[i] = 0;
4054       continue;
4055     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4056       // It probably isn't worth padding out a smaller vector just to
4057       // break it down again in a shuffle.
4058       return SDValue();
4059     }
4060
4061     // Since only 64-bit and 128-bit vectors are legal on ARM and
4062     // we've eliminated the other cases...
4063     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4064            "unexpected vector sizes in ReconstructShuffle");
4065
4066     if (MaxElts[i] - MinElts[i] >= NumElts) {
4067       // Span too large for a VEXT to cope
4068       return SDValue();
4069     }
4070
4071     if (MinElts[i] >= NumElts) {
4072       // The extraction can just take the second half
4073       VEXTOffsets[i] = NumElts;
4074       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4075                                    SourceVecs[i],
4076                                    DAG.getIntPtrConstant(NumElts));
4077     } else if (MaxElts[i] < NumElts) {
4078       // The extraction can just take the first half
4079       VEXTOffsets[i] = 0;
4080       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4081                                    SourceVecs[i],
4082                                    DAG.getIntPtrConstant(0));
4083     } else {
4084       // An actual VEXT is needed
4085       VEXTOffsets[i] = MinElts[i];
4086       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4087                                      SourceVecs[i],
4088                                      DAG.getIntPtrConstant(0));
4089       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4090                                      SourceVecs[i],
4091                                      DAG.getIntPtrConstant(NumElts));
4092       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4093                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4094     }
4095   }
4096
4097   SmallVector<int, 8> Mask;
4098
4099   for (unsigned i = 0; i < NumElts; ++i) {
4100     SDValue Entry = Op.getOperand(i);
4101     if (Entry.getOpcode() == ISD::UNDEF) {
4102       Mask.push_back(-1);
4103       continue;
4104     }
4105
4106     SDValue ExtractVec = Entry.getOperand(0);
4107     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4108                                           .getOperand(1))->getSExtValue();
4109     if (ExtractVec == SourceVecs[0]) {
4110       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4111     } else {
4112       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4113     }
4114   }
4115
4116   // Final check before we try to produce nonsense...
4117   if (isShuffleMaskLegal(Mask, VT))
4118     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4119                                 &Mask[0]);
4120
4121   return SDValue();
4122 }
4123
4124 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4125 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4126 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4127 /// are assumed to be legal.
4128 bool
4129 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4130                                       EVT VT) const {
4131   if (VT.getVectorNumElements() == 4 &&
4132       (VT.is128BitVector() || VT.is64BitVector())) {
4133     unsigned PFIndexes[4];
4134     for (unsigned i = 0; i != 4; ++i) {
4135       if (M[i] < 0)
4136         PFIndexes[i] = 8;
4137       else
4138         PFIndexes[i] = M[i];
4139     }
4140
4141     // Compute the index in the perfect shuffle table.
4142     unsigned PFTableIndex =
4143       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4144     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4145     unsigned Cost = (PFEntry >> 30);
4146
4147     if (Cost <= 4)
4148       return true;
4149   }
4150
4151   bool ReverseVEXT;
4152   unsigned Imm, WhichResult;
4153
4154   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4155   return (EltSize >= 32 ||
4156           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4157           isVREVMask(M, VT, 64) ||
4158           isVREVMask(M, VT, 32) ||
4159           isVREVMask(M, VT, 16) ||
4160           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4161           isVTBLMask(M, VT) ||
4162           isVTRNMask(M, VT, WhichResult) ||
4163           isVUZPMask(M, VT, WhichResult) ||
4164           isVZIPMask(M, VT, WhichResult) ||
4165           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4166           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4167           isVZIP_v_undef_Mask(M, VT, WhichResult));
4168 }
4169
4170 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4171 /// the specified operations to build the shuffle.
4172 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4173                                       SDValue RHS, SelectionDAG &DAG,
4174                                       DebugLoc dl) {
4175   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4176   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4177   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4178
4179   enum {
4180     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4181     OP_VREV,
4182     OP_VDUP0,
4183     OP_VDUP1,
4184     OP_VDUP2,
4185     OP_VDUP3,
4186     OP_VEXT1,
4187     OP_VEXT2,
4188     OP_VEXT3,
4189     OP_VUZPL, // VUZP, left result
4190     OP_VUZPR, // VUZP, right result
4191     OP_VZIPL, // VZIP, left result
4192     OP_VZIPR, // VZIP, right result
4193     OP_VTRNL, // VTRN, left result
4194     OP_VTRNR  // VTRN, right result
4195   };
4196
4197   if (OpNum == OP_COPY) {
4198     if (LHSID == (1*9+2)*9+3) return LHS;
4199     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4200     return RHS;
4201   }
4202
4203   SDValue OpLHS, OpRHS;
4204   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4205   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4206   EVT VT = OpLHS.getValueType();
4207
4208   switch (OpNum) {
4209   default: llvm_unreachable("Unknown shuffle opcode!");
4210   case OP_VREV:
4211     // VREV divides the vector in half and swaps within the half.
4212     if (VT.getVectorElementType() == MVT::i32 ||
4213         VT.getVectorElementType() == MVT::f32)
4214       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4215     // vrev <4 x i16> -> VREV32
4216     if (VT.getVectorElementType() == MVT::i16)
4217       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4218     // vrev <4 x i8> -> VREV16
4219     assert(VT.getVectorElementType() == MVT::i8);
4220     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4221   case OP_VDUP0:
4222   case OP_VDUP1:
4223   case OP_VDUP2:
4224   case OP_VDUP3:
4225     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4226                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4227   case OP_VEXT1:
4228   case OP_VEXT2:
4229   case OP_VEXT3:
4230     return DAG.getNode(ARMISD::VEXT, dl, VT,
4231                        OpLHS, OpRHS,
4232                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4233   case OP_VUZPL:
4234   case OP_VUZPR:
4235     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4236                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4237   case OP_VZIPL:
4238   case OP_VZIPR:
4239     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4240                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4241   case OP_VTRNL:
4242   case OP_VTRNR:
4243     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4244                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4245   }
4246 }
4247
4248 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4249                                        SmallVectorImpl<int> &ShuffleMask,
4250                                        SelectionDAG &DAG) {
4251   // Check to see if we can use the VTBL instruction.
4252   SDValue V1 = Op.getOperand(0);
4253   SDValue V2 = Op.getOperand(1);
4254   DebugLoc DL = Op.getDebugLoc();
4255
4256   SmallVector<SDValue, 8> VTBLMask;
4257   for (SmallVectorImpl<int>::iterator
4258          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4259     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4260
4261   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4262     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4263                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4264                                    &VTBLMask[0], 8));
4265
4266   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4267                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4268                                  &VTBLMask[0], 8));
4269 }
4270
4271 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4272   SDValue V1 = Op.getOperand(0);
4273   SDValue V2 = Op.getOperand(1);
4274   DebugLoc dl = Op.getDebugLoc();
4275   EVT VT = Op.getValueType();
4276   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4277   SmallVector<int, 8> ShuffleMask;
4278
4279   // Convert shuffles that are directly supported on NEON to target-specific
4280   // DAG nodes, instead of keeping them as shuffles and matching them again
4281   // during code selection.  This is more efficient and avoids the possibility
4282   // of inconsistencies between legalization and selection.
4283   // FIXME: floating-point vectors should be canonicalized to integer vectors
4284   // of the same time so that they get CSEd properly.
4285   SVN->getMask(ShuffleMask);
4286
4287   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4288   if (EltSize <= 32) {
4289     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4290       int Lane = SVN->getSplatIndex();
4291       // If this is undef splat, generate it via "just" vdup, if possible.
4292       if (Lane == -1) Lane = 0;
4293
4294       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4295         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4296       }
4297       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4298                          DAG.getConstant(Lane, MVT::i32));
4299     }
4300
4301     bool ReverseVEXT;
4302     unsigned Imm;
4303     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4304       if (ReverseVEXT)
4305         std::swap(V1, V2);
4306       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4307                          DAG.getConstant(Imm, MVT::i32));
4308     }
4309
4310     if (isVREVMask(ShuffleMask, VT, 64))
4311       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4312     if (isVREVMask(ShuffleMask, VT, 32))
4313       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4314     if (isVREVMask(ShuffleMask, VT, 16))
4315       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4316
4317     // Check for Neon shuffles that modify both input vectors in place.
4318     // If both results are used, i.e., if there are two shuffles with the same
4319     // source operands and with masks corresponding to both results of one of
4320     // these operations, DAG memoization will ensure that a single node is
4321     // used for both shuffles.
4322     unsigned WhichResult;
4323     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4324       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4325                          V1, V2).getValue(WhichResult);
4326     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4327       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4328                          V1, V2).getValue(WhichResult);
4329     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4330       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4331                          V1, V2).getValue(WhichResult);
4332
4333     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4334       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4335                          V1, V1).getValue(WhichResult);
4336     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4337       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4338                          V1, V1).getValue(WhichResult);
4339     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4340       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4341                          V1, V1).getValue(WhichResult);
4342   }
4343
4344   // If the shuffle is not directly supported and it has 4 elements, use
4345   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4346   unsigned NumElts = VT.getVectorNumElements();
4347   if (NumElts == 4) {
4348     unsigned PFIndexes[4];
4349     for (unsigned i = 0; i != 4; ++i) {
4350       if (ShuffleMask[i] < 0)
4351         PFIndexes[i] = 8;
4352       else
4353         PFIndexes[i] = ShuffleMask[i];
4354     }
4355
4356     // Compute the index in the perfect shuffle table.
4357     unsigned PFTableIndex =
4358       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4359     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4360     unsigned Cost = (PFEntry >> 30);
4361
4362     if (Cost <= 4)
4363       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4364   }
4365
4366   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4367   if (EltSize >= 32) {
4368     // Do the expansion with floating-point types, since that is what the VFP
4369     // registers are defined to use, and since i64 is not legal.
4370     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4371     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4372     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4373     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4374     SmallVector<SDValue, 8> Ops;
4375     for (unsigned i = 0; i < NumElts; ++i) {
4376       if (ShuffleMask[i] < 0)
4377         Ops.push_back(DAG.getUNDEF(EltVT));
4378       else
4379         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4380                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4381                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4382                                                   MVT::i32)));
4383     }
4384     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4385     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4386   }
4387
4388   if (VT == MVT::v8i8) {
4389     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4390     if (NewOp.getNode())
4391       return NewOp;
4392   }
4393
4394   return SDValue();
4395 }
4396
4397 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4398   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4399   SDValue Lane = Op.getOperand(1);
4400   if (!isa<ConstantSDNode>(Lane))
4401     return SDValue();
4402
4403   SDValue Vec = Op.getOperand(0);
4404   if (Op.getValueType() == MVT::i32 &&
4405       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4406     DebugLoc dl = Op.getDebugLoc();
4407     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4408   }
4409
4410   return Op;
4411 }
4412
4413 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4414   // The only time a CONCAT_VECTORS operation can have legal types is when
4415   // two 64-bit vectors are concatenated to a 128-bit vector.
4416   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4417          "unexpected CONCAT_VECTORS");
4418   DebugLoc dl = Op.getDebugLoc();
4419   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4420   SDValue Op0 = Op.getOperand(0);
4421   SDValue Op1 = Op.getOperand(1);
4422   if (Op0.getOpcode() != ISD::UNDEF)
4423     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4424                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4425                       DAG.getIntPtrConstant(0));
4426   if (Op1.getOpcode() != ISD::UNDEF)
4427     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4428                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4429                       DAG.getIntPtrConstant(1));
4430   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4431 }
4432
4433 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4434 /// element has been zero/sign-extended, depending on the isSigned parameter,
4435 /// from an integer type half its size.
4436 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4437                                    bool isSigned) {
4438   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4439   EVT VT = N->getValueType(0);
4440   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4441     SDNode *BVN = N->getOperand(0).getNode();
4442     if (BVN->getValueType(0) != MVT::v4i32 ||
4443         BVN->getOpcode() != ISD::BUILD_VECTOR)
4444       return false;
4445     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4446     unsigned HiElt = 1 - LoElt;
4447     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4448     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4449     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4450     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4451     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4452       return false;
4453     if (isSigned) {
4454       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4455           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4456         return true;
4457     } else {
4458       if (Hi0->isNullValue() && Hi1->isNullValue())
4459         return true;
4460     }
4461     return false;
4462   }
4463
4464   if (N->getOpcode() != ISD::BUILD_VECTOR)
4465     return false;
4466
4467   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4468     SDNode *Elt = N->getOperand(i).getNode();
4469     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4470       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4471       unsigned HalfSize = EltSize / 2;
4472       if (isSigned) {
4473         int64_t SExtVal = C->getSExtValue();
4474         if ((SExtVal >> HalfSize) != (SExtVal >> EltSize))
4475           return false;
4476       } else {
4477         if ((C->getZExtValue() >> HalfSize) != 0)
4478           return false;
4479       }
4480       continue;
4481     }
4482     return false;
4483   }
4484
4485   return true;
4486 }
4487
4488 /// isSignExtended - Check if a node is a vector value that is sign-extended
4489 /// or a constant BUILD_VECTOR with sign-extended elements.
4490 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4491   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4492     return true;
4493   if (isExtendedBUILD_VECTOR(N, DAG, true))
4494     return true;
4495   return false;
4496 }
4497
4498 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4499 /// or a constant BUILD_VECTOR with zero-extended elements.
4500 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4501   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4502     return true;
4503   if (isExtendedBUILD_VECTOR(N, DAG, false))
4504     return true;
4505   return false;
4506 }
4507
4508 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4509 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4510 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4511   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4512     return N->getOperand(0);
4513   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4514     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4515                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4516                        LD->isNonTemporal(), LD->getAlignment());
4517   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4518   // have been legalized as a BITCAST from v4i32.
4519   if (N->getOpcode() == ISD::BITCAST) {
4520     SDNode *BVN = N->getOperand(0).getNode();
4521     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4522            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4523     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4524     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4525                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4526   }
4527   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4528   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4529   EVT VT = N->getValueType(0);
4530   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4531   unsigned NumElts = VT.getVectorNumElements();
4532   MVT TruncVT = MVT::getIntegerVT(EltSize);
4533   SmallVector<SDValue, 8> Ops;
4534   for (unsigned i = 0; i != NumElts; ++i) {
4535     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4536     const APInt &CInt = C->getAPIntValue();
4537     Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4538   }
4539   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4540                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4541 }
4542
4543 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4544   unsigned Opcode = N->getOpcode();
4545   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4546     SDNode *N0 = N->getOperand(0).getNode();
4547     SDNode *N1 = N->getOperand(1).getNode();
4548     return N0->hasOneUse() && N1->hasOneUse() &&
4549       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4550   }
4551   return false;
4552 }
4553
4554 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4555   unsigned Opcode = N->getOpcode();
4556   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4557     SDNode *N0 = N->getOperand(0).getNode();
4558     SDNode *N1 = N->getOperand(1).getNode();
4559     return N0->hasOneUse() && N1->hasOneUse() &&
4560       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4561   }
4562   return false;
4563 }
4564
4565 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4566   // Multiplications are only custom-lowered for 128-bit vectors so that
4567   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4568   EVT VT = Op.getValueType();
4569   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4570   SDNode *N0 = Op.getOperand(0).getNode();
4571   SDNode *N1 = Op.getOperand(1).getNode();
4572   unsigned NewOpc = 0;
4573   bool isMLA = false;
4574   bool isN0SExt = isSignExtended(N0, DAG);
4575   bool isN1SExt = isSignExtended(N1, DAG);
4576   if (isN0SExt && isN1SExt)
4577     NewOpc = ARMISD::VMULLs;
4578   else {
4579     bool isN0ZExt = isZeroExtended(N0, DAG);
4580     bool isN1ZExt = isZeroExtended(N1, DAG);
4581     if (isN0ZExt && isN1ZExt)
4582       NewOpc = ARMISD::VMULLu;
4583     else if (isN1SExt || isN1ZExt) {
4584       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4585       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4586       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4587         NewOpc = ARMISD::VMULLs;
4588         isMLA = true;
4589       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4590         NewOpc = ARMISD::VMULLu;
4591         isMLA = true;
4592       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4593         std::swap(N0, N1);
4594         NewOpc = ARMISD::VMULLu;
4595         isMLA = true;
4596       }
4597     }
4598
4599     if (!NewOpc) {
4600       if (VT == MVT::v2i64)
4601         // Fall through to expand this.  It is not legal.
4602         return SDValue();
4603       else
4604         // Other vector multiplications are legal.
4605         return Op;
4606     }
4607   }
4608
4609   // Legalize to a VMULL instruction.
4610   DebugLoc DL = Op.getDebugLoc();
4611   SDValue Op0;
4612   SDValue Op1 = SkipExtension(N1, DAG);
4613   if (!isMLA) {
4614     Op0 = SkipExtension(N0, DAG);
4615     assert(Op0.getValueType().is64BitVector() &&
4616            Op1.getValueType().is64BitVector() &&
4617            "unexpected types for extended operands to VMULL");
4618     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4619   }
4620
4621   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4622   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4623   //   vmull q0, d4, d6
4624   //   vmlal q0, d5, d6
4625   // is faster than
4626   //   vaddl q0, d4, d5
4627   //   vmovl q1, d6
4628   //   vmul  q0, q0, q1
4629   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4630   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4631   EVT Op1VT = Op1.getValueType();
4632   return DAG.getNode(N0->getOpcode(), DL, VT,
4633                      DAG.getNode(NewOpc, DL, VT,
4634                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4635                      DAG.getNode(NewOpc, DL, VT,
4636                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4637 }
4638
4639 static SDValue
4640 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4641   // Convert to float
4642   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4643   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4644   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4645   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4646   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4647   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4648   // Get reciprocal estimate.
4649   // float4 recip = vrecpeq_f32(yf);
4650   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4651                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4652   // Because char has a smaller range than uchar, we can actually get away
4653   // without any newton steps.  This requires that we use a weird bias
4654   // of 0xb000, however (again, this has been exhaustively tested).
4655   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4656   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4657   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4658   Y = DAG.getConstant(0xb000, MVT::i32);
4659   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4660   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4661   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4662   // Convert back to short.
4663   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4664   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4665   return X;
4666 }
4667
4668 static SDValue
4669 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4670   SDValue N2;
4671   // Convert to float.
4672   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4673   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4674   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4675   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4676   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4677   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4678
4679   // Use reciprocal estimate and one refinement step.
4680   // float4 recip = vrecpeq_f32(yf);
4681   // recip *= vrecpsq_f32(yf, recip);
4682   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4683                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4684   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4685                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4686                    N1, N2);
4687   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4688   // Because short has a smaller range than ushort, we can actually get away
4689   // with only a single newton step.  This requires that we use a weird bias
4690   // of 89, however (again, this has been exhaustively tested).
4691   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4692   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4693   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4694   N1 = DAG.getConstant(0x89, MVT::i32);
4695   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4696   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4697   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4698   // Convert back to integer and return.
4699   // return vmovn_s32(vcvt_s32_f32(result));
4700   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4701   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4702   return N0;
4703 }
4704
4705 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4706   EVT VT = Op.getValueType();
4707   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4708          "unexpected type for custom-lowering ISD::SDIV");
4709
4710   DebugLoc dl = Op.getDebugLoc();
4711   SDValue N0 = Op.getOperand(0);
4712   SDValue N1 = Op.getOperand(1);
4713   SDValue N2, N3;
4714
4715   if (VT == MVT::v8i8) {
4716     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4717     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4718
4719     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4720                      DAG.getIntPtrConstant(4));
4721     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4722                      DAG.getIntPtrConstant(4));
4723     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4724                      DAG.getIntPtrConstant(0));
4725     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4726                      DAG.getIntPtrConstant(0));
4727
4728     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4729     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4730
4731     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4732     N0 = LowerCONCAT_VECTORS(N0, DAG);
4733
4734     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4735     return N0;
4736   }
4737   return LowerSDIV_v4i16(N0, N1, dl, DAG);
4738 }
4739
4740 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4741   EVT VT = Op.getValueType();
4742   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4743          "unexpected type for custom-lowering ISD::UDIV");
4744
4745   DebugLoc dl = Op.getDebugLoc();
4746   SDValue N0 = Op.getOperand(0);
4747   SDValue N1 = Op.getOperand(1);
4748   SDValue N2, N3;
4749
4750   if (VT == MVT::v8i8) {
4751     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4752     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4753
4754     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4755                      DAG.getIntPtrConstant(4));
4756     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4757                      DAG.getIntPtrConstant(4));
4758     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4759                      DAG.getIntPtrConstant(0));
4760     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4761                      DAG.getIntPtrConstant(0));
4762
4763     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4764     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4765
4766     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4767     N0 = LowerCONCAT_VECTORS(N0, DAG);
4768
4769     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4770                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4771                      N0);
4772     return N0;
4773   }
4774
4775   // v4i16 sdiv ... Convert to float.
4776   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4777   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4778   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4779   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4780   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4781   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4782
4783   // Use reciprocal estimate and two refinement steps.
4784   // float4 recip = vrecpeq_f32(yf);
4785   // recip *= vrecpsq_f32(yf, recip);
4786   // recip *= vrecpsq_f32(yf, recip);
4787   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4788                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
4789   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4790                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4791                    BN1, N2);
4792   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4793   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4794                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4795                    BN1, N2);
4796   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4797   // Simply multiplying by the reciprocal estimate can leave us a few ulps
4798   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4799   // and that it will never cause us to return an answer too large).
4800   // float4 result = as_float4(as_int4(xf*recip) + 2);
4801   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4802   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4803   N1 = DAG.getConstant(2, MVT::i32);
4804   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4805   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4806   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4807   // Convert back to integer and return.
4808   // return vmovn_u32(vcvt_s32_f32(result));
4809   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4810   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4811   return N0;
4812 }
4813
4814 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4815   switch (Op.getOpcode()) {
4816   default: llvm_unreachable("Don't know how to custom lower this!");
4817   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
4818   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
4819   case ISD::GlobalAddress:
4820     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
4821       LowerGlobalAddressELF(Op, DAG);
4822   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4823   case ISD::SELECT:        return LowerSELECT(Op, DAG);
4824   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
4825   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
4826   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
4827   case ISD::VASTART:       return LowerVASTART(Op, DAG);
4828   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
4829   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
4830   case ISD::SINT_TO_FP:
4831   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
4832   case ISD::FP_TO_SINT:
4833   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
4834   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
4835   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
4836   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
4837   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
4838   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
4839   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
4840   case ISD::EH_SJLJ_DISPATCHSETUP: return LowerEH_SJLJ_DISPATCHSETUP(Op, DAG);
4841   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
4842                                                                Subtarget);
4843   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
4844   case ISD::SHL:
4845   case ISD::SRL:
4846   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
4847   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
4848   case ISD::SRL_PARTS:
4849   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
4850   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
4851   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
4852   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
4853   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4854   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4855   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
4856   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
4857   case ISD::MUL:           return LowerMUL(Op, DAG);
4858   case ISD::SDIV:          return LowerSDIV(Op, DAG);
4859   case ISD::UDIV:          return LowerUDIV(Op, DAG);
4860   }
4861   return SDValue();
4862 }
4863
4864 /// ReplaceNodeResults - Replace the results of node with an illegal result
4865 /// type with new values built out of custom code.
4866 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
4867                                            SmallVectorImpl<SDValue>&Results,
4868                                            SelectionDAG &DAG) const {
4869   SDValue Res;
4870   switch (N->getOpcode()) {
4871   default:
4872     llvm_unreachable("Don't know how to custom expand this!");
4873     break;
4874   case ISD::BITCAST:
4875     Res = ExpandBITCAST(N, DAG);
4876     break;
4877   case ISD::SRL:
4878   case ISD::SRA:
4879     Res = Expand64BitShift(N, DAG, Subtarget);
4880     break;
4881   }
4882   if (Res.getNode())
4883     Results.push_back(Res);
4884 }
4885
4886 //===----------------------------------------------------------------------===//
4887 //                           ARM Scheduler Hooks
4888 //===----------------------------------------------------------------------===//
4889
4890 MachineBasicBlock *
4891 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
4892                                      MachineBasicBlock *BB,
4893                                      unsigned Size) const {
4894   unsigned dest    = MI->getOperand(0).getReg();
4895   unsigned ptr     = MI->getOperand(1).getReg();
4896   unsigned oldval  = MI->getOperand(2).getReg();
4897   unsigned newval  = MI->getOperand(3).getReg();
4898   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4899   DebugLoc dl = MI->getDebugLoc();
4900   bool isThumb2 = Subtarget->isThumb2();
4901
4902   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4903   unsigned scratch =
4904     MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
4905                                        : ARM::GPRRegisterClass);
4906
4907   if (isThumb2) {
4908     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
4909     MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
4910     MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
4911   }
4912
4913   unsigned ldrOpc, strOpc;
4914   switch (Size) {
4915   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
4916   case 1:
4917     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
4918     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
4919     break;
4920   case 2:
4921     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
4922     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
4923     break;
4924   case 4:
4925     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
4926     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
4927     break;
4928   }
4929
4930   MachineFunction *MF = BB->getParent();
4931   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4932   MachineFunction::iterator It = BB;
4933   ++It; // insert the new blocks after the current block
4934
4935   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
4936   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
4937   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
4938   MF->insert(It, loop1MBB);
4939   MF->insert(It, loop2MBB);
4940   MF->insert(It, exitMBB);
4941
4942   // Transfer the remainder of BB and its successor edges to exitMBB.
4943   exitMBB->splice(exitMBB->begin(), BB,
4944                   llvm::next(MachineBasicBlock::iterator(MI)),
4945                   BB->end());
4946   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
4947
4948   //  thisMBB:
4949   //   ...
4950   //   fallthrough --> loop1MBB
4951   BB->addSuccessor(loop1MBB);
4952
4953   // loop1MBB:
4954   //   ldrex dest, [ptr]
4955   //   cmp dest, oldval
4956   //   bne exitMBB
4957   BB = loop1MBB;
4958   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
4959   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
4960                  .addReg(dest).addReg(oldval));
4961   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
4962     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
4963   BB->addSuccessor(loop2MBB);
4964   BB->addSuccessor(exitMBB);
4965
4966   // loop2MBB:
4967   //   strex scratch, newval, [ptr]
4968   //   cmp scratch, #0
4969   //   bne loop1MBB
4970   BB = loop2MBB;
4971   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval)
4972                  .addReg(ptr));
4973   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
4974                  .addReg(scratch).addImm(0));
4975   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
4976     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
4977   BB->addSuccessor(loop1MBB);
4978   BB->addSuccessor(exitMBB);
4979
4980   //  exitMBB:
4981   //   ...
4982   BB = exitMBB;
4983
4984   MI->eraseFromParent();   // The instruction is gone now.
4985
4986   return BB;
4987 }
4988
4989 MachineBasicBlock *
4990 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
4991                                     unsigned Size, unsigned BinOpcode) const {
4992   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
4993   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4994
4995   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4996   MachineFunction *MF = BB->getParent();
4997   MachineFunction::iterator It = BB;
4998   ++It;
4999
5000   unsigned dest = MI->getOperand(0).getReg();
5001   unsigned ptr = MI->getOperand(1).getReg();
5002   unsigned incr = MI->getOperand(2).getReg();
5003   DebugLoc dl = MI->getDebugLoc();
5004   bool isThumb2 = Subtarget->isThumb2();
5005
5006   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5007   if (isThumb2) {
5008     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5009     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5010   }
5011
5012   unsigned ldrOpc, strOpc;
5013   switch (Size) {
5014   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5015   case 1:
5016     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5017     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5018     break;
5019   case 2:
5020     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5021     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5022     break;
5023   case 4:
5024     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5025     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5026     break;
5027   }
5028
5029   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5030   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5031   MF->insert(It, loopMBB);
5032   MF->insert(It, exitMBB);
5033
5034   // Transfer the remainder of BB and its successor edges to exitMBB.
5035   exitMBB->splice(exitMBB->begin(), BB,
5036                   llvm::next(MachineBasicBlock::iterator(MI)),
5037                   BB->end());
5038   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5039
5040   TargetRegisterClass *TRC =
5041     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5042   unsigned scratch = MRI.createVirtualRegister(TRC);
5043   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5044
5045   //  thisMBB:
5046   //   ...
5047   //   fallthrough --> loopMBB
5048   BB->addSuccessor(loopMBB);
5049
5050   //  loopMBB:
5051   //   ldrex dest, ptr
5052   //   <binop> scratch2, dest, incr
5053   //   strex scratch, scratch2, ptr
5054   //   cmp scratch, #0
5055   //   bne- loopMBB
5056   //   fallthrough --> exitMBB
5057   BB = loopMBB;
5058   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
5059   if (BinOpcode) {
5060     // operand order needs to go the other way for NAND
5061     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5062       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5063                      addReg(incr).addReg(dest)).addReg(0);
5064     else
5065       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5066                      addReg(dest).addReg(incr)).addReg(0);
5067   }
5068
5069   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2)
5070                  .addReg(ptr));
5071   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5072                  .addReg(scratch).addImm(0));
5073   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5074     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5075
5076   BB->addSuccessor(loopMBB);
5077   BB->addSuccessor(exitMBB);
5078
5079   //  exitMBB:
5080   //   ...
5081   BB = exitMBB;
5082
5083   MI->eraseFromParent();   // The instruction is gone now.
5084
5085   return BB;
5086 }
5087
5088 MachineBasicBlock *
5089 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5090                                           MachineBasicBlock *BB,
5091                                           unsigned Size,
5092                                           bool signExtend,
5093                                           ARMCC::CondCodes Cond) const {
5094   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5095
5096   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5097   MachineFunction *MF = BB->getParent();
5098   MachineFunction::iterator It = BB;
5099   ++It;
5100
5101   unsigned dest = MI->getOperand(0).getReg();
5102   unsigned ptr = MI->getOperand(1).getReg();
5103   unsigned incr = MI->getOperand(2).getReg();
5104   unsigned oldval = dest;
5105   DebugLoc dl = MI->getDebugLoc();
5106   bool isThumb2 = Subtarget->isThumb2();
5107
5108   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5109   if (isThumb2) {
5110     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5111     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5112   }
5113
5114   unsigned ldrOpc, strOpc, extendOpc;
5115   switch (Size) {
5116   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5117   case 1:
5118     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5119     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5120     extendOpc = isThumb2 ? ARM::t2SXTBr : ARM::SXTBr;
5121     break;
5122   case 2:
5123     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5124     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5125     extendOpc = isThumb2 ? ARM::t2SXTHr : ARM::SXTHr;
5126     break;
5127   case 4:
5128     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5129     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5130     extendOpc = 0;
5131     break;
5132   }
5133
5134   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5135   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5136   MF->insert(It, loopMBB);
5137   MF->insert(It, exitMBB);
5138
5139   // Transfer the remainder of BB and its successor edges to exitMBB.
5140   exitMBB->splice(exitMBB->begin(), BB,
5141                   llvm::next(MachineBasicBlock::iterator(MI)),
5142                   BB->end());
5143   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5144
5145   TargetRegisterClass *TRC =
5146     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5147   unsigned scratch = MRI.createVirtualRegister(TRC);
5148   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5149
5150   //  thisMBB:
5151   //   ...
5152   //   fallthrough --> loopMBB
5153   BB->addSuccessor(loopMBB);
5154
5155   //  loopMBB:
5156   //   ldrex dest, ptr
5157   //   (sign extend dest, if required)
5158   //   cmp dest, incr
5159   //   cmov.cond scratch2, dest, incr
5160   //   strex scratch, scratch2, ptr
5161   //   cmp scratch, #0
5162   //   bne- loopMBB
5163   //   fallthrough --> exitMBB
5164   BB = loopMBB;
5165   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
5166
5167   // Sign extend the value, if necessary.
5168   if (signExtend && extendOpc) {
5169     oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5170     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval).addReg(dest));
5171   }
5172
5173   // Build compare and cmov instructions.
5174   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5175                  .addReg(oldval).addReg(incr));
5176   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5177          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5178
5179   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2)
5180                  .addReg(ptr));
5181   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5182                  .addReg(scratch).addImm(0));
5183   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5184     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5185
5186   BB->addSuccessor(loopMBB);
5187   BB->addSuccessor(exitMBB);
5188
5189   //  exitMBB:
5190   //   ...
5191   BB = exitMBB;
5192
5193   MI->eraseFromParent();   // The instruction is gone now.
5194
5195   return BB;
5196 }
5197
5198 static
5199 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
5200   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
5201        E = MBB->succ_end(); I != E; ++I)
5202     if (*I != Succ)
5203       return *I;
5204   llvm_unreachable("Expecting a BB with two successors!");
5205 }
5206
5207 // FIXME: This opcode table should obviously be expressed in the target
5208 // description. We probably just need a "machine opcode" value in the pseudo
5209 // instruction. But the ideal solution maybe to simply remove the "S" version
5210 // of the opcode altogether.
5211 struct AddSubFlagsOpcodePair {
5212   unsigned PseudoOpc;
5213   unsigned MachineOpc;
5214 };
5215
5216 static AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
5217   {ARM::ADCSri, ARM::ADCri},
5218   {ARM::ADCSrr, ARM::ADCrr},
5219   {ARM::ADCSrs, ARM::ADCrs},
5220   {ARM::SBCSri, ARM::SBCri},
5221   {ARM::SBCSrr, ARM::SBCrr},
5222   {ARM::SBCSrs, ARM::SBCrs},
5223   {ARM::RSBSri, ARM::RSBri},
5224   {ARM::RSBSrr, ARM::RSBrr},
5225   {ARM::RSBSrs, ARM::RSBrs},
5226   {ARM::RSCSri, ARM::RSCri},
5227   {ARM::RSCSrs, ARM::RSCrs},
5228   {ARM::t2ADCSri, ARM::t2ADCri},
5229   {ARM::t2ADCSrr, ARM::t2ADCrr},
5230   {ARM::t2ADCSrs, ARM::t2ADCrs},
5231   {ARM::t2SBCSri, ARM::t2SBCri},
5232   {ARM::t2SBCSrr, ARM::t2SBCrr},
5233   {ARM::t2SBCSrs, ARM::t2SBCrs},
5234   {ARM::t2RSBSri, ARM::t2RSBri},
5235   {ARM::t2RSBSrs, ARM::t2RSBrs},
5236 };
5237
5238 // Convert and Add or Subtract with Carry and Flags to a generic opcode with
5239 // CPSR<def> operand. e.g. ADCS (...) -> ADC (... CPSR<def>).
5240 //
5241 // FIXME: Somewhere we should assert that CPSR<def> is in the correct
5242 // position to be recognized by the target descrition as the 'S' bit.
5243 bool ARMTargetLowering::RemapAddSubWithFlags(MachineInstr *MI,
5244                                              MachineBasicBlock *BB) const {
5245   unsigned OldOpc = MI->getOpcode();
5246   unsigned NewOpc = 0;
5247
5248   // This is only called for instructions that need remapping, so iterating over
5249   // the tiny opcode table is not costly.
5250   static const int NPairs =
5251     sizeof(AddSubFlagsOpcodeMap) / sizeof(AddSubFlagsOpcodePair);
5252   for (AddSubFlagsOpcodePair *Pair = &AddSubFlagsOpcodeMap[0],
5253          *End = &AddSubFlagsOpcodeMap[NPairs]; Pair != End; ++Pair) {
5254     if (OldOpc == Pair->PseudoOpc) {
5255       NewOpc = Pair->MachineOpc;
5256       break;
5257     }
5258   }
5259   if (!NewOpc)
5260     return false;
5261
5262   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5263   DebugLoc dl = MI->getDebugLoc();
5264   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
5265   for (unsigned i = 0; i < MI->getNumOperands(); ++i)
5266     MIB.addOperand(MI->getOperand(i));
5267   AddDefaultPred(MIB);
5268   MIB.addReg(ARM::CPSR, RegState::Define); // S bit
5269   MI->eraseFromParent();
5270   return true;
5271 }
5272
5273 MachineBasicBlock *
5274 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5275                                                MachineBasicBlock *BB) const {
5276   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5277   DebugLoc dl = MI->getDebugLoc();
5278   bool isThumb2 = Subtarget->isThumb2();
5279   switch (MI->getOpcode()) {
5280   default: {
5281     if (RemapAddSubWithFlags(MI, BB))
5282       return BB;
5283
5284     MI->dump();
5285     llvm_unreachable("Unexpected instr type to insert");
5286   }
5287   case ARM::ATOMIC_LOAD_ADD_I8:
5288      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
5289   case ARM::ATOMIC_LOAD_ADD_I16:
5290      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
5291   case ARM::ATOMIC_LOAD_ADD_I32:
5292      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
5293
5294   case ARM::ATOMIC_LOAD_AND_I8:
5295      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5296   case ARM::ATOMIC_LOAD_AND_I16:
5297      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5298   case ARM::ATOMIC_LOAD_AND_I32:
5299      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
5300
5301   case ARM::ATOMIC_LOAD_OR_I8:
5302      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5303   case ARM::ATOMIC_LOAD_OR_I16:
5304      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5305   case ARM::ATOMIC_LOAD_OR_I32:
5306      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
5307
5308   case ARM::ATOMIC_LOAD_XOR_I8:
5309      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5310   case ARM::ATOMIC_LOAD_XOR_I16:
5311      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5312   case ARM::ATOMIC_LOAD_XOR_I32:
5313      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
5314
5315   case ARM::ATOMIC_LOAD_NAND_I8:
5316      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5317   case ARM::ATOMIC_LOAD_NAND_I16:
5318      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5319   case ARM::ATOMIC_LOAD_NAND_I32:
5320      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
5321
5322   case ARM::ATOMIC_LOAD_SUB_I8:
5323      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5324   case ARM::ATOMIC_LOAD_SUB_I16:
5325      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5326   case ARM::ATOMIC_LOAD_SUB_I32:
5327      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
5328
5329   case ARM::ATOMIC_LOAD_MIN_I8:
5330      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
5331   case ARM::ATOMIC_LOAD_MIN_I16:
5332      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
5333   case ARM::ATOMIC_LOAD_MIN_I32:
5334      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
5335
5336   case ARM::ATOMIC_LOAD_MAX_I8:
5337      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
5338   case ARM::ATOMIC_LOAD_MAX_I16:
5339      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
5340   case ARM::ATOMIC_LOAD_MAX_I32:
5341      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
5342
5343   case ARM::ATOMIC_LOAD_UMIN_I8:
5344      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
5345   case ARM::ATOMIC_LOAD_UMIN_I16:
5346      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
5347   case ARM::ATOMIC_LOAD_UMIN_I32:
5348      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
5349
5350   case ARM::ATOMIC_LOAD_UMAX_I8:
5351      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
5352   case ARM::ATOMIC_LOAD_UMAX_I16:
5353      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
5354   case ARM::ATOMIC_LOAD_UMAX_I32:
5355      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
5356
5357   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
5358   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
5359   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
5360
5361   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
5362   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
5363   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
5364
5365   case ARM::tMOVCCr_pseudo: {
5366     // To "insert" a SELECT_CC instruction, we actually have to insert the
5367     // diamond control-flow pattern.  The incoming instruction knows the
5368     // destination vreg to set, the condition code register to branch on, the
5369     // true/false values to select between, and a branch opcode to use.
5370     const BasicBlock *LLVM_BB = BB->getBasicBlock();
5371     MachineFunction::iterator It = BB;
5372     ++It;
5373
5374     //  thisMBB:
5375     //  ...
5376     //   TrueVal = ...
5377     //   cmpTY ccX, r1, r2
5378     //   bCC copy1MBB
5379     //   fallthrough --> copy0MBB
5380     MachineBasicBlock *thisMBB  = BB;
5381     MachineFunction *F = BB->getParent();
5382     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5383     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
5384     F->insert(It, copy0MBB);
5385     F->insert(It, sinkMBB);
5386
5387     // Transfer the remainder of BB and its successor edges to sinkMBB.
5388     sinkMBB->splice(sinkMBB->begin(), BB,
5389                     llvm::next(MachineBasicBlock::iterator(MI)),
5390                     BB->end());
5391     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5392
5393     BB->addSuccessor(copy0MBB);
5394     BB->addSuccessor(sinkMBB);
5395
5396     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
5397       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
5398
5399     //  copy0MBB:
5400     //   %FalseValue = ...
5401     //   # fallthrough to sinkMBB
5402     BB = copy0MBB;
5403
5404     // Update machine-CFG edges
5405     BB->addSuccessor(sinkMBB);
5406
5407     //  sinkMBB:
5408     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5409     //  ...
5410     BB = sinkMBB;
5411     BuildMI(*BB, BB->begin(), dl,
5412             TII->get(ARM::PHI), MI->getOperand(0).getReg())
5413       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5414       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5415
5416     MI->eraseFromParent();   // The pseudo instruction is gone now.
5417     return BB;
5418   }
5419
5420   case ARM::BCCi64:
5421   case ARM::BCCZi64: {
5422     // If there is an unconditional branch to the other successor, remove it.
5423     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
5424
5425     // Compare both parts that make up the double comparison separately for
5426     // equality.
5427     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
5428
5429     unsigned LHS1 = MI->getOperand(1).getReg();
5430     unsigned LHS2 = MI->getOperand(2).getReg();
5431     if (RHSisZero) {
5432       AddDefaultPred(BuildMI(BB, dl,
5433                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5434                      .addReg(LHS1).addImm(0));
5435       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5436         .addReg(LHS2).addImm(0)
5437         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
5438     } else {
5439       unsigned RHS1 = MI->getOperand(3).getReg();
5440       unsigned RHS2 = MI->getOperand(4).getReg();
5441       AddDefaultPred(BuildMI(BB, dl,
5442                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5443                      .addReg(LHS1).addReg(RHS1));
5444       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5445         .addReg(LHS2).addReg(RHS2)
5446         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
5447     }
5448
5449     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
5450     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
5451     if (MI->getOperand(0).getImm() == ARMCC::NE)
5452       std::swap(destMBB, exitMBB);
5453
5454     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5455       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
5456     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2B : ARM::B))
5457       .addMBB(exitMBB);
5458
5459     MI->eraseFromParent();   // The pseudo instruction is gone now.
5460     return BB;
5461   }
5462   }
5463 }
5464
5465 //===----------------------------------------------------------------------===//
5466 //                           ARM Optimization Hooks
5467 //===----------------------------------------------------------------------===//
5468
5469 static
5470 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
5471                             TargetLowering::DAGCombinerInfo &DCI) {
5472   SelectionDAG &DAG = DCI.DAG;
5473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5474   EVT VT = N->getValueType(0);
5475   unsigned Opc = N->getOpcode();
5476   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
5477   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
5478   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
5479   ISD::CondCode CC = ISD::SETCC_INVALID;
5480
5481   if (isSlctCC) {
5482     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
5483   } else {
5484     SDValue CCOp = Slct.getOperand(0);
5485     if (CCOp.getOpcode() == ISD::SETCC)
5486       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
5487   }
5488
5489   bool DoXform = false;
5490   bool InvCC = false;
5491   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
5492           "Bad input!");
5493
5494   if (LHS.getOpcode() == ISD::Constant &&
5495       cast<ConstantSDNode>(LHS)->isNullValue()) {
5496     DoXform = true;
5497   } else if (CC != ISD::SETCC_INVALID &&
5498              RHS.getOpcode() == ISD::Constant &&
5499              cast<ConstantSDNode>(RHS)->isNullValue()) {
5500     std::swap(LHS, RHS);
5501     SDValue Op0 = Slct.getOperand(0);
5502     EVT OpVT = isSlctCC ? Op0.getValueType() :
5503                           Op0.getOperand(0).getValueType();
5504     bool isInt = OpVT.isInteger();
5505     CC = ISD::getSetCCInverse(CC, isInt);
5506
5507     if (!TLI.isCondCodeLegal(CC, OpVT))
5508       return SDValue();         // Inverse operator isn't legal.
5509
5510     DoXform = true;
5511     InvCC = true;
5512   }
5513
5514   if (DoXform) {
5515     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
5516     if (isSlctCC)
5517       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
5518                              Slct.getOperand(0), Slct.getOperand(1), CC);
5519     SDValue CCOp = Slct.getOperand(0);
5520     if (InvCC)
5521       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
5522                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
5523     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
5524                        CCOp, OtherOp, Result);
5525   }
5526   return SDValue();
5527 }
5528
5529 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
5530 // (only after legalization).
5531 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
5532                                  TargetLowering::DAGCombinerInfo &DCI,
5533                                  const ARMSubtarget *Subtarget) {
5534
5535   // Only perform optimization if after legalize, and if NEON is available. We
5536   // also expected both operands to be BUILD_VECTORs.
5537   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
5538       || N0.getOpcode() != ISD::BUILD_VECTOR
5539       || N1.getOpcode() != ISD::BUILD_VECTOR)
5540     return SDValue();
5541
5542   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
5543   EVT VT = N->getValueType(0);
5544   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
5545     return SDValue();
5546
5547   // Check that the vector operands are of the right form.
5548   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
5549   // operands, where N is the size of the formed vector.
5550   // Each EXTRACT_VECTOR should have the same input vector and odd or even
5551   // index such that we have a pair wise add pattern.
5552
5553   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
5554   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5555     return SDValue();
5556   SDValue Vec = N0->getOperand(0)->getOperand(0);
5557   SDNode *V = Vec.getNode();
5558   unsigned nextIndex = 0;
5559
5560   // For each operands to the ADD which are BUILD_VECTORs,
5561   // check to see if each of their operands are an EXTRACT_VECTOR with
5562   // the same vector and appropriate index.
5563   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
5564     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
5565         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
5566
5567       SDValue ExtVec0 = N0->getOperand(i);
5568       SDValue ExtVec1 = N1->getOperand(i);
5569
5570       // First operand is the vector, verify its the same.
5571       if (V != ExtVec0->getOperand(0).getNode() ||
5572           V != ExtVec1->getOperand(0).getNode())
5573         return SDValue();
5574
5575       // Second is the constant, verify its correct.
5576       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
5577       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
5578
5579       // For the constant, we want to see all the even or all the odd.
5580       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
5581           || C1->getZExtValue() != nextIndex+1)
5582         return SDValue();
5583
5584       // Increment index.
5585       nextIndex+=2;
5586     } else
5587       return SDValue();
5588   }
5589
5590   // Create VPADDL node.
5591   SelectionDAG &DAG = DCI.DAG;
5592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5593
5594   // Build operand list.
5595   SmallVector<SDValue, 8> Ops;
5596   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
5597                                 TLI.getPointerTy()));
5598
5599   // Input is the vector.
5600   Ops.push_back(Vec);
5601
5602   // Get widened type and narrowed type.
5603   MVT widenType;
5604   unsigned numElem = VT.getVectorNumElements();
5605   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
5606     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
5607     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
5608     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
5609     default:
5610       assert(0 && "Invalid vector element type for padd optimization.");
5611   }
5612
5613   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
5614                             widenType, &Ops[0], Ops.size());
5615   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
5616 }
5617
5618 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
5619 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
5620 /// called with the default operands, and if that fails, with commuted
5621 /// operands.
5622 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
5623                                           TargetLowering::DAGCombinerInfo &DCI,
5624                                           const ARMSubtarget *Subtarget){
5625
5626   // Attempt to create vpaddl for this add.
5627   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
5628   if (Result.getNode())
5629     return Result;
5630
5631   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
5632   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
5633     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
5634     if (Result.getNode()) return Result;
5635   }
5636   return SDValue();
5637 }
5638
5639 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
5640 ///
5641 static SDValue PerformADDCombine(SDNode *N,
5642                                  TargetLowering::DAGCombinerInfo &DCI,
5643                                  const ARMSubtarget *Subtarget) {
5644   SDValue N0 = N->getOperand(0);
5645   SDValue N1 = N->getOperand(1);
5646
5647   // First try with the default operand order.
5648   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
5649   if (Result.getNode())
5650     return Result;
5651
5652   // If that didn't work, try again with the operands commuted.
5653   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
5654 }
5655
5656 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
5657 ///
5658 static SDValue PerformSUBCombine(SDNode *N,
5659                                  TargetLowering::DAGCombinerInfo &DCI) {
5660   SDValue N0 = N->getOperand(0);
5661   SDValue N1 = N->getOperand(1);
5662
5663   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
5664   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
5665     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
5666     if (Result.getNode()) return Result;
5667   }
5668
5669   return SDValue();
5670 }
5671
5672 /// PerformVMULCombine
5673 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
5674 /// special multiplier accumulator forwarding.
5675 ///   vmul d3, d0, d2
5676 ///   vmla d3, d1, d2
5677 /// is faster than
5678 ///   vadd d3, d0, d1
5679 ///   vmul d3, d3, d2
5680 static SDValue PerformVMULCombine(SDNode *N,
5681                                   TargetLowering::DAGCombinerInfo &DCI,
5682                                   const ARMSubtarget *Subtarget) {
5683   if (!Subtarget->hasVMLxForwarding())
5684     return SDValue();
5685
5686   SelectionDAG &DAG = DCI.DAG;
5687   SDValue N0 = N->getOperand(0);
5688   SDValue N1 = N->getOperand(1);
5689   unsigned Opcode = N0.getOpcode();
5690   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
5691       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
5692     Opcode = N1.getOpcode();
5693     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
5694         Opcode != ISD::FADD && Opcode != ISD::FSUB)
5695       return SDValue();
5696     std::swap(N0, N1);
5697   }
5698
5699   EVT VT = N->getValueType(0);
5700   DebugLoc DL = N->getDebugLoc();
5701   SDValue N00 = N0->getOperand(0);
5702   SDValue N01 = N0->getOperand(1);
5703   return DAG.getNode(Opcode, DL, VT,
5704                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
5705                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
5706 }
5707
5708 static SDValue PerformMULCombine(SDNode *N,
5709                                  TargetLowering::DAGCombinerInfo &DCI,
5710                                  const ARMSubtarget *Subtarget) {
5711   SelectionDAG &DAG = DCI.DAG;
5712
5713   if (Subtarget->isThumb1Only())
5714     return SDValue();
5715
5716   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
5717     return SDValue();
5718
5719   EVT VT = N->getValueType(0);
5720   if (VT.is64BitVector() || VT.is128BitVector())
5721     return PerformVMULCombine(N, DCI, Subtarget);
5722   if (VT != MVT::i32)
5723     return SDValue();
5724
5725   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
5726   if (!C)
5727     return SDValue();
5728
5729   uint64_t MulAmt = C->getZExtValue();
5730   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
5731   ShiftAmt = ShiftAmt & (32 - 1);
5732   SDValue V = N->getOperand(0);
5733   DebugLoc DL = N->getDebugLoc();
5734
5735   SDValue Res;
5736   MulAmt >>= ShiftAmt;
5737   if (isPowerOf2_32(MulAmt - 1)) {
5738     // (mul x, 2^N + 1) => (add (shl x, N), x)
5739     Res = DAG.getNode(ISD::ADD, DL, VT,
5740                       V, DAG.getNode(ISD::SHL, DL, VT,
5741                                      V, DAG.getConstant(Log2_32(MulAmt-1),
5742                                                         MVT::i32)));
5743   } else if (isPowerOf2_32(MulAmt + 1)) {
5744     // (mul x, 2^N - 1) => (sub (shl x, N), x)
5745     Res = DAG.getNode(ISD::SUB, DL, VT,
5746                       DAG.getNode(ISD::SHL, DL, VT,
5747                                   V, DAG.getConstant(Log2_32(MulAmt+1),
5748                                                      MVT::i32)),
5749                                                      V);
5750   } else
5751     return SDValue();
5752
5753   if (ShiftAmt != 0)
5754     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
5755                       DAG.getConstant(ShiftAmt, MVT::i32));
5756
5757   // Do not add new nodes to DAG combiner worklist.
5758   DCI.CombineTo(N, Res, false);
5759   return SDValue();
5760 }
5761
5762 static SDValue PerformANDCombine(SDNode *N,
5763                                 TargetLowering::DAGCombinerInfo &DCI) {
5764
5765   // Attempt to use immediate-form VBIC
5766   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
5767   DebugLoc dl = N->getDebugLoc();
5768   EVT VT = N->getValueType(0);
5769   SelectionDAG &DAG = DCI.DAG;
5770
5771   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5772     return SDValue();
5773
5774   APInt SplatBits, SplatUndef;
5775   unsigned SplatBitSize;
5776   bool HasAnyUndefs;
5777   if (BVN &&
5778       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5779     if (SplatBitSize <= 64) {
5780       EVT VbicVT;
5781       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
5782                                       SplatUndef.getZExtValue(), SplatBitSize,
5783                                       DAG, VbicVT, VT.is128BitVector(),
5784                                       OtherModImm);
5785       if (Val.getNode()) {
5786         SDValue Input =
5787           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
5788         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
5789         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
5790       }
5791     }
5792   }
5793
5794   return SDValue();
5795 }
5796
5797 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
5798 static SDValue PerformORCombine(SDNode *N,
5799                                 TargetLowering::DAGCombinerInfo &DCI,
5800                                 const ARMSubtarget *Subtarget) {
5801   // Attempt to use immediate-form VORR
5802   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
5803   DebugLoc dl = N->getDebugLoc();
5804   EVT VT = N->getValueType(0);
5805   SelectionDAG &DAG = DCI.DAG;
5806
5807   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5808     return SDValue();
5809
5810   APInt SplatBits, SplatUndef;
5811   unsigned SplatBitSize;
5812   bool HasAnyUndefs;
5813   if (BVN && Subtarget->hasNEON() &&
5814       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5815     if (SplatBitSize <= 64) {
5816       EVT VorrVT;
5817       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5818                                       SplatUndef.getZExtValue(), SplatBitSize,
5819                                       DAG, VorrVT, VT.is128BitVector(),
5820                                       OtherModImm);
5821       if (Val.getNode()) {
5822         SDValue Input =
5823           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
5824         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
5825         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
5826       }
5827     }
5828   }
5829
5830   SDValue N0 = N->getOperand(0);
5831   if (N0.getOpcode() != ISD::AND)
5832     return SDValue();
5833   SDValue N1 = N->getOperand(1);
5834
5835   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
5836   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
5837       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
5838     APInt SplatUndef;
5839     unsigned SplatBitSize;
5840     bool HasAnyUndefs;
5841
5842     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
5843     APInt SplatBits0;
5844     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
5845                                   HasAnyUndefs) && !HasAnyUndefs) {
5846       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
5847       APInt SplatBits1;
5848       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
5849                                     HasAnyUndefs) && !HasAnyUndefs &&
5850           SplatBits0 == ~SplatBits1) {
5851         // Canonicalize the vector type to make instruction selection simpler.
5852         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5853         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
5854                                      N0->getOperand(1), N0->getOperand(0),
5855                                      N1->getOperand(0));
5856         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
5857       }
5858     }
5859   }
5860
5861   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
5862   // reasonable.
5863
5864   // BFI is only available on V6T2+
5865   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
5866     return SDValue();
5867
5868   DebugLoc DL = N->getDebugLoc();
5869   // 1) or (and A, mask), val => ARMbfi A, val, mask
5870   //      iff (val & mask) == val
5871   //
5872   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
5873   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
5874   //          && mask == ~mask2
5875   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
5876   //          && ~mask == mask2
5877   //  (i.e., copy a bitfield value into another bitfield of the same width)
5878
5879   if (VT != MVT::i32)
5880     return SDValue();
5881
5882   SDValue N00 = N0.getOperand(0);
5883
5884   // The value and the mask need to be constants so we can verify this is
5885   // actually a bitfield set. If the mask is 0xffff, we can do better
5886   // via a movt instruction, so don't use BFI in that case.
5887   SDValue MaskOp = N0.getOperand(1);
5888   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
5889   if (!MaskC)
5890     return SDValue();
5891   unsigned Mask = MaskC->getZExtValue();
5892   if (Mask == 0xffff)
5893     return SDValue();
5894   SDValue Res;
5895   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
5896   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5897   if (N1C) {
5898     unsigned Val = N1C->getZExtValue();
5899     if ((Val & ~Mask) != Val)
5900       return SDValue();
5901
5902     if (ARM::isBitFieldInvertedMask(Mask)) {
5903       Val >>= CountTrailingZeros_32(~Mask);
5904
5905       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
5906                         DAG.getConstant(Val, MVT::i32),
5907                         DAG.getConstant(Mask, MVT::i32));
5908
5909       // Do not add new nodes to DAG combiner worklist.
5910       DCI.CombineTo(N, Res, false);
5911       return SDValue();
5912     }
5913   } else if (N1.getOpcode() == ISD::AND) {
5914     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
5915     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5916     if (!N11C)
5917       return SDValue();
5918     unsigned Mask2 = N11C->getZExtValue();
5919
5920     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
5921     // as is to match.
5922     if (ARM::isBitFieldInvertedMask(Mask) &&
5923         (Mask == ~Mask2)) {
5924       // The pack halfword instruction works better for masks that fit it,
5925       // so use that when it's available.
5926       if (Subtarget->hasT2ExtractPack() &&
5927           (Mask == 0xffff || Mask == 0xffff0000))
5928         return SDValue();
5929       // 2a
5930       unsigned amt = CountTrailingZeros_32(Mask2);
5931       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
5932                         DAG.getConstant(amt, MVT::i32));
5933       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
5934                         DAG.getConstant(Mask, MVT::i32));
5935       // Do not add new nodes to DAG combiner worklist.
5936       DCI.CombineTo(N, Res, false);
5937       return SDValue();
5938     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
5939                (~Mask == Mask2)) {
5940       // The pack halfword instruction works better for masks that fit it,
5941       // so use that when it's available.
5942       if (Subtarget->hasT2ExtractPack() &&
5943           (Mask2 == 0xffff || Mask2 == 0xffff0000))
5944         return SDValue();
5945       // 2b
5946       unsigned lsb = CountTrailingZeros_32(Mask);
5947       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
5948                         DAG.getConstant(lsb, MVT::i32));
5949       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
5950                         DAG.getConstant(Mask2, MVT::i32));
5951       // Do not add new nodes to DAG combiner worklist.
5952       DCI.CombineTo(N, Res, false);
5953       return SDValue();
5954     }
5955   }
5956
5957   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
5958       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
5959       ARM::isBitFieldInvertedMask(~Mask)) {
5960     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
5961     // where lsb(mask) == #shamt and masked bits of B are known zero.
5962     SDValue ShAmt = N00.getOperand(1);
5963     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5964     unsigned LSB = CountTrailingZeros_32(Mask);
5965     if (ShAmtC != LSB)
5966       return SDValue();
5967
5968     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
5969                       DAG.getConstant(~Mask, MVT::i32));
5970
5971     // Do not add new nodes to DAG combiner worklist.
5972     DCI.CombineTo(N, Res, false);
5973   }
5974
5975   return SDValue();
5976 }
5977
5978 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
5979 /// the bits being cleared by the AND are not demanded by the BFI.
5980 static SDValue PerformBFICombine(SDNode *N,
5981                                  TargetLowering::DAGCombinerInfo &DCI) {
5982   SDValue N1 = N->getOperand(1);
5983   if (N1.getOpcode() == ISD::AND) {
5984     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5985     if (!N11C)
5986       return SDValue();
5987     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
5988     unsigned LSB = CountTrailingZeros_32(~InvMask);
5989     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
5990     unsigned Mask = (1 << Width)-1;
5991     unsigned Mask2 = N11C->getZExtValue();
5992     if ((Mask & (~Mask2)) == 0)
5993       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
5994                              N->getOperand(0), N1.getOperand(0),
5995                              N->getOperand(2));
5996   }
5997   return SDValue();
5998 }
5999
6000 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
6001 /// ARMISD::VMOVRRD.
6002 static SDValue PerformVMOVRRDCombine(SDNode *N,
6003                                      TargetLowering::DAGCombinerInfo &DCI) {
6004   // vmovrrd(vmovdrr x, y) -> x,y
6005   SDValue InDouble = N->getOperand(0);
6006   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
6007     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
6008
6009   // vmovrrd(load f64) -> (load i32), (load i32)
6010   SDNode *InNode = InDouble.getNode();
6011   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
6012       InNode->getValueType(0) == MVT::f64 &&
6013       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
6014       !cast<LoadSDNode>(InNode)->isVolatile()) {
6015     // TODO: Should this be done for non-FrameIndex operands?
6016     LoadSDNode *LD = cast<LoadSDNode>(InNode);
6017
6018     SelectionDAG &DAG = DCI.DAG;
6019     DebugLoc DL = LD->getDebugLoc();
6020     SDValue BasePtr = LD->getBasePtr();
6021     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
6022                                  LD->getPointerInfo(), LD->isVolatile(),
6023                                  LD->isNonTemporal(), LD->getAlignment());
6024
6025     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
6026                                     DAG.getConstant(4, MVT::i32));
6027     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
6028                                  LD->getPointerInfo(), LD->isVolatile(),
6029                                  LD->isNonTemporal(),
6030                                  std::min(4U, LD->getAlignment() / 2));
6031
6032     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
6033     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
6034     DCI.RemoveFromWorklist(LD);
6035     DAG.DeleteNode(LD);
6036     return Result;
6037   }
6038
6039   return SDValue();
6040 }
6041
6042 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
6043 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
6044 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
6045   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
6046   SDValue Op0 = N->getOperand(0);
6047   SDValue Op1 = N->getOperand(1);
6048   if (Op0.getOpcode() == ISD::BITCAST)
6049     Op0 = Op0.getOperand(0);
6050   if (Op1.getOpcode() == ISD::BITCAST)
6051     Op1 = Op1.getOperand(0);
6052   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
6053       Op0.getNode() == Op1.getNode() &&
6054       Op0.getResNo() == 0 && Op1.getResNo() == 1)
6055     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6056                        N->getValueType(0), Op0.getOperand(0));
6057   return SDValue();
6058 }
6059
6060 /// PerformSTORECombine - Target-specific dag combine xforms for
6061 /// ISD::STORE.
6062 static SDValue PerformSTORECombine(SDNode *N,
6063                                    TargetLowering::DAGCombinerInfo &DCI) {
6064   // Bitcast an i64 store extracted from a vector to f64.
6065   // Otherwise, the i64 value will be legalized to a pair of i32 values.
6066   StoreSDNode *St = cast<StoreSDNode>(N);
6067   SDValue StVal = St->getValue();
6068   if (!ISD::isNormalStore(St) || St->isVolatile())
6069     return SDValue();
6070
6071   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
6072       StVal.getNode()->hasOneUse() && !St->isVolatile()) {
6073     SelectionDAG  &DAG = DCI.DAG;
6074     DebugLoc DL = St->getDebugLoc();
6075     SDValue BasePtr = St->getBasePtr();
6076     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
6077                                   StVal.getNode()->getOperand(0), BasePtr,
6078                                   St->getPointerInfo(), St->isVolatile(),
6079                                   St->isNonTemporal(), St->getAlignment());
6080
6081     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
6082                                     DAG.getConstant(4, MVT::i32));
6083     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
6084                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
6085                         St->isNonTemporal(),
6086                         std::min(4U, St->getAlignment() / 2));
6087   }
6088
6089   if (StVal.getValueType() != MVT::i64 ||
6090       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6091     return SDValue();
6092
6093   SelectionDAG &DAG = DCI.DAG;
6094   DebugLoc dl = StVal.getDebugLoc();
6095   SDValue IntVec = StVal.getOperand(0);
6096   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
6097                                  IntVec.getValueType().getVectorNumElements());
6098   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
6099   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6100                                Vec, StVal.getOperand(1));
6101   dl = N->getDebugLoc();
6102   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
6103   // Make the DAGCombiner fold the bitcasts.
6104   DCI.AddToWorklist(Vec.getNode());
6105   DCI.AddToWorklist(ExtElt.getNode());
6106   DCI.AddToWorklist(V.getNode());
6107   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
6108                       St->getPointerInfo(), St->isVolatile(),
6109                       St->isNonTemporal(), St->getAlignment(),
6110                       St->getTBAAInfo());
6111 }
6112
6113 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
6114 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
6115 /// i64 vector to have f64 elements, since the value can then be loaded
6116 /// directly into a VFP register.
6117 static bool hasNormalLoadOperand(SDNode *N) {
6118   unsigned NumElts = N->getValueType(0).getVectorNumElements();
6119   for (unsigned i = 0; i < NumElts; ++i) {
6120     SDNode *Elt = N->getOperand(i).getNode();
6121     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
6122       return true;
6123   }
6124   return false;
6125 }
6126
6127 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
6128 /// ISD::BUILD_VECTOR.
6129 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
6130                                           TargetLowering::DAGCombinerInfo &DCI){
6131   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
6132   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
6133   // into a pair of GPRs, which is fine when the value is used as a scalar,
6134   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
6135   SelectionDAG &DAG = DCI.DAG;
6136   if (N->getNumOperands() == 2) {
6137     SDValue RV = PerformVMOVDRRCombine(N, DAG);
6138     if (RV.getNode())
6139       return RV;
6140   }
6141
6142   // Load i64 elements as f64 values so that type legalization does not split
6143   // them up into i32 values.
6144   EVT VT = N->getValueType(0);
6145   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
6146     return SDValue();
6147   DebugLoc dl = N->getDebugLoc();
6148   SmallVector<SDValue, 8> Ops;
6149   unsigned NumElts = VT.getVectorNumElements();
6150   for (unsigned i = 0; i < NumElts; ++i) {
6151     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
6152     Ops.push_back(V);
6153     // Make the DAGCombiner fold the bitcast.
6154     DCI.AddToWorklist(V.getNode());
6155   }
6156   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
6157   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
6158   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
6159 }
6160
6161 /// PerformInsertEltCombine - Target-specific dag combine xforms for
6162 /// ISD::INSERT_VECTOR_ELT.
6163 static SDValue PerformInsertEltCombine(SDNode *N,
6164                                        TargetLowering::DAGCombinerInfo &DCI) {
6165   // Bitcast an i64 load inserted into a vector to f64.
6166   // Otherwise, the i64 value will be legalized to a pair of i32 values.
6167   EVT VT = N->getValueType(0);
6168   SDNode *Elt = N->getOperand(1).getNode();
6169   if (VT.getVectorElementType() != MVT::i64 ||
6170       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
6171     return SDValue();
6172
6173   SelectionDAG &DAG = DCI.DAG;
6174   DebugLoc dl = N->getDebugLoc();
6175   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
6176                                  VT.getVectorNumElements());
6177   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
6178   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
6179   // Make the DAGCombiner fold the bitcasts.
6180   DCI.AddToWorklist(Vec.getNode());
6181   DCI.AddToWorklist(V.getNode());
6182   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
6183                                Vec, V, N->getOperand(2));
6184   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
6185 }
6186
6187 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
6188 /// ISD::VECTOR_SHUFFLE.
6189 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
6190   // The LLVM shufflevector instruction does not require the shuffle mask
6191   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
6192   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
6193   // operands do not match the mask length, they are extended by concatenating
6194   // them with undef vectors.  That is probably the right thing for other
6195   // targets, but for NEON it is better to concatenate two double-register
6196   // size vector operands into a single quad-register size vector.  Do that
6197   // transformation here:
6198   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
6199   //   shuffle(concat(v1, v2), undef)
6200   SDValue Op0 = N->getOperand(0);
6201   SDValue Op1 = N->getOperand(1);
6202   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
6203       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
6204       Op0.getNumOperands() != 2 ||
6205       Op1.getNumOperands() != 2)
6206     return SDValue();
6207   SDValue Concat0Op1 = Op0.getOperand(1);
6208   SDValue Concat1Op1 = Op1.getOperand(1);
6209   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
6210       Concat1Op1.getOpcode() != ISD::UNDEF)
6211     return SDValue();
6212   // Skip the transformation if any of the types are illegal.
6213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6214   EVT VT = N->getValueType(0);
6215   if (!TLI.isTypeLegal(VT) ||
6216       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
6217       !TLI.isTypeLegal(Concat1Op1.getValueType()))
6218     return SDValue();
6219
6220   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
6221                                   Op0.getOperand(0), Op1.getOperand(0));
6222   // Translate the shuffle mask.
6223   SmallVector<int, 16> NewMask;
6224   unsigned NumElts = VT.getVectorNumElements();
6225   unsigned HalfElts = NumElts/2;
6226   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6227   for (unsigned n = 0; n < NumElts; ++n) {
6228     int MaskElt = SVN->getMaskElt(n);
6229     int NewElt = -1;
6230     if (MaskElt < (int)HalfElts)
6231       NewElt = MaskElt;
6232     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
6233       NewElt = HalfElts + MaskElt - NumElts;
6234     NewMask.push_back(NewElt);
6235   }
6236   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
6237                               DAG.getUNDEF(VT), NewMask.data());
6238 }
6239
6240 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
6241 /// NEON load/store intrinsics to merge base address updates.
6242 static SDValue CombineBaseUpdate(SDNode *N,
6243                                  TargetLowering::DAGCombinerInfo &DCI) {
6244   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6245     return SDValue();
6246
6247   SelectionDAG &DAG = DCI.DAG;
6248   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
6249                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
6250   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
6251   SDValue Addr = N->getOperand(AddrOpIdx);
6252
6253   // Search for a use of the address operand that is an increment.
6254   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
6255          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
6256     SDNode *User = *UI;
6257     if (User->getOpcode() != ISD::ADD ||
6258         UI.getUse().getResNo() != Addr.getResNo())
6259       continue;
6260
6261     // Check that the add is independent of the load/store.  Otherwise, folding
6262     // it would create a cycle.
6263     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
6264       continue;
6265
6266     // Find the new opcode for the updating load/store.
6267     bool isLoad = true;
6268     bool isLaneOp = false;
6269     unsigned NewOpc = 0;
6270     unsigned NumVecs = 0;
6271     if (isIntrinsic) {
6272       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
6273       switch (IntNo) {
6274       default: assert(0 && "unexpected intrinsic for Neon base update");
6275       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
6276         NumVecs = 1; break;
6277       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
6278         NumVecs = 2; break;
6279       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
6280         NumVecs = 3; break;
6281       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
6282         NumVecs = 4; break;
6283       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
6284         NumVecs = 2; isLaneOp = true; break;
6285       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
6286         NumVecs = 3; isLaneOp = true; break;
6287       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
6288         NumVecs = 4; isLaneOp = true; break;
6289       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
6290         NumVecs = 1; isLoad = false; break;
6291       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
6292         NumVecs = 2; isLoad = false; break;
6293       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
6294         NumVecs = 3; isLoad = false; break;
6295       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
6296         NumVecs = 4; isLoad = false; break;
6297       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
6298         NumVecs = 2; isLoad = false; isLaneOp = true; break;
6299       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
6300         NumVecs = 3; isLoad = false; isLaneOp = true; break;
6301       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
6302         NumVecs = 4; isLoad = false; isLaneOp = true; break;
6303       }
6304     } else {
6305       isLaneOp = true;
6306       switch (N->getOpcode()) {
6307       default: assert(0 && "unexpected opcode for Neon base update");
6308       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
6309       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
6310       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
6311       }
6312     }
6313
6314     // Find the size of memory referenced by the load/store.
6315     EVT VecTy;
6316     if (isLoad)
6317       VecTy = N->getValueType(0);
6318     else
6319       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
6320     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
6321     if (isLaneOp)
6322       NumBytes /= VecTy.getVectorNumElements();
6323
6324     // If the increment is a constant, it must match the memory ref size.
6325     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
6326     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
6327       uint64_t IncVal = CInc->getZExtValue();
6328       if (IncVal != NumBytes)
6329         continue;
6330     } else if (NumBytes >= 3 * 16) {
6331       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
6332       // separate instructions that make it harder to use a non-constant update.
6333       continue;
6334     }
6335
6336     // Create the new updating load/store node.
6337     EVT Tys[6];
6338     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
6339     unsigned n;
6340     for (n = 0; n < NumResultVecs; ++n)
6341       Tys[n] = VecTy;
6342     Tys[n++] = MVT::i32;
6343     Tys[n] = MVT::Other;
6344     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
6345     SmallVector<SDValue, 8> Ops;
6346     Ops.push_back(N->getOperand(0)); // incoming chain
6347     Ops.push_back(N->getOperand(AddrOpIdx));
6348     Ops.push_back(Inc);
6349     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
6350       Ops.push_back(N->getOperand(i));
6351     }
6352     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
6353     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
6354                                            Ops.data(), Ops.size(),
6355                                            MemInt->getMemoryVT(),
6356                                            MemInt->getMemOperand());
6357
6358     // Update the uses.
6359     std::vector<SDValue> NewResults;
6360     for (unsigned i = 0; i < NumResultVecs; ++i) {
6361       NewResults.push_back(SDValue(UpdN.getNode(), i));
6362     }
6363     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
6364     DCI.CombineTo(N, NewResults);
6365     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
6366
6367     break;
6368   }
6369   return SDValue();
6370 }
6371
6372 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
6373 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
6374 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
6375 /// return true.
6376 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
6377   SelectionDAG &DAG = DCI.DAG;
6378   EVT VT = N->getValueType(0);
6379   // vldN-dup instructions only support 64-bit vectors for N > 1.
6380   if (!VT.is64BitVector())
6381     return false;
6382
6383   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
6384   SDNode *VLD = N->getOperand(0).getNode();
6385   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
6386     return false;
6387   unsigned NumVecs = 0;
6388   unsigned NewOpc = 0;
6389   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
6390   if (IntNo == Intrinsic::arm_neon_vld2lane) {
6391     NumVecs = 2;
6392     NewOpc = ARMISD::VLD2DUP;
6393   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
6394     NumVecs = 3;
6395     NewOpc = ARMISD::VLD3DUP;
6396   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
6397     NumVecs = 4;
6398     NewOpc = ARMISD::VLD4DUP;
6399   } else {
6400     return false;
6401   }
6402
6403   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
6404   // numbers match the load.
6405   unsigned VLDLaneNo =
6406     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
6407   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
6408        UI != UE; ++UI) {
6409     // Ignore uses of the chain result.
6410     if (UI.getUse().getResNo() == NumVecs)
6411       continue;
6412     SDNode *User = *UI;
6413     if (User->getOpcode() != ARMISD::VDUPLANE ||
6414         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
6415       return false;
6416   }
6417
6418   // Create the vldN-dup node.
6419   EVT Tys[5];
6420   unsigned n;
6421   for (n = 0; n < NumVecs; ++n)
6422     Tys[n] = VT;
6423   Tys[n] = MVT::Other;
6424   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
6425   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
6426   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
6427   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
6428                                            Ops, 2, VLDMemInt->getMemoryVT(),
6429                                            VLDMemInt->getMemOperand());
6430
6431   // Update the uses.
6432   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
6433        UI != UE; ++UI) {
6434     unsigned ResNo = UI.getUse().getResNo();
6435     // Ignore uses of the chain result.
6436     if (ResNo == NumVecs)
6437       continue;
6438     SDNode *User = *UI;
6439     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
6440   }
6441
6442   // Now the vldN-lane intrinsic is dead except for its chain result.
6443   // Update uses of the chain.
6444   std::vector<SDValue> VLDDupResults;
6445   for (unsigned n = 0; n < NumVecs; ++n)
6446     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
6447   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
6448   DCI.CombineTo(VLD, VLDDupResults);
6449
6450   return true;
6451 }
6452
6453 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
6454 /// ARMISD::VDUPLANE.
6455 static SDValue PerformVDUPLANECombine(SDNode *N,
6456                                       TargetLowering::DAGCombinerInfo &DCI) {
6457   SDValue Op = N->getOperand(0);
6458
6459   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
6460   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
6461   if (CombineVLDDUP(N, DCI))
6462     return SDValue(N, 0);
6463
6464   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
6465   // redundant.  Ignore bit_converts for now; element sizes are checked below.
6466   while (Op.getOpcode() == ISD::BITCAST)
6467     Op = Op.getOperand(0);
6468   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
6469     return SDValue();
6470
6471   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
6472   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
6473   // The canonical VMOV for a zero vector uses a 32-bit element size.
6474   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6475   unsigned EltBits;
6476   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
6477     EltSize = 8;
6478   EVT VT = N->getValueType(0);
6479   if (EltSize > VT.getVectorElementType().getSizeInBits())
6480     return SDValue();
6481
6482   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
6483 }
6484
6485 // isConstVecPow2 - Return true if each vector element is a power of 2, all
6486 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
6487 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
6488 {
6489   integerPart cN;
6490   integerPart c0 = 0;
6491   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
6492        I != E; I++) {
6493     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
6494     if (!C)
6495       return false;
6496
6497     bool isExact;
6498     APFloat APF = C->getValueAPF();
6499     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
6500         != APFloat::opOK || !isExact)
6501       return false;
6502
6503     c0 = (I == 0) ? cN : c0;
6504     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
6505       return false;
6506   }
6507   C = c0;
6508   return true;
6509 }
6510
6511 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
6512 /// can replace combinations of VMUL and VCVT (floating-point to integer)
6513 /// when the VMUL has a constant operand that is a power of 2.
6514 ///
6515 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
6516 ///  vmul.f32        d16, d17, d16
6517 ///  vcvt.s32.f32    d16, d16
6518 /// becomes:
6519 ///  vcvt.s32.f32    d16, d16, #3
6520 static SDValue PerformVCVTCombine(SDNode *N,
6521                                   TargetLowering::DAGCombinerInfo &DCI,
6522                                   const ARMSubtarget *Subtarget) {
6523   SelectionDAG &DAG = DCI.DAG;
6524   SDValue Op = N->getOperand(0);
6525
6526   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
6527       Op.getOpcode() != ISD::FMUL)
6528     return SDValue();
6529
6530   uint64_t C;
6531   SDValue N0 = Op->getOperand(0);
6532   SDValue ConstVec = Op->getOperand(1);
6533   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
6534
6535   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
6536       !isConstVecPow2(ConstVec, isSigned, C))
6537     return SDValue();
6538
6539   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
6540     Intrinsic::arm_neon_vcvtfp2fxu;
6541   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6542                      N->getValueType(0),
6543                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
6544                      DAG.getConstant(Log2_64(C), MVT::i32));
6545 }
6546
6547 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
6548 /// can replace combinations of VCVT (integer to floating-point) and VDIV
6549 /// when the VDIV has a constant operand that is a power of 2.
6550 ///
6551 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
6552 ///  vcvt.f32.s32    d16, d16
6553 ///  vdiv.f32        d16, d17, d16
6554 /// becomes:
6555 ///  vcvt.f32.s32    d16, d16, #3
6556 static SDValue PerformVDIVCombine(SDNode *N,
6557                                   TargetLowering::DAGCombinerInfo &DCI,
6558                                   const ARMSubtarget *Subtarget) {
6559   SelectionDAG &DAG = DCI.DAG;
6560   SDValue Op = N->getOperand(0);
6561   unsigned OpOpcode = Op.getNode()->getOpcode();
6562
6563   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
6564       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
6565     return SDValue();
6566
6567   uint64_t C;
6568   SDValue ConstVec = N->getOperand(1);
6569   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
6570
6571   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
6572       !isConstVecPow2(ConstVec, isSigned, C))
6573     return SDValue();
6574
6575   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
6576     Intrinsic::arm_neon_vcvtfxu2fp;
6577   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6578                      Op.getValueType(),
6579                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
6580                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
6581 }
6582
6583 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6584 /// operand of a vector shift operation, where all the elements of the
6585 /// build_vector must have the same constant integer value.
6586 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6587   // Ignore bit_converts.
6588   while (Op.getOpcode() == ISD::BITCAST)
6589     Op = Op.getOperand(0);
6590   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6591   APInt SplatBits, SplatUndef;
6592   unsigned SplatBitSize;
6593   bool HasAnyUndefs;
6594   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6595                                       HasAnyUndefs, ElementBits) ||
6596       SplatBitSize > ElementBits)
6597     return false;
6598   Cnt = SplatBits.getSExtValue();
6599   return true;
6600 }
6601
6602 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6603 /// operand of a vector shift left operation.  That value must be in the range:
6604 ///   0 <= Value < ElementBits for a left shift; or
6605 ///   0 <= Value <= ElementBits for a long left shift.
6606 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6607   assert(VT.isVector() && "vector shift count is not a vector type");
6608   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6609   if (! getVShiftImm(Op, ElementBits, Cnt))
6610     return false;
6611   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
6612 }
6613
6614 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6615 /// operand of a vector shift right operation.  For a shift opcode, the value
6616 /// is positive, but for an intrinsic the value count must be negative. The
6617 /// absolute value must be in the range:
6618 ///   1 <= |Value| <= ElementBits for a right shift; or
6619 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6620 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6621                          int64_t &Cnt) {
6622   assert(VT.isVector() && "vector shift count is not a vector type");
6623   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6624   if (! getVShiftImm(Op, ElementBits, Cnt))
6625     return false;
6626   if (isIntrinsic)
6627     Cnt = -Cnt;
6628   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
6629 }
6630
6631 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
6632 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
6633   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6634   switch (IntNo) {
6635   default:
6636     // Don't do anything for most intrinsics.
6637     break;
6638
6639   // Vector shifts: check for immediate versions and lower them.
6640   // Note: This is done during DAG combining instead of DAG legalizing because
6641   // the build_vectors for 64-bit vector element shift counts are generally
6642   // not legal, and it is hard to see their values after they get legalized to
6643   // loads from a constant pool.
6644   case Intrinsic::arm_neon_vshifts:
6645   case Intrinsic::arm_neon_vshiftu:
6646   case Intrinsic::arm_neon_vshiftls:
6647   case Intrinsic::arm_neon_vshiftlu:
6648   case Intrinsic::arm_neon_vshiftn:
6649   case Intrinsic::arm_neon_vrshifts:
6650   case Intrinsic::arm_neon_vrshiftu:
6651   case Intrinsic::arm_neon_vrshiftn:
6652   case Intrinsic::arm_neon_vqshifts:
6653   case Intrinsic::arm_neon_vqshiftu:
6654   case Intrinsic::arm_neon_vqshiftsu:
6655   case Intrinsic::arm_neon_vqshiftns:
6656   case Intrinsic::arm_neon_vqshiftnu:
6657   case Intrinsic::arm_neon_vqshiftnsu:
6658   case Intrinsic::arm_neon_vqrshiftns:
6659   case Intrinsic::arm_neon_vqrshiftnu:
6660   case Intrinsic::arm_neon_vqrshiftnsu: {
6661     EVT VT = N->getOperand(1).getValueType();
6662     int64_t Cnt;
6663     unsigned VShiftOpc = 0;
6664
6665     switch (IntNo) {
6666     case Intrinsic::arm_neon_vshifts:
6667     case Intrinsic::arm_neon_vshiftu:
6668       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
6669         VShiftOpc = ARMISD::VSHL;
6670         break;
6671       }
6672       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
6673         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
6674                      ARMISD::VSHRs : ARMISD::VSHRu);
6675         break;
6676       }
6677       return SDValue();
6678
6679     case Intrinsic::arm_neon_vshiftls:
6680     case Intrinsic::arm_neon_vshiftlu:
6681       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
6682         break;
6683       llvm_unreachable("invalid shift count for vshll intrinsic");
6684
6685     case Intrinsic::arm_neon_vrshifts:
6686     case Intrinsic::arm_neon_vrshiftu:
6687       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
6688         break;
6689       return SDValue();
6690
6691     case Intrinsic::arm_neon_vqshifts:
6692     case Intrinsic::arm_neon_vqshiftu:
6693       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
6694         break;
6695       return SDValue();
6696
6697     case Intrinsic::arm_neon_vqshiftsu:
6698       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
6699         break;
6700       llvm_unreachable("invalid shift count for vqshlu intrinsic");
6701
6702     case Intrinsic::arm_neon_vshiftn:
6703     case Intrinsic::arm_neon_vrshiftn:
6704     case Intrinsic::arm_neon_vqshiftns:
6705     case Intrinsic::arm_neon_vqshiftnu:
6706     case Intrinsic::arm_neon_vqshiftnsu:
6707     case Intrinsic::arm_neon_vqrshiftns:
6708     case Intrinsic::arm_neon_vqrshiftnu:
6709     case Intrinsic::arm_neon_vqrshiftnsu:
6710       // Narrowing shifts require an immediate right shift.
6711       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
6712         break;
6713       llvm_unreachable("invalid shift count for narrowing vector shift "
6714                        "intrinsic");
6715
6716     default:
6717       llvm_unreachable("unhandled vector shift");
6718     }
6719
6720     switch (IntNo) {
6721     case Intrinsic::arm_neon_vshifts:
6722     case Intrinsic::arm_neon_vshiftu:
6723       // Opcode already set above.
6724       break;
6725     case Intrinsic::arm_neon_vshiftls:
6726     case Intrinsic::arm_neon_vshiftlu:
6727       if (Cnt == VT.getVectorElementType().getSizeInBits())
6728         VShiftOpc = ARMISD::VSHLLi;
6729       else
6730         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
6731                      ARMISD::VSHLLs : ARMISD::VSHLLu);
6732       break;
6733     case Intrinsic::arm_neon_vshiftn:
6734       VShiftOpc = ARMISD::VSHRN; break;
6735     case Intrinsic::arm_neon_vrshifts:
6736       VShiftOpc = ARMISD::VRSHRs; break;
6737     case Intrinsic::arm_neon_vrshiftu:
6738       VShiftOpc = ARMISD::VRSHRu; break;
6739     case Intrinsic::arm_neon_vrshiftn:
6740       VShiftOpc = ARMISD::VRSHRN; break;
6741     case Intrinsic::arm_neon_vqshifts:
6742       VShiftOpc = ARMISD::VQSHLs; break;
6743     case Intrinsic::arm_neon_vqshiftu:
6744       VShiftOpc = ARMISD::VQSHLu; break;
6745     case Intrinsic::arm_neon_vqshiftsu:
6746       VShiftOpc = ARMISD::VQSHLsu; break;
6747     case Intrinsic::arm_neon_vqshiftns:
6748       VShiftOpc = ARMISD::VQSHRNs; break;
6749     case Intrinsic::arm_neon_vqshiftnu:
6750       VShiftOpc = ARMISD::VQSHRNu; break;
6751     case Intrinsic::arm_neon_vqshiftnsu:
6752       VShiftOpc = ARMISD::VQSHRNsu; break;
6753     case Intrinsic::arm_neon_vqrshiftns:
6754       VShiftOpc = ARMISD::VQRSHRNs; break;
6755     case Intrinsic::arm_neon_vqrshiftnu:
6756       VShiftOpc = ARMISD::VQRSHRNu; break;
6757     case Intrinsic::arm_neon_vqrshiftnsu:
6758       VShiftOpc = ARMISD::VQRSHRNsu; break;
6759     }
6760
6761     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
6762                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
6763   }
6764
6765   case Intrinsic::arm_neon_vshiftins: {
6766     EVT VT = N->getOperand(1).getValueType();
6767     int64_t Cnt;
6768     unsigned VShiftOpc = 0;
6769
6770     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
6771       VShiftOpc = ARMISD::VSLI;
6772     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
6773       VShiftOpc = ARMISD::VSRI;
6774     else {
6775       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
6776     }
6777
6778     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
6779                        N->getOperand(1), N->getOperand(2),
6780                        DAG.getConstant(Cnt, MVT::i32));
6781   }
6782
6783   case Intrinsic::arm_neon_vqrshifts:
6784   case Intrinsic::arm_neon_vqrshiftu:
6785     // No immediate versions of these to check for.
6786     break;
6787   }
6788
6789   return SDValue();
6790 }
6791
6792 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
6793 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
6794 /// combining instead of DAG legalizing because the build_vectors for 64-bit
6795 /// vector element shift counts are generally not legal, and it is hard to see
6796 /// their values after they get legalized to loads from a constant pool.
6797 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
6798                                    const ARMSubtarget *ST) {
6799   EVT VT = N->getValueType(0);
6800
6801   // Nothing to be done for scalar shifts.
6802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6803   if (!VT.isVector() || !TLI.isTypeLegal(VT))
6804     return SDValue();
6805
6806   assert(ST->hasNEON() && "unexpected vector shift");
6807   int64_t Cnt;
6808
6809   switch (N->getOpcode()) {
6810   default: llvm_unreachable("unexpected shift opcode");
6811
6812   case ISD::SHL:
6813     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6814       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
6815                          DAG.getConstant(Cnt, MVT::i32));
6816     break;
6817
6818   case ISD::SRA:
6819   case ISD::SRL:
6820     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6821       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
6822                             ARMISD::VSHRs : ARMISD::VSHRu);
6823       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
6824                          DAG.getConstant(Cnt, MVT::i32));
6825     }
6826   }
6827   return SDValue();
6828 }
6829
6830 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
6831 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
6832 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
6833                                     const ARMSubtarget *ST) {
6834   SDValue N0 = N->getOperand(0);
6835
6836   // Check for sign- and zero-extensions of vector extract operations of 8-
6837   // and 16-bit vector elements.  NEON supports these directly.  They are
6838   // handled during DAG combining because type legalization will promote them
6839   // to 32-bit types and it is messy to recognize the operations after that.
6840   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6841     SDValue Vec = N0.getOperand(0);
6842     SDValue Lane = N0.getOperand(1);
6843     EVT VT = N->getValueType(0);
6844     EVT EltVT = N0.getValueType();
6845     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6846
6847     if (VT == MVT::i32 &&
6848         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
6849         TLI.isTypeLegal(Vec.getValueType()) &&
6850         isa<ConstantSDNode>(Lane)) {
6851
6852       unsigned Opc = 0;
6853       switch (N->getOpcode()) {
6854       default: llvm_unreachable("unexpected opcode");
6855       case ISD::SIGN_EXTEND:
6856         Opc = ARMISD::VGETLANEs;
6857         break;
6858       case ISD::ZERO_EXTEND:
6859       case ISD::ANY_EXTEND:
6860         Opc = ARMISD::VGETLANEu;
6861         break;
6862       }
6863       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
6864     }
6865   }
6866
6867   return SDValue();
6868 }
6869
6870 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
6871 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
6872 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
6873                                        const ARMSubtarget *ST) {
6874   // If the target supports NEON, try to use vmax/vmin instructions for f32
6875   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
6876   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
6877   // a NaN; only do the transformation when it matches that behavior.
6878
6879   // For now only do this when using NEON for FP operations; if using VFP, it
6880   // is not obvious that the benefit outweighs the cost of switching to the
6881   // NEON pipeline.
6882   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
6883       N->getValueType(0) != MVT::f32)
6884     return SDValue();
6885
6886   SDValue CondLHS = N->getOperand(0);
6887   SDValue CondRHS = N->getOperand(1);
6888   SDValue LHS = N->getOperand(2);
6889   SDValue RHS = N->getOperand(3);
6890   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
6891
6892   unsigned Opcode = 0;
6893   bool IsReversed;
6894   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
6895     IsReversed = false; // x CC y ? x : y
6896   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
6897     IsReversed = true ; // x CC y ? y : x
6898   } else {
6899     return SDValue();
6900   }
6901
6902   bool IsUnordered;
6903   switch (CC) {
6904   default: break;
6905   case ISD::SETOLT:
6906   case ISD::SETOLE:
6907   case ISD::SETLT:
6908   case ISD::SETLE:
6909   case ISD::SETULT:
6910   case ISD::SETULE:
6911     // If LHS is NaN, an ordered comparison will be false and the result will
6912     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
6913     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
6914     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
6915     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
6916       break;
6917     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
6918     // will return -0, so vmin can only be used for unsafe math or if one of
6919     // the operands is known to be nonzero.
6920     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
6921         !UnsafeFPMath &&
6922         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
6923       break;
6924     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
6925     break;
6926
6927   case ISD::SETOGT:
6928   case ISD::SETOGE:
6929   case ISD::SETGT:
6930   case ISD::SETGE:
6931   case ISD::SETUGT:
6932   case ISD::SETUGE:
6933     // If LHS is NaN, an ordered comparison will be false and the result will
6934     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
6935     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
6936     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
6937     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
6938       break;
6939     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
6940     // will return +0, so vmax can only be used for unsafe math or if one of
6941     // the operands is known to be nonzero.
6942     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
6943         !UnsafeFPMath &&
6944         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
6945       break;
6946     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
6947     break;
6948   }
6949
6950   if (!Opcode)
6951     return SDValue();
6952   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
6953 }
6954
6955 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
6956                                              DAGCombinerInfo &DCI) const {
6957   switch (N->getOpcode()) {
6958   default: break;
6959   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
6960   case ISD::SUB:        return PerformSUBCombine(N, DCI);
6961   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
6962   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
6963   case ISD::AND:        return PerformANDCombine(N, DCI);
6964   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
6965   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
6966   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
6967   case ISD::STORE:      return PerformSTORECombine(N, DCI);
6968   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
6969   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
6970   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
6971   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
6972   case ISD::FP_TO_SINT:
6973   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
6974   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
6975   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
6976   case ISD::SHL:
6977   case ISD::SRA:
6978   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
6979   case ISD::SIGN_EXTEND:
6980   case ISD::ZERO_EXTEND:
6981   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
6982   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
6983   case ARMISD::VLD2DUP:
6984   case ARMISD::VLD3DUP:
6985   case ARMISD::VLD4DUP:
6986     return CombineBaseUpdate(N, DCI);
6987   case ISD::INTRINSIC_VOID:
6988   case ISD::INTRINSIC_W_CHAIN:
6989     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
6990     case Intrinsic::arm_neon_vld1:
6991     case Intrinsic::arm_neon_vld2:
6992     case Intrinsic::arm_neon_vld3:
6993     case Intrinsic::arm_neon_vld4:
6994     case Intrinsic::arm_neon_vld2lane:
6995     case Intrinsic::arm_neon_vld3lane:
6996     case Intrinsic::arm_neon_vld4lane:
6997     case Intrinsic::arm_neon_vst1:
6998     case Intrinsic::arm_neon_vst2:
6999     case Intrinsic::arm_neon_vst3:
7000     case Intrinsic::arm_neon_vst4:
7001     case Intrinsic::arm_neon_vst2lane:
7002     case Intrinsic::arm_neon_vst3lane:
7003     case Intrinsic::arm_neon_vst4lane:
7004       return CombineBaseUpdate(N, DCI);
7005     default: break;
7006     }
7007     break;
7008   }
7009   return SDValue();
7010 }
7011
7012 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
7013                                                           EVT VT) const {
7014   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
7015 }
7016
7017 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
7018   if (!Subtarget->allowsUnalignedMem())
7019     return false;
7020
7021   switch (VT.getSimpleVT().SimpleTy) {
7022   default:
7023     return false;
7024   case MVT::i8:
7025   case MVT::i16:
7026   case MVT::i32:
7027     return true;
7028   // FIXME: VLD1 etc with standard alignment is legal.
7029   }
7030 }
7031
7032 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
7033   if (V < 0)
7034     return false;
7035
7036   unsigned Scale = 1;
7037   switch (VT.getSimpleVT().SimpleTy) {
7038   default: return false;
7039   case MVT::i1:
7040   case MVT::i8:
7041     // Scale == 1;
7042     break;
7043   case MVT::i16:
7044     // Scale == 2;
7045     Scale = 2;
7046     break;
7047   case MVT::i32:
7048     // Scale == 4;
7049     Scale = 4;
7050     break;
7051   }
7052
7053   if ((V & (Scale - 1)) != 0)
7054     return false;
7055   V /= Scale;
7056   return V == (V & ((1LL << 5) - 1));
7057 }
7058
7059 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
7060                                       const ARMSubtarget *Subtarget) {
7061   bool isNeg = false;
7062   if (V < 0) {
7063     isNeg = true;
7064     V = - V;
7065   }
7066
7067   switch (VT.getSimpleVT().SimpleTy) {
7068   default: return false;
7069   case MVT::i1:
7070   case MVT::i8:
7071   case MVT::i16:
7072   case MVT::i32:
7073     // + imm12 or - imm8
7074     if (isNeg)
7075       return V == (V & ((1LL << 8) - 1));
7076     return V == (V & ((1LL << 12) - 1));
7077   case MVT::f32:
7078   case MVT::f64:
7079     // Same as ARM mode. FIXME: NEON?
7080     if (!Subtarget->hasVFP2())
7081       return false;
7082     if ((V & 3) != 0)
7083       return false;
7084     V >>= 2;
7085     return V == (V & ((1LL << 8) - 1));
7086   }
7087 }
7088
7089 /// isLegalAddressImmediate - Return true if the integer value can be used
7090 /// as the offset of the target addressing mode for load / store of the
7091 /// given type.
7092 static bool isLegalAddressImmediate(int64_t V, EVT VT,
7093                                     const ARMSubtarget *Subtarget) {
7094   if (V == 0)
7095     return true;
7096
7097   if (!VT.isSimple())
7098     return false;
7099
7100   if (Subtarget->isThumb1Only())
7101     return isLegalT1AddressImmediate(V, VT);
7102   else if (Subtarget->isThumb2())
7103     return isLegalT2AddressImmediate(V, VT, Subtarget);
7104
7105   // ARM mode.
7106   if (V < 0)
7107     V = - V;
7108   switch (VT.getSimpleVT().SimpleTy) {
7109   default: return false;
7110   case MVT::i1:
7111   case MVT::i8:
7112   case MVT::i32:
7113     // +- imm12
7114     return V == (V & ((1LL << 12) - 1));
7115   case MVT::i16:
7116     // +- imm8
7117     return V == (V & ((1LL << 8) - 1));
7118   case MVT::f32:
7119   case MVT::f64:
7120     if (!Subtarget->hasVFP2()) // FIXME: NEON?
7121       return false;
7122     if ((V & 3) != 0)
7123       return false;
7124     V >>= 2;
7125     return V == (V & ((1LL << 8) - 1));
7126   }
7127 }
7128
7129 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
7130                                                       EVT VT) const {
7131   int Scale = AM.Scale;
7132   if (Scale < 0)
7133     return false;
7134
7135   switch (VT.getSimpleVT().SimpleTy) {
7136   default: return false;
7137   case MVT::i1:
7138   case MVT::i8:
7139   case MVT::i16:
7140   case MVT::i32:
7141     if (Scale == 1)
7142       return true;
7143     // r + r << imm
7144     Scale = Scale & ~1;
7145     return Scale == 2 || Scale == 4 || Scale == 8;
7146   case MVT::i64:
7147     // r + r
7148     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
7149       return true;
7150     return false;
7151   case MVT::isVoid:
7152     // Note, we allow "void" uses (basically, uses that aren't loads or
7153     // stores), because arm allows folding a scale into many arithmetic
7154     // operations.  This should be made more precise and revisited later.
7155
7156     // Allow r << imm, but the imm has to be a multiple of two.
7157     if (Scale & 1) return false;
7158     return isPowerOf2_32(Scale);
7159   }
7160 }
7161
7162 /// isLegalAddressingMode - Return true if the addressing mode represented
7163 /// by AM is legal for this target, for a load/store of the specified type.
7164 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7165                                               const Type *Ty) const {
7166   EVT VT = getValueType(Ty, true);
7167   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
7168     return false;
7169
7170   // Can never fold addr of global into load/store.
7171   if (AM.BaseGV)
7172     return false;
7173
7174   switch (AM.Scale) {
7175   case 0:  // no scale reg, must be "r+i" or "r", or "i".
7176     break;
7177   case 1:
7178     if (Subtarget->isThumb1Only())
7179       return false;
7180     // FALL THROUGH.
7181   default:
7182     // ARM doesn't support any R+R*scale+imm addr modes.
7183     if (AM.BaseOffs)
7184       return false;
7185
7186     if (!VT.isSimple())
7187       return false;
7188
7189     if (Subtarget->isThumb2())
7190       return isLegalT2ScaledAddressingMode(AM, VT);
7191
7192     int Scale = AM.Scale;
7193     switch (VT.getSimpleVT().SimpleTy) {
7194     default: return false;
7195     case MVT::i1:
7196     case MVT::i8:
7197     case MVT::i32:
7198       if (Scale < 0) Scale = -Scale;
7199       if (Scale == 1)
7200         return true;
7201       // r + r << imm
7202       return isPowerOf2_32(Scale & ~1);
7203     case MVT::i16:
7204     case MVT::i64:
7205       // r + r
7206       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
7207         return true;
7208       return false;
7209
7210     case MVT::isVoid:
7211       // Note, we allow "void" uses (basically, uses that aren't loads or
7212       // stores), because arm allows folding a scale into many arithmetic
7213       // operations.  This should be made more precise and revisited later.
7214
7215       // Allow r << imm, but the imm has to be a multiple of two.
7216       if (Scale & 1) return false;
7217       return isPowerOf2_32(Scale);
7218     }
7219     break;
7220   }
7221   return true;
7222 }
7223
7224 /// isLegalICmpImmediate - Return true if the specified immediate is legal
7225 /// icmp immediate, that is the target has icmp instructions which can compare
7226 /// a register against the immediate without having to materialize the
7227 /// immediate into a register.
7228 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
7229   if (!Subtarget->isThumb())
7230     return ARM_AM::getSOImmVal(Imm) != -1;
7231   if (Subtarget->isThumb2())
7232     return ARM_AM::getT2SOImmVal(Imm) != -1;
7233   return Imm >= 0 && Imm <= 255;
7234 }
7235
7236 /// isLegalAddImmediate - Return true if the specified immediate is legal
7237 /// add immediate, that is the target has add instructions which can add
7238 /// a register with the immediate without having to materialize the
7239 /// immediate into a register.
7240 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
7241   return ARM_AM::getSOImmVal(Imm) != -1;
7242 }
7243
7244 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
7245                                       bool isSEXTLoad, SDValue &Base,
7246                                       SDValue &Offset, bool &isInc,
7247                                       SelectionDAG &DAG) {
7248   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
7249     return false;
7250
7251   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
7252     // AddressingMode 3
7253     Base = Ptr->getOperand(0);
7254     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
7255       int RHSC = (int)RHS->getZExtValue();
7256       if (RHSC < 0 && RHSC > -256) {
7257         assert(Ptr->getOpcode() == ISD::ADD);
7258         isInc = false;
7259         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
7260         return true;
7261       }
7262     }
7263     isInc = (Ptr->getOpcode() == ISD::ADD);
7264     Offset = Ptr->getOperand(1);
7265     return true;
7266   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
7267     // AddressingMode 2
7268     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
7269       int RHSC = (int)RHS->getZExtValue();
7270       if (RHSC < 0 && RHSC > -0x1000) {
7271         assert(Ptr->getOpcode() == ISD::ADD);
7272         isInc = false;
7273         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
7274         Base = Ptr->getOperand(0);
7275         return true;
7276       }
7277     }
7278
7279     if (Ptr->getOpcode() == ISD::ADD) {
7280       isInc = true;
7281       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
7282       if (ShOpcVal != ARM_AM::no_shift) {
7283         Base = Ptr->getOperand(1);
7284         Offset = Ptr->getOperand(0);
7285       } else {
7286         Base = Ptr->getOperand(0);
7287         Offset = Ptr->getOperand(1);
7288       }
7289       return true;
7290     }
7291
7292     isInc = (Ptr->getOpcode() == ISD::ADD);
7293     Base = Ptr->getOperand(0);
7294     Offset = Ptr->getOperand(1);
7295     return true;
7296   }
7297
7298   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
7299   return false;
7300 }
7301
7302 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
7303                                      bool isSEXTLoad, SDValue &Base,
7304                                      SDValue &Offset, bool &isInc,
7305                                      SelectionDAG &DAG) {
7306   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
7307     return false;
7308
7309   Base = Ptr->getOperand(0);
7310   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
7311     int RHSC = (int)RHS->getZExtValue();
7312     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
7313       assert(Ptr->getOpcode() == ISD::ADD);
7314       isInc = false;
7315       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
7316       return true;
7317     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
7318       isInc = Ptr->getOpcode() == ISD::ADD;
7319       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
7320       return true;
7321     }
7322   }
7323
7324   return false;
7325 }
7326
7327 /// getPreIndexedAddressParts - returns true by value, base pointer and
7328 /// offset pointer and addressing mode by reference if the node's address
7329 /// can be legally represented as pre-indexed load / store address.
7330 bool
7331 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7332                                              SDValue &Offset,
7333                                              ISD::MemIndexedMode &AM,
7334                                              SelectionDAG &DAG) const {
7335   if (Subtarget->isThumb1Only())
7336     return false;
7337
7338   EVT VT;
7339   SDValue Ptr;
7340   bool isSEXTLoad = false;
7341   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7342     Ptr = LD->getBasePtr();
7343     VT  = LD->getMemoryVT();
7344     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
7345   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7346     Ptr = ST->getBasePtr();
7347     VT  = ST->getMemoryVT();
7348   } else
7349     return false;
7350
7351   bool isInc;
7352   bool isLegal = false;
7353   if (Subtarget->isThumb2())
7354     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
7355                                        Offset, isInc, DAG);
7356   else
7357     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
7358                                         Offset, isInc, DAG);
7359   if (!isLegal)
7360     return false;
7361
7362   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
7363   return true;
7364 }
7365
7366 /// getPostIndexedAddressParts - returns true by value, base pointer and
7367 /// offset pointer and addressing mode by reference if this node can be
7368 /// combined with a load / store to form a post-indexed load / store.
7369 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7370                                                    SDValue &Base,
7371                                                    SDValue &Offset,
7372                                                    ISD::MemIndexedMode &AM,
7373                                                    SelectionDAG &DAG) const {
7374   if (Subtarget->isThumb1Only())
7375     return false;
7376
7377   EVT VT;
7378   SDValue Ptr;
7379   bool isSEXTLoad = false;
7380   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7381     VT  = LD->getMemoryVT();
7382     Ptr = LD->getBasePtr();
7383     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
7384   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7385     VT  = ST->getMemoryVT();
7386     Ptr = ST->getBasePtr();
7387   } else
7388     return false;
7389
7390   bool isInc;
7391   bool isLegal = false;
7392   if (Subtarget->isThumb2())
7393     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
7394                                        isInc, DAG);
7395   else
7396     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
7397                                         isInc, DAG);
7398   if (!isLegal)
7399     return false;
7400
7401   if (Ptr != Base) {
7402     // Swap base ptr and offset to catch more post-index load / store when
7403     // it's legal. In Thumb2 mode, offset must be an immediate.
7404     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
7405         !Subtarget->isThumb2())
7406       std::swap(Base, Offset);
7407
7408     // Post-indexed load / store update the base pointer.
7409     if (Ptr != Base)
7410       return false;
7411   }
7412
7413   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
7414   return true;
7415 }
7416
7417 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7418                                                        const APInt &Mask,
7419                                                        APInt &KnownZero,
7420                                                        APInt &KnownOne,
7421                                                        const SelectionDAG &DAG,
7422                                                        unsigned Depth) const {
7423   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
7424   switch (Op.getOpcode()) {
7425   default: break;
7426   case ARMISD::CMOV: {
7427     // Bits are known zero/one if known on the LHS and RHS.
7428     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
7429     if (KnownZero == 0 && KnownOne == 0) return;
7430
7431     APInt KnownZeroRHS, KnownOneRHS;
7432     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
7433                           KnownZeroRHS, KnownOneRHS, Depth+1);
7434     KnownZero &= KnownZeroRHS;
7435     KnownOne  &= KnownOneRHS;
7436     return;
7437   }
7438   }
7439 }
7440
7441 //===----------------------------------------------------------------------===//
7442 //                           ARM Inline Assembly Support
7443 //===----------------------------------------------------------------------===//
7444
7445 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
7446   // Looking for "rev" which is V6+.
7447   if (!Subtarget->hasV6Ops())
7448     return false;
7449
7450   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
7451   std::string AsmStr = IA->getAsmString();
7452   SmallVector<StringRef, 4> AsmPieces;
7453   SplitString(AsmStr, AsmPieces, ";\n");
7454
7455   switch (AsmPieces.size()) {
7456   default: return false;
7457   case 1:
7458     AsmStr = AsmPieces[0];
7459     AsmPieces.clear();
7460     SplitString(AsmStr, AsmPieces, " \t,");
7461
7462     // rev $0, $1
7463     if (AsmPieces.size() == 3 &&
7464         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
7465         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
7466       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
7467       if (Ty && Ty->getBitWidth() == 32)
7468         return IntrinsicLowering::LowerToByteSwap(CI);
7469     }
7470     break;
7471   }
7472
7473   return false;
7474 }
7475
7476 /// getConstraintType - Given a constraint letter, return the type of
7477 /// constraint it is for this target.
7478 ARMTargetLowering::ConstraintType
7479 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
7480   if (Constraint.size() == 1) {
7481     switch (Constraint[0]) {
7482     default:  break;
7483     case 'l': return C_RegisterClass;
7484     case 'w': return C_RegisterClass;
7485     case 'h': return C_RegisterClass;
7486     }
7487   } else if (Constraint.size() == 2) {
7488     switch (Constraint[0]) {
7489     default: break;
7490     // All 'U+' constraints are addresses.
7491     case 'U': return C_Memory;
7492     }
7493   }
7494   return TargetLowering::getConstraintType(Constraint);
7495 }
7496
7497 /// Examine constraint type and operand type and determine a weight value.
7498 /// This object must already have been set up with the operand type
7499 /// and the current alternative constraint selected.
7500 TargetLowering::ConstraintWeight
7501 ARMTargetLowering::getSingleConstraintMatchWeight(
7502     AsmOperandInfo &info, const char *constraint) const {
7503   ConstraintWeight weight = CW_Invalid;
7504   Value *CallOperandVal = info.CallOperandVal;
7505     // If we don't have a value, we can't do a match,
7506     // but allow it at the lowest weight.
7507   if (CallOperandVal == NULL)
7508     return CW_Default;
7509   const Type *type = CallOperandVal->getType();
7510   // Look at the constraint type.
7511   switch (*constraint) {
7512   default:
7513     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7514     break;
7515   case 'l':
7516     if (type->isIntegerTy()) {
7517       if (Subtarget->isThumb())
7518         weight = CW_SpecificReg;
7519       else
7520         weight = CW_Register;
7521     }
7522     break;
7523   case 'w':
7524     if (type->isFloatingPointTy())
7525       weight = CW_Register;
7526     break;
7527   }
7528   return weight;
7529 }
7530
7531 typedef std::pair<unsigned, const TargetRegisterClass*> Pair;
7532 Pair
7533 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7534                                                 EVT VT) const {
7535   if (Constraint.size() == 1) {
7536     // GCC ARM Constraint Letters
7537     switch (Constraint[0]) {
7538     case 'l': // Low regs or general regs.
7539       if (Subtarget->isThumb())
7540         return Pair(0U, ARM::tGPRRegisterClass);
7541       else
7542         return Pair(0U, ARM::GPRRegisterClass);
7543     case 'h': // High regs or no regs.
7544       if (Subtarget->isThumb())
7545         return Pair(0U, ARM::hGPRRegisterClass);
7546       else
7547         return Pair(0u, static_cast<const TargetRegisterClass*>(0));
7548     case 'r':
7549       return Pair(0U, ARM::GPRRegisterClass);
7550     case 'w':
7551       if (VT == MVT::f32)
7552         return Pair(0U, ARM::SPRRegisterClass);
7553       if (VT.getSizeInBits() == 64)
7554         return Pair(0U, ARM::DPRRegisterClass);
7555       if (VT.getSizeInBits() == 128)
7556         return Pair(0U, ARM::QPRRegisterClass);
7557       break;
7558     }
7559   }
7560   if (StringRef("{cc}").equals_lower(Constraint))
7561     return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
7562
7563   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7564 }
7565
7566 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7567 /// vector.  If it is invalid, don't add anything to Ops.
7568 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7569                                                      std::string &Constraint,
7570                                                      std::vector<SDValue>&Ops,
7571                                                      SelectionDAG &DAG) const {
7572   SDValue Result(0, 0);
7573
7574   // Currently only support length 1 constraints.
7575   if (Constraint.length() != 1) return;
7576
7577   char ConstraintLetter = Constraint[0];
7578   switch (ConstraintLetter) {
7579   default: break;
7580   case 'I': case 'J': case 'K': case 'L':
7581   case 'M': case 'N': case 'O':
7582     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
7583     if (!C)
7584       return;
7585
7586     int64_t CVal64 = C->getSExtValue();
7587     int CVal = (int) CVal64;
7588     // None of these constraints allow values larger than 32 bits.  Check
7589     // that the value fits in an int.
7590     if (CVal != CVal64)
7591       return;
7592
7593     switch (ConstraintLetter) {
7594       case 'I':
7595         if (Subtarget->isThumb1Only()) {
7596           // This must be a constant between 0 and 255, for ADD
7597           // immediates.
7598           if (CVal >= 0 && CVal <= 255)
7599             break;
7600         } else if (Subtarget->isThumb2()) {
7601           // A constant that can be used as an immediate value in a
7602           // data-processing instruction.
7603           if (ARM_AM::getT2SOImmVal(CVal) != -1)
7604             break;
7605         } else {
7606           // A constant that can be used as an immediate value in a
7607           // data-processing instruction.
7608           if (ARM_AM::getSOImmVal(CVal) != -1)
7609             break;
7610         }
7611         return;
7612
7613       case 'J':
7614         if (Subtarget->isThumb()) {  // FIXME thumb2
7615           // This must be a constant between -255 and -1, for negated ADD
7616           // immediates. This can be used in GCC with an "n" modifier that
7617           // prints the negated value, for use with SUB instructions. It is
7618           // not useful otherwise but is implemented for compatibility.
7619           if (CVal >= -255 && CVal <= -1)
7620             break;
7621         } else {
7622           // This must be a constant between -4095 and 4095. It is not clear
7623           // what this constraint is intended for. Implemented for
7624           // compatibility with GCC.
7625           if (CVal >= -4095 && CVal <= 4095)
7626             break;
7627         }
7628         return;
7629
7630       case 'K':
7631         if (Subtarget->isThumb1Only()) {
7632           // A 32-bit value where only one byte has a nonzero value. Exclude
7633           // zero to match GCC. This constraint is used by GCC internally for
7634           // constants that can be loaded with a move/shift combination.
7635           // It is not useful otherwise but is implemented for compatibility.
7636           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
7637             break;
7638         } else if (Subtarget->isThumb2()) {
7639           // A constant whose bitwise inverse can be used as an immediate
7640           // value in a data-processing instruction. This can be used in GCC
7641           // with a "B" modifier that prints the inverted value, for use with
7642           // BIC and MVN instructions. It is not useful otherwise but is
7643           // implemented for compatibility.
7644           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
7645             break;
7646         } else {
7647           // A constant whose bitwise inverse can be used as an immediate
7648           // value in a data-processing instruction. This can be used in GCC
7649           // with a "B" modifier that prints the inverted value, for use with
7650           // BIC and MVN instructions. It is not useful otherwise but is
7651           // implemented for compatibility.
7652           if (ARM_AM::getSOImmVal(~CVal) != -1)
7653             break;
7654         }
7655         return;
7656
7657       case 'L':
7658         if (Subtarget->isThumb1Only()) {
7659           // This must be a constant between -7 and 7,
7660           // for 3-operand ADD/SUB immediate instructions.
7661           if (CVal >= -7 && CVal < 7)
7662             break;
7663         } else if (Subtarget->isThumb2()) {
7664           // A constant whose negation can be used as an immediate value in a
7665           // data-processing instruction. This can be used in GCC with an "n"
7666           // modifier that prints the negated value, for use with SUB
7667           // instructions. It is not useful otherwise but is implemented for
7668           // compatibility.
7669           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
7670             break;
7671         } else {
7672           // A constant whose negation can be used as an immediate value in a
7673           // data-processing instruction. This can be used in GCC with an "n"
7674           // modifier that prints the negated value, for use with SUB
7675           // instructions. It is not useful otherwise but is implemented for
7676           // compatibility.
7677           if (ARM_AM::getSOImmVal(-CVal) != -1)
7678             break;
7679         }
7680         return;
7681
7682       case 'M':
7683         if (Subtarget->isThumb()) { // FIXME thumb2
7684           // This must be a multiple of 4 between 0 and 1020, for
7685           // ADD sp + immediate.
7686           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
7687             break;
7688         } else {
7689           // A power of two or a constant between 0 and 32.  This is used in
7690           // GCC for the shift amount on shifted register operands, but it is
7691           // useful in general for any shift amounts.
7692           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
7693             break;
7694         }
7695         return;
7696
7697       case 'N':
7698         if (Subtarget->isThumb()) {  // FIXME thumb2
7699           // This must be a constant between 0 and 31, for shift amounts.
7700           if (CVal >= 0 && CVal <= 31)
7701             break;
7702         }
7703         return;
7704
7705       case 'O':
7706         if (Subtarget->isThumb()) {  // FIXME thumb2
7707           // This must be a multiple of 4 between -508 and 508, for
7708           // ADD/SUB sp = sp + immediate.
7709           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
7710             break;
7711         }
7712         return;
7713     }
7714     Result = DAG.getTargetConstant(CVal, Op.getValueType());
7715     break;
7716   }
7717
7718   if (Result.getNode()) {
7719     Ops.push_back(Result);
7720     return;
7721   }
7722   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7723 }
7724
7725 bool
7726 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7727   // The ARM target isn't yet aware of offsets.
7728   return false;
7729 }
7730
7731 int ARM::getVFPf32Imm(const APFloat &FPImm) {
7732   APInt Imm = FPImm.bitcastToAPInt();
7733   uint32_t Sign = Imm.lshr(31).getZExtValue() & 1;
7734   int32_t Exp = (Imm.lshr(23).getSExtValue() & 0xff) - 127;  // -126 to 127
7735   int64_t Mantissa = Imm.getZExtValue() & 0x7fffff;  // 23 bits
7736
7737   // We can handle 4 bits of mantissa.
7738   // mantissa = (16+UInt(e:f:g:h))/16.
7739   if (Mantissa & 0x7ffff)
7740     return -1;
7741   Mantissa >>= 19;
7742   if ((Mantissa & 0xf) != Mantissa)
7743     return -1;
7744
7745   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
7746   if (Exp < -3 || Exp > 4)
7747     return -1;
7748   Exp = ((Exp+3) & 0x7) ^ 4;
7749
7750   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
7751 }
7752
7753 int ARM::getVFPf64Imm(const APFloat &FPImm) {
7754   APInt Imm = FPImm.bitcastToAPInt();
7755   uint64_t Sign = Imm.lshr(63).getZExtValue() & 1;
7756   int64_t Exp = (Imm.lshr(52).getSExtValue() & 0x7ff) - 1023;   // -1022 to 1023
7757   uint64_t Mantissa = Imm.getZExtValue() & 0xfffffffffffffLL;
7758
7759   // We can handle 4 bits of mantissa.
7760   // mantissa = (16+UInt(e:f:g:h))/16.
7761   if (Mantissa & 0xffffffffffffLL)
7762     return -1;
7763   Mantissa >>= 48;
7764   if ((Mantissa & 0xf) != Mantissa)
7765     return -1;
7766
7767   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
7768   if (Exp < -3 || Exp > 4)
7769     return -1;
7770   Exp = ((Exp+3) & 0x7) ^ 4;
7771
7772   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
7773 }
7774
7775 bool ARM::isBitFieldInvertedMask(unsigned v) {
7776   if (v == 0xffffffff)
7777     return 0;
7778   // there can be 1's on either or both "outsides", all the "inside"
7779   // bits must be 0's
7780   unsigned int lsb = 0, msb = 31;
7781   while (v & (1 << msb)) --msb;
7782   while (v & (1 << lsb)) ++lsb;
7783   for (unsigned int i = lsb; i <= msb; ++i) {
7784     if (v & (1 << i))
7785       return 0;
7786   }
7787   return 1;
7788 }
7789
7790 /// isFPImmLegal - Returns true if the target can instruction select the
7791 /// specified FP immediate natively. If false, the legalizer will
7792 /// materialize the FP immediate as a load from a constant pool.
7793 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
7794   if (!Subtarget->hasVFP3())
7795     return false;
7796   if (VT == MVT::f32)
7797     return ARM::getVFPf32Imm(Imm) != -1;
7798   if (VT == MVT::f64)
7799     return ARM::getVFPf64Imm(Imm) != -1;
7800   return false;
7801 }
7802
7803 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7804 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
7805 /// specified in the intrinsic calls.
7806 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7807                                            const CallInst &I,
7808                                            unsigned Intrinsic) const {
7809   switch (Intrinsic) {
7810   case Intrinsic::arm_neon_vld1:
7811   case Intrinsic::arm_neon_vld2:
7812   case Intrinsic::arm_neon_vld3:
7813   case Intrinsic::arm_neon_vld4:
7814   case Intrinsic::arm_neon_vld2lane:
7815   case Intrinsic::arm_neon_vld3lane:
7816   case Intrinsic::arm_neon_vld4lane: {
7817     Info.opc = ISD::INTRINSIC_W_CHAIN;
7818     // Conservatively set memVT to the entire set of vectors loaded.
7819     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
7820     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7821     Info.ptrVal = I.getArgOperand(0);
7822     Info.offset = 0;
7823     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
7824     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
7825     Info.vol = false; // volatile loads with NEON intrinsics not supported
7826     Info.readMem = true;
7827     Info.writeMem = false;
7828     return true;
7829   }
7830   case Intrinsic::arm_neon_vst1:
7831   case Intrinsic::arm_neon_vst2:
7832   case Intrinsic::arm_neon_vst3:
7833   case Intrinsic::arm_neon_vst4:
7834   case Intrinsic::arm_neon_vst2lane:
7835   case Intrinsic::arm_neon_vst3lane:
7836   case Intrinsic::arm_neon_vst4lane: {
7837     Info.opc = ISD::INTRINSIC_VOID;
7838     // Conservatively set memVT to the entire set of vectors stored.
7839     unsigned NumElts = 0;
7840     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7841       const Type *ArgTy = I.getArgOperand(ArgI)->getType();
7842       if (!ArgTy->isVectorTy())
7843         break;
7844       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
7845     }
7846     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7847     Info.ptrVal = I.getArgOperand(0);
7848     Info.offset = 0;
7849     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
7850     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
7851     Info.vol = false; // volatile stores with NEON intrinsics not supported
7852     Info.readMem = false;
7853     Info.writeMem = true;
7854     return true;
7855   }
7856   case Intrinsic::arm_strexd: {
7857     Info.opc = ISD::INTRINSIC_W_CHAIN;
7858     Info.memVT = MVT::i64;
7859     Info.ptrVal = I.getArgOperand(2);
7860     Info.offset = 0;
7861     Info.align = 8;
7862     Info.vol = true;
7863     Info.readMem = false;
7864     Info.writeMem = true;
7865     return true;
7866   }
7867   case Intrinsic::arm_ldrexd: {
7868     Info.opc = ISD::INTRINSIC_W_CHAIN;
7869     Info.memVT = MVT::i64;
7870     Info.ptrVal = I.getArgOperand(0);
7871     Info.offset = 0;
7872     Info.align = 8;
7873     Info.vol = true;
7874     Info.readMem = true;
7875     Info.writeMem = false;
7876     return true;
7877   }
7878   default:
7879     break;
7880   }
7881
7882   return false;
7883 }