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