Expand all v2f64 arithmetic operations for Neon.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instruction.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/CodeGen/SelectionDAG.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/VectorExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MathExtras.h"
43 #include <sstream>
44 using namespace llvm;
45
46 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
47                                    CCValAssign::LocInfo &LocInfo,
48                                    ISD::ArgFlagsTy &ArgFlags,
49                                    CCState &State);
50 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
51                                     CCValAssign::LocInfo &LocInfo,
52                                     ISD::ArgFlagsTy &ArgFlags,
53                                     CCState &State);
54 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
55                                       CCValAssign::LocInfo &LocInfo,
56                                       ISD::ArgFlagsTy &ArgFlags,
57                                       CCState &State);
58 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
59                                        CCValAssign::LocInfo &LocInfo,
60                                        ISD::ArgFlagsTy &ArgFlags,
61                                        CCState &State);
62
63 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
64                                        EVT PromotedBitwiseVT) {
65   if (VT != PromotedLdStVT) {
66     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
67     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
68                        PromotedLdStVT.getSimpleVT());
69
70     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
71     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
72                        PromotedLdStVT.getSimpleVT());
73   }
74
75   EVT ElemTy = VT.getVectorElementType();
76   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
77     setOperationAction(ISD::VSETCC, VT.getSimpleVT(), Custom);
78   if (ElemTy == MVT::i8 || ElemTy == MVT::i16)
79     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
80   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
81   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
82   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Custom);
83   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Expand);
84   if (VT.isInteger()) {
85     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
86     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
87     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
88   }
89
90   // Promote all bit-wise operations.
91   if (VT.isInteger() && VT != PromotedBitwiseVT) {
92     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
93     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
94                        PromotedBitwiseVT.getSimpleVT());
95     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
96     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
97                        PromotedBitwiseVT.getSimpleVT());
98     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
99     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
100                        PromotedBitwiseVT.getSimpleVT());
101   }
102 }
103
104 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
105   addRegisterClass(VT, ARM::DPRRegisterClass);
106   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
107 }
108
109 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
110   addRegisterClass(VT, ARM::QPRRegisterClass);
111   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
112 }
113
114 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
115   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
116     return new TargetLoweringObjectFileMachO();
117   return new ARMElfTargetObjectFile();
118 }
119
120 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
121     : TargetLowering(TM, createTLOF(TM)), ARMPCLabelIndex(0) {
122   Subtarget = &TM.getSubtarget<ARMSubtarget>();
123
124   if (Subtarget->isTargetDarwin()) {
125     // Uses VFP for Thumb libfuncs if available.
126     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
127       // Single-precision floating-point arithmetic.
128       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
129       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
130       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
131       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
132
133       // Double-precision floating-point arithmetic.
134       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
135       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
136       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
137       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
138
139       // Single-precision comparisons.
140       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
141       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
142       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
143       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
144       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
145       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
146       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
147       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
148
149       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
150       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
151       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
152       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
153       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
154       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
155       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
156       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
157
158       // Double-precision comparisons.
159       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
160       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
161       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
162       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
163       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
164       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
165       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
166       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
167
168       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
169       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
170       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
171       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
172       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
173       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
174       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
175       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
176
177       // Floating-point to integer conversions.
178       // i64 conversions are done via library routines even when generating VFP
179       // instructions, so use the same ones.
180       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
181       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
182       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
183       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
184
185       // Conversions between floating types.
186       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
187       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
188
189       // Integer to floating-point conversions.
190       // i64 conversions are done via library routines even when generating VFP
191       // instructions, so use the same ones.
192       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
193       // e.g., __floatunsidf vs. __floatunssidfvfp.
194       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
195       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
196       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
197       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
198     }
199   }
200
201   // These libcalls are not available in 32-bit.
202   setLibcallName(RTLIB::SHL_I128, 0);
203   setLibcallName(RTLIB::SRL_I128, 0);
204   setLibcallName(RTLIB::SRA_I128, 0);
205
206   // Libcalls should use the AAPCS base standard ABI, even if hard float
207   // is in effect, as per the ARM RTABI specification, section 4.1.2.
208   if (Subtarget->isAAPCS_ABI()) {
209     for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
210       setLibcallCallingConv(static_cast<RTLIB::Libcall>(i),
211                             CallingConv::ARM_AAPCS);
212     }
213   }
214
215   if (Subtarget->isThumb1Only())
216     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
217   else
218     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
219   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
220     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
221     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
222
223     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224   }
225
226   if (Subtarget->hasNEON()) {
227     addDRTypeForNEON(MVT::v2f32);
228     addDRTypeForNEON(MVT::v8i8);
229     addDRTypeForNEON(MVT::v4i16);
230     addDRTypeForNEON(MVT::v2i32);
231     addDRTypeForNEON(MVT::v1i64);
232
233     addQRTypeForNEON(MVT::v4f32);
234     addQRTypeForNEON(MVT::v2f64);
235     addQRTypeForNEON(MVT::v16i8);
236     addQRTypeForNEON(MVT::v8i16);
237     addQRTypeForNEON(MVT::v4i32);
238     addQRTypeForNEON(MVT::v2i64);
239
240     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
241     // neither Neon nor VFP support any arithmetic operations on it.
242     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
243     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
244     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
245     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
246     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
247     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
248     setOperationAction(ISD::VSETCC, MVT::v2f64, Expand);
249     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
250     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
251     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
252     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
253     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
254     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
255     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
256     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
257     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
258     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
259     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
260     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
261     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
262     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
263     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
264     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
265     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
266
267     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
268     setTargetDAGCombine(ISD::SHL);
269     setTargetDAGCombine(ISD::SRL);
270     setTargetDAGCombine(ISD::SRA);
271     setTargetDAGCombine(ISD::SIGN_EXTEND);
272     setTargetDAGCombine(ISD::ZERO_EXTEND);
273     setTargetDAGCombine(ISD::ANY_EXTEND);
274   }
275
276   computeRegisterProperties();
277
278   // ARM does not have f32 extending load.
279   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
280
281   // ARM does not have i1 sign extending load.
282   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
283
284   // ARM supports all 4 flavors of integer indexed load / store.
285   if (!Subtarget->isThumb1Only()) {
286     for (unsigned im = (unsigned)ISD::PRE_INC;
287          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
288       setIndexedLoadAction(im,  MVT::i1,  Legal);
289       setIndexedLoadAction(im,  MVT::i8,  Legal);
290       setIndexedLoadAction(im,  MVT::i16, Legal);
291       setIndexedLoadAction(im,  MVT::i32, Legal);
292       setIndexedStoreAction(im, MVT::i1,  Legal);
293       setIndexedStoreAction(im, MVT::i8,  Legal);
294       setIndexedStoreAction(im, MVT::i16, Legal);
295       setIndexedStoreAction(im, MVT::i32, Legal);
296     }
297   }
298
299   // i64 operation support.
300   if (Subtarget->isThumb1Only()) {
301     setOperationAction(ISD::MUL,     MVT::i64, Expand);
302     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
303     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
304     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
305     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
306   } else {
307     setOperationAction(ISD::MUL,     MVT::i64, Expand);
308     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
309     if (!Subtarget->hasV6Ops())
310       setOperationAction(ISD::MULHS, MVT::i32, Expand);
311   }
312   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
313   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
314   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
315   setOperationAction(ISD::SRL,       MVT::i64, Custom);
316   setOperationAction(ISD::SRA,       MVT::i64, Custom);
317
318   // ARM does not have ROTL.
319   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
320   setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
321   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
322   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
323     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
324
325   // Only ARMv6 has BSWAP.
326   if (!Subtarget->hasV6Ops())
327     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
328
329   // These are expanded into libcalls.
330   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
331   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
332   setOperationAction(ISD::SREM,  MVT::i32, Expand);
333   setOperationAction(ISD::UREM,  MVT::i32, Expand);
334   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
335   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
336
337   // Support label based line numbers.
338   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
339   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
340
341   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
342   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
343   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
344   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
345
346   // Use the default implementation.
347   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
348   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
349   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
350   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
351   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
352   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
353   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
354   // FIXME: Shouldn't need this, since no register is used, but the legalizer
355   // doesn't yet know how to not do that for SjLj.
356   setExceptionSelectorRegister(ARM::R0);
357   if (Subtarget->isThumb())
358     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
359   else
360     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
361   setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
362
363   if (!Subtarget->hasV6Ops() && !Subtarget->isThumb2()) {
364     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
365     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
366   }
367   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
368
369   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())
370     // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
371     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
372
373   // We want to custom lower some of our intrinsics.
374   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
375   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
376   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
377
378   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
379   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
380   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
381   setOperationAction(ISD::SELECT,    MVT::i32, Expand);
382   setOperationAction(ISD::SELECT,    MVT::f32, Expand);
383   setOperationAction(ISD::SELECT,    MVT::f64, Expand);
384   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
385   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
386   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
387
388   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
389   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
390   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
391   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
392   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
393
394   // We don't support sin/cos/fmod/copysign/pow
395   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
396   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
397   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
398   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
399   setOperationAction(ISD::FREM,      MVT::f64, Expand);
400   setOperationAction(ISD::FREM,      MVT::f32, Expand);
401   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
402     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
403     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
404   }
405   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
406   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
407
408   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
409   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
410     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
411     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
412     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
413     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
414   }
415
416   // We have target-specific dag combine patterns for the following nodes:
417   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
418   setTargetDAGCombine(ISD::ADD);
419   setTargetDAGCombine(ISD::SUB);
420
421   setStackPointerRegisterToSaveRestore(ARM::SP);
422   setSchedulingPreference(SchedulingForRegPressure);
423
424   // FIXME: If-converter should use instruction latency to determine
425   // profitability rather than relying on fixed limits.
426   if (Subtarget->getCPUString() == "generic") {
427     // Generic (and overly aggressive) if-conversion limits.
428     setIfCvtBlockSizeLimit(10);
429     setIfCvtDupBlockSizeLimit(2);
430   } else if (Subtarget->hasV6Ops()) {
431     setIfCvtBlockSizeLimit(2);
432     setIfCvtDupBlockSizeLimit(1);
433   } else {
434     setIfCvtBlockSizeLimit(3);
435     setIfCvtDupBlockSizeLimit(2);
436   }
437
438   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
439   // Do not enable CodePlacementOpt for now: it currently runs after the
440   // ARMConstantIslandPass and messes up branch relaxation and placement
441   // of constant islands.
442   // benefitFromCodePlacementOpt = true;
443 }
444
445 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
446   switch (Opcode) {
447   default: return 0;
448   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
449   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
450   case ARMISD::CALL:          return "ARMISD::CALL";
451   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
452   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
453   case ARMISD::tCALL:         return "ARMISD::tCALL";
454   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
455   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
456   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
457   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
458   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
459   case ARMISD::CMP:           return "ARMISD::CMP";
460   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
461   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
462   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
463   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
464   case ARMISD::CMOV:          return "ARMISD::CMOV";
465   case ARMISD::CNEG:          return "ARMISD::CNEG";
466
467   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
468   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
469   case ARMISD::SITOF:         return "ARMISD::SITOF";
470   case ARMISD::UITOF:         return "ARMISD::UITOF";
471
472   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
473   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
474   case ARMISD::RRX:           return "ARMISD::RRX";
475
476   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
477   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
478
479   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
480
481   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
482
483   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
484   case ARMISD::VCGE:          return "ARMISD::VCGE";
485   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
486   case ARMISD::VCGT:          return "ARMISD::VCGT";
487   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
488   case ARMISD::VTST:          return "ARMISD::VTST";
489
490   case ARMISD::VSHL:          return "ARMISD::VSHL";
491   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
492   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
493   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
494   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
495   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
496   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
497   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
498   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
499   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
500   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
501   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
502   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
503   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
504   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
505   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
506   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
507   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
508   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
509   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
510   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
511   case ARMISD::VDUP:          return "ARMISD::VDUP";
512   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
513   case ARMISD::VEXT:          return "ARMISD::VEXT";
514   case ARMISD::VREV64:        return "ARMISD::VREV64";
515   case ARMISD::VREV32:        return "ARMISD::VREV32";
516   case ARMISD::VREV16:        return "ARMISD::VREV16";
517   case ARMISD::VZIP:          return "ARMISD::VZIP";
518   case ARMISD::VUZP:          return "ARMISD::VUZP";
519   case ARMISD::VTRN:          return "ARMISD::VTRN";
520   }
521 }
522
523 /// getFunctionAlignment - Return the Log2 alignment of this function.
524 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
525   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
526 }
527
528 //===----------------------------------------------------------------------===//
529 // Lowering Code
530 //===----------------------------------------------------------------------===//
531
532 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
533 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
534   switch (CC) {
535   default: llvm_unreachable("Unknown condition code!");
536   case ISD::SETNE:  return ARMCC::NE;
537   case ISD::SETEQ:  return ARMCC::EQ;
538   case ISD::SETGT:  return ARMCC::GT;
539   case ISD::SETGE:  return ARMCC::GE;
540   case ISD::SETLT:  return ARMCC::LT;
541   case ISD::SETLE:  return ARMCC::LE;
542   case ISD::SETUGT: return ARMCC::HI;
543   case ISD::SETUGE: return ARMCC::HS;
544   case ISD::SETULT: return ARMCC::LO;
545   case ISD::SETULE: return ARMCC::LS;
546   }
547 }
548
549 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
550 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
551                         ARMCC::CondCodes &CondCode2) {
552   CondCode2 = ARMCC::AL;
553   switch (CC) {
554   default: llvm_unreachable("Unknown FP condition!");
555   case ISD::SETEQ:
556   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
557   case ISD::SETGT:
558   case ISD::SETOGT: CondCode = ARMCC::GT; break;
559   case ISD::SETGE:
560   case ISD::SETOGE: CondCode = ARMCC::GE; break;
561   case ISD::SETOLT: CondCode = ARMCC::MI; break;
562   case ISD::SETOLE: CondCode = ARMCC::LS; break;
563   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
564   case ISD::SETO:   CondCode = ARMCC::VC; break;
565   case ISD::SETUO:  CondCode = ARMCC::VS; break;
566   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
567   case ISD::SETUGT: CondCode = ARMCC::HI; break;
568   case ISD::SETUGE: CondCode = ARMCC::PL; break;
569   case ISD::SETLT:
570   case ISD::SETULT: CondCode = ARMCC::LT; break;
571   case ISD::SETLE:
572   case ISD::SETULE: CondCode = ARMCC::LE; break;
573   case ISD::SETNE:
574   case ISD::SETUNE: CondCode = ARMCC::NE; break;
575   }
576 }
577
578 //===----------------------------------------------------------------------===//
579 //                      Calling Convention Implementation
580 //===----------------------------------------------------------------------===//
581
582 #include "ARMGenCallingConv.inc"
583
584 // APCS f64 is in register pairs, possibly split to stack
585 static bool f64AssignAPCS(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
586                           CCValAssign::LocInfo &LocInfo,
587                           CCState &State, bool CanFail) {
588   static const unsigned RegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
589
590   // Try to get the first register.
591   if (unsigned Reg = State.AllocateReg(RegList, 4))
592     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
593   else {
594     // For the 2nd half of a v2f64, do not fail.
595     if (CanFail)
596       return false;
597
598     // Put the whole thing on the stack.
599     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
600                                            State.AllocateStack(8, 4),
601                                            LocVT, LocInfo));
602     return true;
603   }
604
605   // Try to get the second register.
606   if (unsigned Reg = State.AllocateReg(RegList, 4))
607     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
608   else
609     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
610                                            State.AllocateStack(4, 4),
611                                            LocVT, LocInfo));
612   return true;
613 }
614
615 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
616                                    CCValAssign::LocInfo &LocInfo,
617                                    ISD::ArgFlagsTy &ArgFlags,
618                                    CCState &State) {
619   if (!f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
620     return false;
621   if (LocVT == MVT::v2f64 &&
622       !f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
623     return false;
624   return true;  // we handled it
625 }
626
627 // AAPCS f64 is in aligned register pairs
628 static bool f64AssignAAPCS(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
629                            CCValAssign::LocInfo &LocInfo,
630                            CCState &State, bool CanFail) {
631   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
632   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
633
634   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
635   if (Reg == 0) {
636     // For the 2nd half of a v2f64, do not just fail.
637     if (CanFail)
638       return false;
639
640     // Put the whole thing on the stack.
641     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
642                                            State.AllocateStack(8, 8),
643                                            LocVT, LocInfo));
644     return true;
645   }
646
647   unsigned i;
648   for (i = 0; i < 2; ++i)
649     if (HiRegList[i] == Reg)
650       break;
651
652   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
653   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
654                                          LocVT, LocInfo));
655   return true;
656 }
657
658 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
659                                     CCValAssign::LocInfo &LocInfo,
660                                     ISD::ArgFlagsTy &ArgFlags,
661                                     CCState &State) {
662   if (!f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
663     return false;
664   if (LocVT == MVT::v2f64 &&
665       !f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
666     return false;
667   return true;  // we handled it
668 }
669
670 static bool f64RetAssign(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
671                          CCValAssign::LocInfo &LocInfo, CCState &State) {
672   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
673   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
674
675   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
676   if (Reg == 0)
677     return false; // we didn't handle it
678
679   unsigned i;
680   for (i = 0; i < 2; ++i)
681     if (HiRegList[i] == Reg)
682       break;
683
684   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
685   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
686                                          LocVT, LocInfo));
687   return true;
688 }
689
690 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
691                                       CCValAssign::LocInfo &LocInfo,
692                                       ISD::ArgFlagsTy &ArgFlags,
693                                       CCState &State) {
694   if (!f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
695     return false;
696   if (LocVT == MVT::v2f64 && !f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
697     return false;
698   return true;  // we handled it
699 }
700
701 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
702                                        CCValAssign::LocInfo &LocInfo,
703                                        ISD::ArgFlagsTy &ArgFlags,
704                                        CCState &State) {
705   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
706                                    State);
707 }
708
709 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
710 /// given CallingConvention value.
711 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
712                                                  bool Return,
713                                                  bool isVarArg) const {
714   switch (CC) {
715   default:
716     llvm_unreachable("Unsupported calling convention");
717   case CallingConv::C:
718   case CallingConv::Fast:
719     // Use target triple & subtarget features to do actual dispatch.
720     if (Subtarget->isAAPCS_ABI()) {
721       if (Subtarget->hasVFP2() &&
722           FloatABIType == FloatABI::Hard && !isVarArg)
723         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
724       else
725         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
726     } else
727         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
728   case CallingConv::ARM_AAPCS_VFP:
729     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
730   case CallingConv::ARM_AAPCS:
731     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
732   case CallingConv::ARM_APCS:
733     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
734   }
735 }
736
737 /// LowerCallResult - Lower the result values of a call into the
738 /// appropriate copies out of appropriate physical registers.
739 SDValue
740 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
741                                    CallingConv::ID CallConv, bool isVarArg,
742                                    const SmallVectorImpl<ISD::InputArg> &Ins,
743                                    DebugLoc dl, SelectionDAG &DAG,
744                                    SmallVectorImpl<SDValue> &InVals) {
745
746   // Assign locations to each value returned by this call.
747   SmallVector<CCValAssign, 16> RVLocs;
748   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
749                  RVLocs, *DAG.getContext());
750   CCInfo.AnalyzeCallResult(Ins,
751                            CCAssignFnForNode(CallConv, /* Return*/ true,
752                                              isVarArg));
753
754   // Copy all of the result registers out of their specified physreg.
755   for (unsigned i = 0; i != RVLocs.size(); ++i) {
756     CCValAssign VA = RVLocs[i];
757
758     SDValue Val;
759     if (VA.needsCustom()) {
760       // Handle f64 or half of a v2f64.
761       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
762                                       InFlag);
763       Chain = Lo.getValue(1);
764       InFlag = Lo.getValue(2);
765       VA = RVLocs[++i]; // skip ahead to next loc
766       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
767                                       InFlag);
768       Chain = Hi.getValue(1);
769       InFlag = Hi.getValue(2);
770       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
771
772       if (VA.getLocVT() == MVT::v2f64) {
773         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
774         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
775                           DAG.getConstant(0, MVT::i32));
776
777         VA = RVLocs[++i]; // skip ahead to next loc
778         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
779         Chain = Lo.getValue(1);
780         InFlag = Lo.getValue(2);
781         VA = RVLocs[++i]; // skip ahead to next loc
782         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
783         Chain = Hi.getValue(1);
784         InFlag = Hi.getValue(2);
785         Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
786         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
787                           DAG.getConstant(1, MVT::i32));
788       }
789     } else {
790       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
791                                InFlag);
792       Chain = Val.getValue(1);
793       InFlag = Val.getValue(2);
794     }
795
796     switch (VA.getLocInfo()) {
797     default: llvm_unreachable("Unknown loc info!");
798     case CCValAssign::Full: break;
799     case CCValAssign::BCvt:
800       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
801       break;
802     }
803
804     InVals.push_back(Val);
805   }
806
807   return Chain;
808 }
809
810 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
811 /// by "Src" to address "Dst" of size "Size".  Alignment information is
812 /// specified by the specific parameter attribute.  The copy will be passed as
813 /// a byval function parameter.
814 /// Sometimes what we are copying is the end of a larger object, the part that
815 /// does not fit in registers.
816 static SDValue
817 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
818                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
819                           DebugLoc dl) {
820   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
821   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
822                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
823 }
824
825 /// LowerMemOpCallTo - Store the argument to the stack.
826 SDValue
827 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
828                                     SDValue StackPtr, SDValue Arg,
829                                     DebugLoc dl, SelectionDAG &DAG,
830                                     const CCValAssign &VA,
831                                     ISD::ArgFlagsTy Flags) {
832   unsigned LocMemOffset = VA.getLocMemOffset();
833   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
834   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
835   if (Flags.isByVal()) {
836     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
837   }
838   return DAG.getStore(Chain, dl, Arg, PtrOff,
839                       PseudoSourceValue::getStack(), LocMemOffset);
840 }
841
842 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
843                                          SDValue Chain, SDValue &Arg,
844                                          RegsToPassVector &RegsToPass,
845                                          CCValAssign &VA, CCValAssign &NextVA,
846                                          SDValue &StackPtr,
847                                          SmallVector<SDValue, 8> &MemOpChains,
848                                          ISD::ArgFlagsTy Flags) {
849
850   SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
851                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
852   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
853
854   if (NextVA.isRegLoc())
855     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
856   else {
857     assert(NextVA.isMemLoc());
858     if (StackPtr.getNode() == 0)
859       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
860
861     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
862                                            dl, DAG, NextVA,
863                                            Flags));
864   }
865 }
866
867 /// LowerCall - Lowering a call into a callseq_start <-
868 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
869 /// nodes.
870 SDValue
871 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
872                              CallingConv::ID CallConv, bool isVarArg,
873                              bool isTailCall,
874                              const SmallVectorImpl<ISD::OutputArg> &Outs,
875                              const SmallVectorImpl<ISD::InputArg> &Ins,
876                              DebugLoc dl, SelectionDAG &DAG,
877                              SmallVectorImpl<SDValue> &InVals) {
878
879   // Analyze operands of the call, assigning locations to each operand.
880   SmallVector<CCValAssign, 16> ArgLocs;
881   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
882                  *DAG.getContext());
883   CCInfo.AnalyzeCallOperands(Outs,
884                              CCAssignFnForNode(CallConv, /* Return*/ false,
885                                                isVarArg));
886
887   // Get a count of how many bytes are to be pushed on the stack.
888   unsigned NumBytes = CCInfo.getNextStackOffset();
889
890   // Adjust the stack pointer for the new arguments...
891   // These operations are automatically eliminated by the prolog/epilog pass
892   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
893
894   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
895
896   RegsToPassVector RegsToPass;
897   SmallVector<SDValue, 8> MemOpChains;
898
899   // Walk the register/memloc assignments, inserting copies/loads.  In the case
900   // of tail call optimization, arguments are handled later.
901   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
902        i != e;
903        ++i, ++realArgIdx) {
904     CCValAssign &VA = ArgLocs[i];
905     SDValue Arg = Outs[realArgIdx].Val;
906     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
907
908     // Promote the value if needed.
909     switch (VA.getLocInfo()) {
910     default: llvm_unreachable("Unknown loc info!");
911     case CCValAssign::Full: break;
912     case CCValAssign::SExt:
913       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
914       break;
915     case CCValAssign::ZExt:
916       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
917       break;
918     case CCValAssign::AExt:
919       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
920       break;
921     case CCValAssign::BCvt:
922       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
923       break;
924     }
925
926     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
927     if (VA.needsCustom()) {
928       if (VA.getLocVT() == MVT::v2f64) {
929         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
930                                   DAG.getConstant(0, MVT::i32));
931         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
932                                   DAG.getConstant(1, MVT::i32));
933
934         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
935                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
936
937         VA = ArgLocs[++i]; // skip ahead to next loc
938         if (VA.isRegLoc()) {
939           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
940                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
941         } else {
942           assert(VA.isMemLoc());
943           if (StackPtr.getNode() == 0)
944             StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
945
946           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
947                                                  dl, DAG, VA, Flags));
948         }
949       } else {
950         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
951                          StackPtr, MemOpChains, Flags);
952       }
953     } else if (VA.isRegLoc()) {
954       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
955     } else {
956       assert(VA.isMemLoc());
957       if (StackPtr.getNode() == 0)
958         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
959
960       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
961                                              dl, DAG, VA, Flags));
962     }
963   }
964
965   if (!MemOpChains.empty())
966     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
967                         &MemOpChains[0], MemOpChains.size());
968
969   // Build a sequence of copy-to-reg nodes chained together with token chain
970   // and flag operands which copy the outgoing args into the appropriate regs.
971   SDValue InFlag;
972   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
973     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
974                              RegsToPass[i].second, InFlag);
975     InFlag = Chain.getValue(1);
976   }
977
978   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
979   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
980   // node so that legalize doesn't hack it.
981   bool isDirect = false;
982   bool isARMFunc = false;
983   bool isLocalARMFunc = false;
984   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
985     GlobalValue *GV = G->getGlobal();
986     isDirect = true;
987     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
988     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
989                    getTargetMachine().getRelocationModel() != Reloc::Static;
990     isARMFunc = !Subtarget->isThumb() || isStub;
991     // ARM call to a local ARM function is predicable.
992     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
993     // tBX takes a register source operand.
994     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
995       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
996                                                            ARMPCLabelIndex,
997                                                            ARMCP::CPValue, 4);
998       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
999       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1000       Callee = DAG.getLoad(getPointerTy(), dl,
1001                            DAG.getEntryNode(), CPAddr, NULL, 0);
1002       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1003       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1004                            getPointerTy(), Callee, PICLabel);
1005    } else
1006       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
1007   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1008     isDirect = true;
1009     bool isStub = Subtarget->isTargetDarwin() &&
1010                   getTargetMachine().getRelocationModel() != Reloc::Static;
1011     isARMFunc = !Subtarget->isThumb() || isStub;
1012     // tBX takes a register source operand.
1013     const char *Sym = S->getSymbol();
1014     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1015       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1016                                                        Sym, ARMPCLabelIndex, 4);
1017       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1018       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1019       Callee = DAG.getLoad(getPointerTy(), dl,
1020                            DAG.getEntryNode(), CPAddr, NULL, 0);
1021       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1022       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1023                            getPointerTy(), Callee, PICLabel);
1024     } else
1025       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1026   }
1027
1028   // FIXME: handle tail calls differently.
1029   unsigned CallOpc;
1030   if (Subtarget->isThumb()) {
1031     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1032       CallOpc = ARMISD::CALL_NOLINK;
1033     else
1034       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1035   } else {
1036     CallOpc = (isDirect || Subtarget->hasV5TOps())
1037       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1038       : ARMISD::CALL_NOLINK;
1039   }
1040   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb1Only()) {
1041     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
1042     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
1043     InFlag = Chain.getValue(1);
1044   }
1045
1046   std::vector<SDValue> Ops;
1047   Ops.push_back(Chain);
1048   Ops.push_back(Callee);
1049
1050   // Add argument registers to the end of the list so that they are known live
1051   // into the call.
1052   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1053     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1054                                   RegsToPass[i].second.getValueType()));
1055
1056   if (InFlag.getNode())
1057     Ops.push_back(InFlag);
1058   // Returns a chain and a flag for retval copy to use.
1059   Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
1060                       &Ops[0], Ops.size());
1061   InFlag = Chain.getValue(1);
1062
1063   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1064                              DAG.getIntPtrConstant(0, true), InFlag);
1065   if (!Ins.empty())
1066     InFlag = Chain.getValue(1);
1067
1068   // Handle result values, copying them out of physregs into vregs that we
1069   // return.
1070   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1071                          dl, DAG, InVals);
1072 }
1073
1074 SDValue
1075 ARMTargetLowering::LowerReturn(SDValue Chain,
1076                                CallingConv::ID CallConv, bool isVarArg,
1077                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1078                                DebugLoc dl, SelectionDAG &DAG) {
1079
1080   // CCValAssign - represent the assignment of the return value to a location.
1081   SmallVector<CCValAssign, 16> RVLocs;
1082
1083   // CCState - Info about the registers and stack slots.
1084   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1085                  *DAG.getContext());
1086
1087   // Analyze outgoing return values.
1088   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1089                                                isVarArg));
1090
1091   // If this is the first return lowered for this function, add
1092   // the regs to the liveout set for the function.
1093   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1094     for (unsigned i = 0; i != RVLocs.size(); ++i)
1095       if (RVLocs[i].isRegLoc())
1096         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1097   }
1098
1099   SDValue Flag;
1100
1101   // Copy the result values into the output registers.
1102   for (unsigned i = 0, realRVLocIdx = 0;
1103        i != RVLocs.size();
1104        ++i, ++realRVLocIdx) {
1105     CCValAssign &VA = RVLocs[i];
1106     assert(VA.isRegLoc() && "Can only return in registers!");
1107
1108     SDValue Arg = Outs[realRVLocIdx].Val;
1109
1110     switch (VA.getLocInfo()) {
1111     default: llvm_unreachable("Unknown loc info!");
1112     case CCValAssign::Full: break;
1113     case CCValAssign::BCvt:
1114       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
1115       break;
1116     }
1117
1118     if (VA.needsCustom()) {
1119       if (VA.getLocVT() == MVT::v2f64) {
1120         // Extract the first half and return it in two registers.
1121         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1122                                    DAG.getConstant(0, MVT::i32));
1123         SDValue HalfGPRs = DAG.getNode(ARMISD::FMRRD, dl,
1124                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1125
1126         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1127         Flag = Chain.getValue(1);
1128         VA = RVLocs[++i]; // skip ahead to next loc
1129         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1130                                  HalfGPRs.getValue(1), Flag);
1131         Flag = Chain.getValue(1);
1132         VA = RVLocs[++i]; // skip ahead to next loc
1133
1134         // Extract the 2nd half and fall through to handle it as an f64 value.
1135         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1136                           DAG.getConstant(1, MVT::i32));
1137       }
1138       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1139       // available.
1140       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
1141                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1142       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1143       Flag = Chain.getValue(1);
1144       VA = RVLocs[++i]; // skip ahead to next loc
1145       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1146                                Flag);
1147     } else
1148       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1149
1150     // Guarantee that all emitted copies are
1151     // stuck together, avoiding something bad.
1152     Flag = Chain.getValue(1);
1153   }
1154
1155   SDValue result;
1156   if (Flag.getNode())
1157     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1158   else // Return Void
1159     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1160
1161   return result;
1162 }
1163
1164 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1165 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1166 // one of the above mentioned nodes. It has to be wrapped because otherwise
1167 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1168 // be used to form addressing mode. These wrapped nodes will be selected
1169 // into MOVi.
1170 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1171   EVT PtrVT = Op.getValueType();
1172   // FIXME there is no actual debug info here
1173   DebugLoc dl = Op.getDebugLoc();
1174   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1175   SDValue Res;
1176   if (CP->isMachineConstantPoolEntry())
1177     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1178                                     CP->getAlignment());
1179   else
1180     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1181                                     CP->getAlignment());
1182   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1183 }
1184
1185 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1186 SDValue
1187 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1188                                                  SelectionDAG &DAG) {
1189   DebugLoc dl = GA->getDebugLoc();
1190   EVT PtrVT = getPointerTy();
1191   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1192   ARMConstantPoolValue *CPV =
1193     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1194                              ARMCP::CPValue, PCAdj, "tlsgd", true);
1195   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1196   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1197   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
1198   SDValue Chain = Argument.getValue(1);
1199
1200   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1201   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1202
1203   // call __tls_get_addr.
1204   ArgListTy Args;
1205   ArgListEntry Entry;
1206   Entry.Node = Argument;
1207   Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1208   Args.push_back(Entry);
1209   // FIXME: is there useful debug info available here?
1210   std::pair<SDValue, SDValue> CallResult =
1211     LowerCallTo(Chain, (const Type *) Type::getInt32Ty(*DAG.getContext()),
1212                 false, false, false, false,
1213                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1214                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1215   return CallResult.first;
1216 }
1217
1218 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1219 // "local exec" model.
1220 SDValue
1221 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1222                                         SelectionDAG &DAG) {
1223   GlobalValue *GV = GA->getGlobal();
1224   DebugLoc dl = GA->getDebugLoc();
1225   SDValue Offset;
1226   SDValue Chain = DAG.getEntryNode();
1227   EVT PtrVT = getPointerTy();
1228   // Get the Thread Pointer
1229   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1230
1231   if (GV->isDeclaration()) {
1232     // initial exec model
1233     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1234     ARMConstantPoolValue *CPV =
1235       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1236                                ARMCP::CPValue, PCAdj, "gottpoff", true);
1237     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1238     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1239     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1240     Chain = Offset.getValue(1);
1241
1242     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1243     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1244
1245     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1246   } else {
1247     // local exec model
1248     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, "tpoff");
1249     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1250     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1251     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1252   }
1253
1254   // The address of the thread local variable is the add of the thread
1255   // pointer with the offset of the variable.
1256   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1257 }
1258
1259 SDValue
1260 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
1261   // TODO: implement the "local dynamic" model
1262   assert(Subtarget->isTargetELF() &&
1263          "TLS not implemented for non-ELF targets");
1264   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1265   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1266   // otherwise use the "Local Exec" TLS Model
1267   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1268     return LowerToTLSGeneralDynamicModel(GA, DAG);
1269   else
1270     return LowerToTLSExecModels(GA, DAG);
1271 }
1272
1273 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1274                                                  SelectionDAG &DAG) {
1275   EVT PtrVT = getPointerTy();
1276   DebugLoc dl = Op.getDebugLoc();
1277   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1278   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1279   if (RelocM == Reloc::PIC_) {
1280     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1281     ARMConstantPoolValue *CPV =
1282       new ARMConstantPoolValue(GV, UseGOTOFF ? "GOTOFF" : "GOT");
1283     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1284     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1285     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1286                                  CPAddr, NULL, 0);
1287     SDValue Chain = Result.getValue(1);
1288     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1289     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
1290     if (!UseGOTOFF)
1291       Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1292     return Result;
1293   } else {
1294     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1295     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1296     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1297   }
1298 }
1299
1300 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
1301                                                     SelectionDAG &DAG) {
1302   EVT PtrVT = getPointerTy();
1303   DebugLoc dl = Op.getDebugLoc();
1304   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1305   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1306   SDValue CPAddr;
1307   if (RelocM == Reloc::Static)
1308     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1309   else {
1310     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
1311     ARMConstantPoolValue *CPV =
1312       new ARMConstantPoolValue(GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj);
1313     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1314   }
1315   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1316
1317   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1318   SDValue Chain = Result.getValue(1);
1319
1320   if (RelocM == Reloc::PIC_) {
1321     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1322     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1323   }
1324
1325   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
1326     Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1327
1328   return Result;
1329 }
1330
1331 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1332                                                     SelectionDAG &DAG){
1333   assert(Subtarget->isTargetELF() &&
1334          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1335   EVT PtrVT = getPointerTy();
1336   DebugLoc dl = Op.getDebugLoc();
1337   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1338   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1339                                                        "_GLOBAL_OFFSET_TABLE_",
1340                                                        ARMPCLabelIndex, PCAdj);
1341   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1342   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1343   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1344   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1345   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1346 }
1347
1348 static SDValue LowerNeonVLDIntrinsic(SDValue Op, SelectionDAG &DAG,
1349                                      unsigned NumVecs) {
1350   SDNode *Node = Op.getNode();
1351   EVT VT = Node->getValueType(0);
1352
1353   // No expansion needed for 64-bit vectors.
1354   if (VT.is64BitVector())
1355     return SDValue();
1356
1357   // FIXME: We need to expand VLD3 and VLD4 of 128-bit vectors into separate
1358   // operations to load the even and odd registers.
1359   return SDValue();
1360 }
1361
1362 static SDValue LowerNeonVSTIntrinsic(SDValue Op, SelectionDAG &DAG,
1363                                      unsigned NumVecs) {
1364   SDNode *Node = Op.getNode();
1365   EVT VT = Node->getOperand(3).getValueType();
1366
1367   // No expansion needed for 64-bit vectors.
1368   if (VT.is64BitVector())
1369     return SDValue();
1370
1371   // FIXME: We need to expand VST3 and VST4 of 128-bit vectors into separate
1372   // operations to store the even and odd registers.
1373   return SDValue();
1374 }
1375
1376 static SDValue LowerNeonVLDLaneIntrinsic(SDValue Op, SelectionDAG &DAG,
1377                                          unsigned NumVecs) {
1378   SDNode *Node = Op.getNode();
1379   EVT VT = Node->getValueType(0);
1380
1381   if (!VT.is64BitVector())
1382     return SDValue(); // unimplemented
1383
1384   // Change the lane number operand to be a TargetConstant; otherwise it
1385   // will be legalized into a register.
1386   ConstantSDNode *Lane = dyn_cast<ConstantSDNode>(Node->getOperand(NumVecs+3));
1387   if (!Lane) {
1388     assert(false && "vld lane number must be a constant");
1389     return SDValue();
1390   }
1391   SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1392   Ops[NumVecs+3] = DAG.getTargetConstant(Lane->getZExtValue(), MVT::i32);
1393   return DAG.UpdateNodeOperands(Op, &Ops[0], Ops.size());
1394 }
1395
1396 static SDValue LowerNeonVSTLaneIntrinsic(SDValue Op, SelectionDAG &DAG,
1397                                          unsigned NumVecs) {
1398   SDNode *Node = Op.getNode();
1399   EVT VT = Node->getOperand(3).getValueType();
1400
1401   if (!VT.is64BitVector())
1402     return SDValue(); // unimplemented
1403
1404   // Change the lane number operand to be a TargetConstant; otherwise it
1405   // will be legalized into a register.
1406   ConstantSDNode *Lane = dyn_cast<ConstantSDNode>(Node->getOperand(NumVecs+3));
1407   if (!Lane) {
1408     assert(false && "vst lane number must be a constant");
1409     return SDValue();
1410   }
1411   SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1412   Ops[NumVecs+3] = DAG.getTargetConstant(Lane->getZExtValue(), MVT::i32);
1413   return DAG.UpdateNodeOperands(Op, &Ops[0], Ops.size());
1414 }
1415
1416 SDValue
1417 ARMTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
1418   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1419   switch (IntNo) {
1420   case Intrinsic::arm_neon_vld3:
1421     return LowerNeonVLDIntrinsic(Op, DAG, 3);
1422   case Intrinsic::arm_neon_vld4:
1423     return LowerNeonVLDIntrinsic(Op, DAG, 4);
1424   case Intrinsic::arm_neon_vld2lane:
1425     return LowerNeonVLDLaneIntrinsic(Op, DAG, 2);
1426   case Intrinsic::arm_neon_vld3lane:
1427     return LowerNeonVLDLaneIntrinsic(Op, DAG, 3);
1428   case Intrinsic::arm_neon_vld4lane:
1429     return LowerNeonVLDLaneIntrinsic(Op, DAG, 4);
1430   case Intrinsic::arm_neon_vst3:
1431     return LowerNeonVSTIntrinsic(Op, DAG, 3);
1432   case Intrinsic::arm_neon_vst4:
1433     return LowerNeonVSTIntrinsic(Op, DAG, 4);
1434   case Intrinsic::arm_neon_vst2lane:
1435     return LowerNeonVSTLaneIntrinsic(Op, DAG, 2);
1436   case Intrinsic::arm_neon_vst3lane:
1437     return LowerNeonVSTLaneIntrinsic(Op, DAG, 3);
1438   case Intrinsic::arm_neon_vst4lane:
1439     return LowerNeonVSTLaneIntrinsic(Op, DAG, 4);
1440   default: return SDValue();    // Don't custom lower most intrinsics.
1441   }
1442 }
1443
1444 SDValue
1445 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1446   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1447   DebugLoc dl = Op.getDebugLoc();
1448   switch (IntNo) {
1449   default: return SDValue();    // Don't custom lower most intrinsics.
1450   case Intrinsic::arm_thread_pointer: {
1451     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1452     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1453   }
1454   case Intrinsic::eh_sjlj_lsda: {
1455     MachineFunction &MF = DAG.getMachineFunction();
1456     EVT PtrVT = getPointerTy();
1457     DebugLoc dl = Op.getDebugLoc();
1458     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1459     SDValue CPAddr;
1460     unsigned PCAdj = (RelocM != Reloc::PIC_)
1461       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1462     ARMConstantPoolValue *CPV =
1463       new ARMConstantPoolValue(MF.getFunction(), ARMPCLabelIndex,
1464                                ARMCP::CPLSDA, PCAdj);
1465     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1466     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1467     SDValue Result =
1468       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1469     SDValue Chain = Result.getValue(1);
1470
1471     if (RelocM == Reloc::PIC_) {
1472       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1473       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1474     }
1475     return Result;
1476   }
1477   case Intrinsic::eh_sjlj_setjmp:
1478     return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(1));
1479   }
1480 }
1481
1482 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1483                             unsigned VarArgsFrameIndex) {
1484   // vastart just stores the address of the VarArgsFrameIndex slot into the
1485   // memory location argument.
1486   DebugLoc dl = Op.getDebugLoc();
1487   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1488   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1489   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1490   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1491 }
1492
1493 SDValue
1494 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1495   SDNode *Node = Op.getNode();
1496   DebugLoc dl = Node->getDebugLoc();
1497   EVT VT = Node->getValueType(0);
1498   SDValue Chain = Op.getOperand(0);
1499   SDValue Size  = Op.getOperand(1);
1500   SDValue Align = Op.getOperand(2);
1501
1502   // Chain the dynamic stack allocation so that it doesn't modify the stack
1503   // pointer when other instructions are using the stack.
1504   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1505
1506   unsigned AlignVal = cast<ConstantSDNode>(Align)->getZExtValue();
1507   unsigned StackAlign = getTargetMachine().getFrameInfo()->getStackAlignment();
1508   if (AlignVal > StackAlign)
1509     // Do this now since selection pass cannot introduce new target
1510     // independent node.
1511     Align = DAG.getConstant(-(uint64_t)AlignVal, VT);
1512
1513   // In Thumb1 mode, there isn't a "sub r, sp, r" instruction, we will end up
1514   // using a "add r, sp, r" instead. Negate the size now so we don't have to
1515   // do even more horrible hack later.
1516   MachineFunction &MF = DAG.getMachineFunction();
1517   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1518   if (AFI->isThumb1OnlyFunction()) {
1519     bool Negate = true;
1520     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Size);
1521     if (C) {
1522       uint32_t Val = C->getZExtValue();
1523       if (Val <= 508 && ((Val & 3) == 0))
1524         Negate = false;
1525     }
1526     if (Negate)
1527       Size = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, VT), Size);
1528   }
1529
1530   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1531   SDValue Ops1[] = { Chain, Size, Align };
1532   SDValue Res = DAG.getNode(ARMISD::DYN_ALLOC, dl, VTList, Ops1, 3);
1533   Chain = Res.getValue(1);
1534   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1535                              DAG.getIntPtrConstant(0, true), SDValue());
1536   SDValue Ops2[] = { Res, Chain };
1537   return DAG.getMergeValues(Ops2, 2, dl);
1538 }
1539
1540 SDValue
1541 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1542                                         SDValue &Root, SelectionDAG &DAG,
1543                                         DebugLoc dl) {
1544   MachineFunction &MF = DAG.getMachineFunction();
1545   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1546
1547   TargetRegisterClass *RC;
1548   if (AFI->isThumb1OnlyFunction())
1549     RC = ARM::tGPRRegisterClass;
1550   else
1551     RC = ARM::GPRRegisterClass;
1552
1553   // Transform the arguments stored in physical registers into virtual ones.
1554   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1555   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1556
1557   SDValue ArgValue2;
1558   if (NextVA.isMemLoc()) {
1559     unsigned ArgSize = NextVA.getLocVT().getSizeInBits()/8;
1560     MachineFrameInfo *MFI = MF.getFrameInfo();
1561     int FI = MFI->CreateFixedObject(ArgSize, NextVA.getLocMemOffset());
1562
1563     // Create load node to retrieve arguments from the stack.
1564     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1565     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1566   } else {
1567     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1568     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1569   }
1570
1571   return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
1572 }
1573
1574 SDValue
1575 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1576                                         CallingConv::ID CallConv, bool isVarArg,
1577                                         const SmallVectorImpl<ISD::InputArg>
1578                                           &Ins,
1579                                         DebugLoc dl, SelectionDAG &DAG,
1580                                         SmallVectorImpl<SDValue> &InVals) {
1581
1582   MachineFunction &MF = DAG.getMachineFunction();
1583   MachineFrameInfo *MFI = MF.getFrameInfo();
1584
1585   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1586
1587   // Assign locations to all of the incoming arguments.
1588   SmallVector<CCValAssign, 16> ArgLocs;
1589   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1590                  *DAG.getContext());
1591   CCInfo.AnalyzeFormalArguments(Ins,
1592                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1593                                                   isVarArg));
1594
1595   SmallVector<SDValue, 16> ArgValues;
1596
1597   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1598     CCValAssign &VA = ArgLocs[i];
1599
1600     // Arguments stored in registers.
1601     if (VA.isRegLoc()) {
1602       EVT RegVT = VA.getLocVT();
1603
1604       SDValue ArgValue;
1605       if (VA.needsCustom()) {
1606         // f64 and vector types are split up into multiple registers or
1607         // combinations of registers and stack slots.
1608         RegVT = MVT::i32;
1609
1610         if (VA.getLocVT() == MVT::v2f64) {
1611           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1612                                                    Chain, DAG, dl);
1613           VA = ArgLocs[++i]; // skip ahead to next loc
1614           SDValue ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1615                                                    Chain, DAG, dl);
1616           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1617           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1618                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1619           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1620                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1621         } else
1622           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
1623
1624       } else {
1625         TargetRegisterClass *RC;
1626
1627         if (RegVT == MVT::f32)
1628           RC = ARM::SPRRegisterClass;
1629         else if (RegVT == MVT::f64)
1630           RC = ARM::DPRRegisterClass;
1631         else if (RegVT == MVT::v2f64)
1632           RC = ARM::QPRRegisterClass;
1633         else if (RegVT == MVT::i32)
1634           RC = (AFI->isThumb1OnlyFunction() ?
1635                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
1636         else
1637           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1638
1639         // Transform the arguments in physical registers into virtual ones.
1640         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1641         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1642       }
1643
1644       // If this is an 8 or 16-bit value, it is really passed promoted
1645       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1646       // truncate to the right size.
1647       switch (VA.getLocInfo()) {
1648       default: llvm_unreachable("Unknown loc info!");
1649       case CCValAssign::Full: break;
1650       case CCValAssign::BCvt:
1651         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1652         break;
1653       case CCValAssign::SExt:
1654         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1655                                DAG.getValueType(VA.getValVT()));
1656         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1657         break;
1658       case CCValAssign::ZExt:
1659         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1660                                DAG.getValueType(VA.getValVT()));
1661         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1662         break;
1663       }
1664
1665       InVals.push_back(ArgValue);
1666
1667     } else { // VA.isRegLoc()
1668
1669       // sanity check
1670       assert(VA.isMemLoc());
1671       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1672
1673       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1674       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1675
1676       // Create load nodes to retrieve arguments from the stack.
1677       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1678       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
1679     }
1680   }
1681
1682   // varargs
1683   if (isVarArg) {
1684     static const unsigned GPRArgRegs[] = {
1685       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1686     };
1687
1688     unsigned NumGPRs = CCInfo.getFirstUnallocated
1689       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1690
1691     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1692     unsigned VARegSize = (4 - NumGPRs) * 4;
1693     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1694     unsigned ArgOffset = 0;
1695     if (VARegSaveSize) {
1696       // If this function is vararg, store any remaining integer argument regs
1697       // to their spots on the stack so that they may be loaded by deferencing
1698       // the result of va_next.
1699       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1700       ArgOffset = CCInfo.getNextStackOffset();
1701       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1702                                                  VARegSaveSize - VARegSize);
1703       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1704
1705       SmallVector<SDValue, 4> MemOps;
1706       for (; NumGPRs < 4; ++NumGPRs) {
1707         TargetRegisterClass *RC;
1708         if (AFI->isThumb1OnlyFunction())
1709           RC = ARM::tGPRRegisterClass;
1710         else
1711           RC = ARM::GPRRegisterClass;
1712
1713         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1714         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1715         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1716         MemOps.push_back(Store);
1717         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1718                           DAG.getConstant(4, getPointerTy()));
1719       }
1720       if (!MemOps.empty())
1721         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1722                             &MemOps[0], MemOps.size());
1723     } else
1724       // This will point to the next argument passed via stack.
1725       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1726   }
1727
1728   return Chain;
1729 }
1730
1731 /// isFloatingPointZero - Return true if this is +0.0.
1732 static bool isFloatingPointZero(SDValue Op) {
1733   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1734     return CFP->getValueAPF().isPosZero();
1735   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1736     // Maybe this has already been legalized into the constant pool?
1737     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1738       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1739       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1740         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1741           return CFP->getValueAPF().isPosZero();
1742     }
1743   }
1744   return false;
1745 }
1746
1747 static bool isLegalCmpImmediate(unsigned C, bool isThumb1Only) {
1748   return ( isThumb1Only && (C & ~255U) == 0) ||
1749          (!isThumb1Only && ARM_AM::getSOImmVal(C) != -1);
1750 }
1751
1752 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1753 /// the given operands.
1754 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1755                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb1Only,
1756                          DebugLoc dl) {
1757   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1758     unsigned C = RHSC->getZExtValue();
1759     if (!isLegalCmpImmediate(C, isThumb1Only)) {
1760       // Constant does not fit, try adjusting it by one?
1761       switch (CC) {
1762       default: break;
1763       case ISD::SETLT:
1764       case ISD::SETGE:
1765         if (isLegalCmpImmediate(C-1, isThumb1Only)) {
1766           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1767           RHS = DAG.getConstant(C-1, MVT::i32);
1768         }
1769         break;
1770       case ISD::SETULT:
1771       case ISD::SETUGE:
1772         if (C > 0 && isLegalCmpImmediate(C-1, isThumb1Only)) {
1773           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1774           RHS = DAG.getConstant(C-1, MVT::i32);
1775         }
1776         break;
1777       case ISD::SETLE:
1778       case ISD::SETGT:
1779         if (isLegalCmpImmediate(C+1, isThumb1Only)) {
1780           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1781           RHS = DAG.getConstant(C+1, MVT::i32);
1782         }
1783         break;
1784       case ISD::SETULE:
1785       case ISD::SETUGT:
1786         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb1Only)) {
1787           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1788           RHS = DAG.getConstant(C+1, MVT::i32);
1789         }
1790         break;
1791       }
1792     }
1793   }
1794
1795   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1796   ARMISD::NodeType CompareType;
1797   switch (CondCode) {
1798   default:
1799     CompareType = ARMISD::CMP;
1800     break;
1801   case ARMCC::EQ:
1802   case ARMCC::NE:
1803     // Uses only Z Flag
1804     CompareType = ARMISD::CMPZ;
1805     break;
1806   }
1807   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1808   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1809 }
1810
1811 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1812 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1813                          DebugLoc dl) {
1814   SDValue Cmp;
1815   if (!isFloatingPointZero(RHS))
1816     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1817   else
1818     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1819   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1820 }
1821
1822 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1823                               const ARMSubtarget *ST) {
1824   EVT VT = Op.getValueType();
1825   SDValue LHS = Op.getOperand(0);
1826   SDValue RHS = Op.getOperand(1);
1827   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1828   SDValue TrueVal = Op.getOperand(2);
1829   SDValue FalseVal = Op.getOperand(3);
1830   DebugLoc dl = Op.getDebugLoc();
1831
1832   if (LHS.getValueType() == MVT::i32) {
1833     SDValue ARMCC;
1834     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1835     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1836     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1837   }
1838
1839   ARMCC::CondCodes CondCode, CondCode2;
1840   FPCCToARMCC(CC, CondCode, CondCode2);
1841
1842   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1843   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1844   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1845   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1846                                  ARMCC, CCR, Cmp);
1847   if (CondCode2 != ARMCC::AL) {
1848     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1849     // FIXME: Needs another CMP because flag can have but one use.
1850     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1851     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1852                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1853   }
1854   return Result;
1855 }
1856
1857 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1858                           const ARMSubtarget *ST) {
1859   SDValue  Chain = Op.getOperand(0);
1860   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1861   SDValue    LHS = Op.getOperand(2);
1862   SDValue    RHS = Op.getOperand(3);
1863   SDValue   Dest = Op.getOperand(4);
1864   DebugLoc dl = Op.getDebugLoc();
1865
1866   if (LHS.getValueType() == MVT::i32) {
1867     SDValue ARMCC;
1868     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1869     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1870     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1871                        Chain, Dest, ARMCC, CCR,Cmp);
1872   }
1873
1874   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1875   ARMCC::CondCodes CondCode, CondCode2;
1876   FPCCToARMCC(CC, CondCode, CondCode2);
1877
1878   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1879   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1880   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1881   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1882   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1883   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1884   if (CondCode2 != ARMCC::AL) {
1885     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1886     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1887     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1888   }
1889   return Res;
1890 }
1891
1892 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1893   SDValue Chain = Op.getOperand(0);
1894   SDValue Table = Op.getOperand(1);
1895   SDValue Index = Op.getOperand(2);
1896   DebugLoc dl = Op.getDebugLoc();
1897
1898   EVT PTy = getPointerTy();
1899   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1900   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1901   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1902   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1903   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1904   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1905   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1906   if (Subtarget->isThumb2()) {
1907     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1908     // which does another jump to the destination. This also makes it easier
1909     // to translate it to TBB / TBH later.
1910     // FIXME: This might not work if the function is extremely large.
1911     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1912                        Addr, Op.getOperand(2), JTI, UId);
1913   }
1914   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1915     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, NULL, 0);
1916     Chain = Addr.getValue(1);
1917     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1918     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1919   } else {
1920     Addr = DAG.getLoad(PTy, dl, Chain, Addr, NULL, 0);
1921     Chain = Addr.getValue(1);
1922     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1923   }
1924 }
1925
1926 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1927   DebugLoc dl = Op.getDebugLoc();
1928   unsigned Opc =
1929     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1930   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1931   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1932 }
1933
1934 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1935   EVT VT = Op.getValueType();
1936   DebugLoc dl = Op.getDebugLoc();
1937   unsigned Opc =
1938     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1939
1940   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1941   return DAG.getNode(Opc, dl, VT, Op);
1942 }
1943
1944 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1945   // Implement fcopysign with a fabs and a conditional fneg.
1946   SDValue Tmp0 = Op.getOperand(0);
1947   SDValue Tmp1 = Op.getOperand(1);
1948   DebugLoc dl = Op.getDebugLoc();
1949   EVT VT = Op.getValueType();
1950   EVT SrcVT = Tmp1.getValueType();
1951   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1952   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1953   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1954   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1955   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1956 }
1957
1958 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1959   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1960   MFI->setFrameAddressIsTaken(true);
1961   EVT VT = Op.getValueType();
1962   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1963   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1964   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1965     ? ARM::R7 : ARM::R11;
1966   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1967   while (Depth--)
1968     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1969   return FrameAddr;
1970 }
1971
1972 SDValue
1973 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1974                                            SDValue Chain,
1975                                            SDValue Dst, SDValue Src,
1976                                            SDValue Size, unsigned Align,
1977                                            bool AlwaysInline,
1978                                          const Value *DstSV, uint64_t DstSVOff,
1979                                          const Value *SrcSV, uint64_t SrcSVOff){
1980   // Do repeated 4-byte loads and stores. To be improved.
1981   // This requires 4-byte alignment.
1982   if ((Align & 3) != 0)
1983     return SDValue();
1984   // This requires the copy size to be a constant, preferrably
1985   // within a subtarget-specific limit.
1986   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1987   if (!ConstantSize)
1988     return SDValue();
1989   uint64_t SizeVal = ConstantSize->getZExtValue();
1990   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1991     return SDValue();
1992
1993   unsigned BytesLeft = SizeVal & 3;
1994   unsigned NumMemOps = SizeVal >> 2;
1995   unsigned EmittedNumMemOps = 0;
1996   EVT VT = MVT::i32;
1997   unsigned VTSize = 4;
1998   unsigned i = 0;
1999   const unsigned MAX_LOADS_IN_LDM = 6;
2000   SDValue TFOps[MAX_LOADS_IN_LDM];
2001   SDValue Loads[MAX_LOADS_IN_LDM];
2002   uint64_t SrcOff = 0, DstOff = 0;
2003
2004   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
2005   // same number of stores.  The loads and stores will get combined into
2006   // ldm/stm later on.
2007   while (EmittedNumMemOps < NumMemOps) {
2008     for (i = 0;
2009          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
2010       Loads[i] = DAG.getLoad(VT, dl, Chain,
2011                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2012                                          DAG.getConstant(SrcOff, MVT::i32)),
2013                              SrcSV, SrcSVOff + SrcOff);
2014       TFOps[i] = Loads[i].getValue(1);
2015       SrcOff += VTSize;
2016     }
2017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2018
2019     for (i = 0;
2020          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
2021       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2022                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2023                                        DAG.getConstant(DstOff, MVT::i32)),
2024                            DstSV, DstSVOff + DstOff);
2025       DstOff += VTSize;
2026     }
2027     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2028
2029     EmittedNumMemOps += i;
2030   }
2031
2032   if (BytesLeft == 0)
2033     return Chain;
2034
2035   // Issue loads / stores for the trailing (1 - 3) bytes.
2036   unsigned BytesLeftSave = BytesLeft;
2037   i = 0;
2038   while (BytesLeft) {
2039     if (BytesLeft >= 2) {
2040       VT = MVT::i16;
2041       VTSize = 2;
2042     } else {
2043       VT = MVT::i8;
2044       VTSize = 1;
2045     }
2046
2047     Loads[i] = DAG.getLoad(VT, dl, Chain,
2048                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2049                                        DAG.getConstant(SrcOff, MVT::i32)),
2050                            SrcSV, SrcSVOff + SrcOff);
2051     TFOps[i] = Loads[i].getValue(1);
2052     ++i;
2053     SrcOff += VTSize;
2054     BytesLeft -= VTSize;
2055   }
2056   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2057
2058   i = 0;
2059   BytesLeft = BytesLeftSave;
2060   while (BytesLeft) {
2061     if (BytesLeft >= 2) {
2062       VT = MVT::i16;
2063       VTSize = 2;
2064     } else {
2065       VT = MVT::i8;
2066       VTSize = 1;
2067     }
2068
2069     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2070                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2071                                         DAG.getConstant(DstOff, MVT::i32)),
2072                             DstSV, DstSVOff + DstOff);
2073     ++i;
2074     DstOff += VTSize;
2075     BytesLeft -= VTSize;
2076   }
2077   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2078 }
2079
2080 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
2081   SDValue Op = N->getOperand(0);
2082   DebugLoc dl = N->getDebugLoc();
2083   if (N->getValueType(0) == MVT::f64) {
2084     // Turn i64->f64 into FMDRR.
2085     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2086                              DAG.getConstant(0, MVT::i32));
2087     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2088                              DAG.getConstant(1, MVT::i32));
2089     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
2090   }
2091
2092   // Turn f64->i64 into FMRRD.
2093   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
2094                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
2095
2096   // Merge the pieces into a single i64 value.
2097   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
2098 }
2099
2100 /// getZeroVector - Returns a vector of specified type with all zero elements.
2101 ///
2102 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2103   assert(VT.isVector() && "Expected a vector type");
2104
2105   // Zero vectors are used to represent vector negation and in those cases
2106   // will be implemented with the NEON VNEG instruction.  However, VNEG does
2107   // not support i64 elements, so sometimes the zero vectors will need to be
2108   // explicitly constructed.  For those cases, and potentially other uses in
2109   // the future, always build zero vectors as <16 x i8> or <8 x i8> bitcasted
2110   // to their dest type.  This ensures they get CSE'd.
2111   SDValue Vec;
2112   SDValue Cst = DAG.getTargetConstant(0, MVT::i8);
2113   SmallVector<SDValue, 8> Ops;
2114   MVT TVT;
2115
2116   if (VT.getSizeInBits() == 64) {
2117     Ops.assign(8, Cst); TVT = MVT::v8i8;
2118   } else {
2119     Ops.assign(16, Cst); TVT = MVT::v16i8;
2120   }
2121   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2122
2123   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2124 }
2125
2126 /// getOnesVector - Returns a vector of specified type with all bits set.
2127 ///
2128 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2129   assert(VT.isVector() && "Expected a vector type");
2130
2131   // Always build ones vectors as <16 x i32> or <8 x i32> bitcasted to their
2132   // dest type. This ensures they get CSE'd.
2133   SDValue Vec;
2134   SDValue Cst = DAG.getTargetConstant(0xFF, MVT::i8);
2135   SmallVector<SDValue, 8> Ops;
2136   MVT TVT;
2137
2138   if (VT.getSizeInBits() == 64) {
2139     Ops.assign(8, Cst); TVT = MVT::v8i8;
2140   } else {
2141     Ops.assign(16, Cst); TVT = MVT::v16i8;
2142   }
2143   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2144
2145   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2146 }
2147
2148 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
2149                           const ARMSubtarget *ST) {
2150   EVT VT = N->getValueType(0);
2151   DebugLoc dl = N->getDebugLoc();
2152
2153   // Lower vector shifts on NEON to use VSHL.
2154   if (VT.isVector()) {
2155     assert(ST->hasNEON() && "unexpected vector shift");
2156
2157     // Left shifts translate directly to the vshiftu intrinsic.
2158     if (N->getOpcode() == ISD::SHL)
2159       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2160                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2161                          N->getOperand(0), N->getOperand(1));
2162
2163     assert((N->getOpcode() == ISD::SRA ||
2164             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2165
2166     // NEON uses the same intrinsics for both left and right shifts.  For
2167     // right shifts, the shift amounts are negative, so negate the vector of
2168     // shift amounts.
2169     EVT ShiftVT = N->getOperand(1).getValueType();
2170     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2171                                        getZeroVector(ShiftVT, DAG, dl),
2172                                        N->getOperand(1));
2173     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2174                                Intrinsic::arm_neon_vshifts :
2175                                Intrinsic::arm_neon_vshiftu);
2176     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2177                        DAG.getConstant(vshiftInt, MVT::i32),
2178                        N->getOperand(0), NegatedCount);
2179   }
2180
2181   // We can get here for a node like i32 = ISD::SHL i32, i64
2182   if (VT != MVT::i64)
2183     return SDValue();
2184
2185   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2186          "Unknown shift to lower!");
2187
2188   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2189   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2190       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2191     return SDValue();
2192
2193   // If we are in thumb mode, we don't have RRX.
2194   if (ST->isThumb1Only()) return SDValue();
2195
2196   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2197   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2198                              DAG.getConstant(0, MVT::i32));
2199   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2200                              DAG.getConstant(1, MVT::i32));
2201
2202   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2203   // captures the result into a carry flag.
2204   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2205   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2206
2207   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2208   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2209
2210   // Merge the pieces into a single i64 value.
2211  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2212 }
2213
2214 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2215   SDValue TmpOp0, TmpOp1;
2216   bool Invert = false;
2217   bool Swap = false;
2218   unsigned Opc = 0;
2219
2220   SDValue Op0 = Op.getOperand(0);
2221   SDValue Op1 = Op.getOperand(1);
2222   SDValue CC = Op.getOperand(2);
2223   EVT VT = Op.getValueType();
2224   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2225   DebugLoc dl = Op.getDebugLoc();
2226
2227   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2228     switch (SetCCOpcode) {
2229     default: llvm_unreachable("Illegal FP comparison"); break;
2230     case ISD::SETUNE:
2231     case ISD::SETNE:  Invert = true; // Fallthrough
2232     case ISD::SETOEQ:
2233     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2234     case ISD::SETOLT:
2235     case ISD::SETLT: Swap = true; // Fallthrough
2236     case ISD::SETOGT:
2237     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2238     case ISD::SETOLE:
2239     case ISD::SETLE:  Swap = true; // Fallthrough
2240     case ISD::SETOGE:
2241     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2242     case ISD::SETUGE: Swap = true; // Fallthrough
2243     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2244     case ISD::SETUGT: Swap = true; // Fallthrough
2245     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2246     case ISD::SETUEQ: Invert = true; // Fallthrough
2247     case ISD::SETONE:
2248       // Expand this to (OLT | OGT).
2249       TmpOp0 = Op0;
2250       TmpOp1 = Op1;
2251       Opc = ISD::OR;
2252       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2253       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2254       break;
2255     case ISD::SETUO: Invert = true; // Fallthrough
2256     case ISD::SETO:
2257       // Expand this to (OLT | OGE).
2258       TmpOp0 = Op0;
2259       TmpOp1 = Op1;
2260       Opc = ISD::OR;
2261       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2262       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2263       break;
2264     }
2265   } else {
2266     // Integer comparisons.
2267     switch (SetCCOpcode) {
2268     default: llvm_unreachable("Illegal integer comparison"); break;
2269     case ISD::SETNE:  Invert = true;
2270     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2271     case ISD::SETLT:  Swap = true;
2272     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2273     case ISD::SETLE:  Swap = true;
2274     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2275     case ISD::SETULT: Swap = true;
2276     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2277     case ISD::SETULE: Swap = true;
2278     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2279     }
2280
2281     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2282     if (Opc == ARMISD::VCEQ) {
2283
2284       SDValue AndOp;
2285       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2286         AndOp = Op0;
2287       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2288         AndOp = Op1;
2289
2290       // Ignore bitconvert.
2291       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2292         AndOp = AndOp.getOperand(0);
2293
2294       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2295         Opc = ARMISD::VTST;
2296         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2297         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2298         Invert = !Invert;
2299       }
2300     }
2301   }
2302
2303   if (Swap)
2304     std::swap(Op0, Op1);
2305
2306   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2307
2308   if (Invert)
2309     Result = DAG.getNOT(dl, Result, VT);
2310
2311   return Result;
2312 }
2313
2314 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2315 /// VMOV instruction, and if so, return the constant being splatted.
2316 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2317                            unsigned SplatBitSize, SelectionDAG &DAG) {
2318   switch (SplatBitSize) {
2319   case 8:
2320     // Any 1-byte value is OK.
2321     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2322     return DAG.getTargetConstant(SplatBits, MVT::i8);
2323
2324   case 16:
2325     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2326     if ((SplatBits & ~0xff) == 0 ||
2327         (SplatBits & ~0xff00) == 0)
2328       return DAG.getTargetConstant(SplatBits, MVT::i16);
2329     break;
2330
2331   case 32:
2332     // NEON's 32-bit VMOV supports splat values where:
2333     // * only one byte is nonzero, or
2334     // * the least significant byte is 0xff and the second byte is nonzero, or
2335     // * the least significant 2 bytes are 0xff and the third is nonzero.
2336     if ((SplatBits & ~0xff) == 0 ||
2337         (SplatBits & ~0xff00) == 0 ||
2338         (SplatBits & ~0xff0000) == 0 ||
2339         (SplatBits & ~0xff000000) == 0)
2340       return DAG.getTargetConstant(SplatBits, MVT::i32);
2341
2342     if ((SplatBits & ~0xffff) == 0 &&
2343         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2344       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2345
2346     if ((SplatBits & ~0xffffff) == 0 &&
2347         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2348       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2349
2350     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2351     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2352     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2353     // and fall through here to test for a valid 64-bit splat.  But, then the
2354     // caller would also need to check and handle the change in size.
2355     break;
2356
2357   case 64: {
2358     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2359     uint64_t BitMask = 0xff;
2360     uint64_t Val = 0;
2361     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2362       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2363         Val |= BitMask;
2364       else if ((SplatBits & BitMask) != 0)
2365         return SDValue();
2366       BitMask <<= 8;
2367     }
2368     return DAG.getTargetConstant(Val, MVT::i64);
2369   }
2370
2371   default:
2372     llvm_unreachable("unexpected size for isVMOVSplat");
2373     break;
2374   }
2375
2376   return SDValue();
2377 }
2378
2379 /// getVMOVImm - If this is a build_vector of constants which can be
2380 /// formed by using a VMOV instruction of the specified element size,
2381 /// return the constant being splatted.  The ByteSize field indicates the
2382 /// number of bytes of each element [1248].
2383 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2384   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2385   APInt SplatBits, SplatUndef;
2386   unsigned SplatBitSize;
2387   bool HasAnyUndefs;
2388   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2389                                       HasAnyUndefs, ByteSize * 8))
2390     return SDValue();
2391
2392   if (SplatBitSize > ByteSize * 8)
2393     return SDValue();
2394
2395   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2396                      SplatBitSize, DAG);
2397 }
2398
2399 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
2400                        bool &ReverseVEXT, unsigned &Imm) {
2401   unsigned NumElts = VT.getVectorNumElements();
2402   ReverseVEXT = false;
2403   Imm = M[0];
2404
2405   // If this is a VEXT shuffle, the immediate value is the index of the first
2406   // element.  The other shuffle indices must be the successive elements after
2407   // the first one.
2408   unsigned ExpectedElt = Imm;
2409   for (unsigned i = 1; i < NumElts; ++i) {
2410     // Increment the expected index.  If it wraps around, it may still be
2411     // a VEXT but the source vectors must be swapped.
2412     ExpectedElt += 1;
2413     if (ExpectedElt == NumElts * 2) {
2414       ExpectedElt = 0;
2415       ReverseVEXT = true;
2416     }
2417
2418     if (ExpectedElt != static_cast<unsigned>(M[i]))
2419       return false;
2420   }
2421
2422   // Adjust the index value if the source operands will be swapped.
2423   if (ReverseVEXT)
2424     Imm -= NumElts;
2425
2426   return true;
2427 }
2428
2429 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2430 /// instruction with the specified blocksize.  (The order of the elements
2431 /// within each block of the vector is reversed.)
2432 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
2433                        unsigned BlockSize) {
2434   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2435          "Only possible block sizes for VREV are: 16, 32, 64");
2436
2437   unsigned NumElts = VT.getVectorNumElements();
2438   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2439   unsigned BlockElts = M[0] + 1;
2440
2441   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2442     return false;
2443
2444   for (unsigned i = 0; i < NumElts; ++i) {
2445     if ((unsigned) M[i] !=
2446         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2447       return false;
2448   }
2449
2450   return true;
2451 }
2452
2453 static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
2454                        unsigned &WhichResult) {
2455   unsigned NumElts = VT.getVectorNumElements();
2456   WhichResult = (M[0] == 0 ? 0 : 1);
2457   for (unsigned i = 0; i < NumElts; i += 2) {
2458     if ((unsigned) M[i] != i + WhichResult ||
2459         (unsigned) M[i+1] != i + NumElts + WhichResult)
2460       return false;
2461   }
2462   return true;
2463 }
2464
2465 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
2466                        unsigned &WhichResult) {
2467   unsigned NumElts = VT.getVectorNumElements();
2468   WhichResult = (M[0] == 0 ? 0 : 1);
2469   for (unsigned i = 0; i != NumElts; ++i) {
2470     if ((unsigned) M[i] != 2 * i + WhichResult)
2471       return false;
2472   }
2473
2474   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2475   if (VT.is64BitVector() && VT.getVectorElementType().getSizeInBits() == 32)
2476     return false;
2477
2478   return true;
2479 }
2480
2481 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
2482                        unsigned &WhichResult) {
2483   unsigned NumElts = VT.getVectorNumElements();
2484   WhichResult = (M[0] == 0 ? 0 : 1);
2485   unsigned Idx = WhichResult * NumElts / 2;
2486   for (unsigned i = 0; i != NumElts; i += 2) {
2487     if ((unsigned) M[i] != Idx ||
2488         (unsigned) M[i+1] != Idx + NumElts)
2489       return false;
2490     Idx += 1;
2491   }
2492
2493   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2494   if (VT.is64BitVector() && VT.getVectorElementType().getSizeInBits() == 32)
2495     return false;
2496
2497   return true;
2498 }
2499
2500 static SDValue BuildSplat(SDValue Val, EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2501   // Canonicalize all-zeros and all-ones vectors.
2502   ConstantSDNode *ConstVal = cast<ConstantSDNode>(Val.getNode());
2503   if (ConstVal->isNullValue())
2504     return getZeroVector(VT, DAG, dl);
2505   if (ConstVal->isAllOnesValue())
2506     return getOnesVector(VT, DAG, dl);
2507
2508   EVT CanonicalVT;
2509   if (VT.is64BitVector()) {
2510     switch (Val.getValueType().getSizeInBits()) {
2511     case 8:  CanonicalVT = MVT::v8i8; break;
2512     case 16: CanonicalVT = MVT::v4i16; break;
2513     case 32: CanonicalVT = MVT::v2i32; break;
2514     case 64: CanonicalVT = MVT::v1i64; break;
2515     default: llvm_unreachable("unexpected splat element type"); break;
2516     }
2517   } else {
2518     assert(VT.is128BitVector() && "unknown splat vector size");
2519     switch (Val.getValueType().getSizeInBits()) {
2520     case 8:  CanonicalVT = MVT::v16i8; break;
2521     case 16: CanonicalVT = MVT::v8i16; break;
2522     case 32: CanonicalVT = MVT::v4i32; break;
2523     case 64: CanonicalVT = MVT::v2i64; break;
2524     default: llvm_unreachable("unexpected splat element type"); break;
2525     }
2526   }
2527
2528   // Build a canonical splat for this value.
2529   SmallVector<SDValue, 8> Ops;
2530   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2531   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2532                             Ops.size());
2533   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2534 }
2535
2536 // If this is a case we can't handle, return null and let the default
2537 // expansion code take care of it.
2538 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2539   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
2540   DebugLoc dl = Op.getDebugLoc();
2541   EVT VT = Op.getValueType();
2542
2543   APInt SplatBits, SplatUndef;
2544   unsigned SplatBitSize;
2545   bool HasAnyUndefs;
2546   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2547     if (SplatBitSize <= 64) {
2548       SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2549                                 SplatUndef.getZExtValue(), SplatBitSize, DAG);
2550       if (Val.getNode())
2551         return BuildSplat(Val, VT, DAG, dl);
2552     }
2553   }
2554
2555   // If there are only 2 elements in a 128-bit vector, insert them into an
2556   // undef vector.  This handles the common case for 128-bit vector argument
2557   // passing, where the insertions should be translated to subreg accesses
2558   // with no real instructions.
2559   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2560     SDValue Val = DAG.getUNDEF(VT);
2561     SDValue Op0 = Op.getOperand(0);
2562     SDValue Op1 = Op.getOperand(1);
2563     if (Op0.getOpcode() != ISD::UNDEF)
2564       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2565                         DAG.getIntPtrConstant(0));
2566     if (Op1.getOpcode() != ISD::UNDEF)
2567       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2568                         DAG.getIntPtrConstant(1));
2569     return Val;
2570   }
2571
2572   return SDValue();
2573 }
2574
2575 /// isShuffleMaskLegal - Targets can use this to indicate that they only
2576 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
2577 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
2578 /// are assumed to be legal.
2579 bool
2580 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
2581                                       EVT VT) const {
2582   if (VT.getVectorNumElements() == 4 &&
2583       (VT.is128BitVector() || VT.is64BitVector())) {
2584     unsigned PFIndexes[4];
2585     for (unsigned i = 0; i != 4; ++i) {
2586       if (M[i] < 0)
2587         PFIndexes[i] = 8;
2588       else
2589         PFIndexes[i] = M[i];
2590     }
2591
2592     // Compute the index in the perfect shuffle table.
2593     unsigned PFTableIndex =
2594       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2595     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2596     unsigned Cost = (PFEntry >> 30);
2597
2598     if (Cost <= 4)
2599       return true;
2600   }
2601
2602   bool ReverseVEXT;
2603   unsigned Imm, WhichResult;
2604
2605   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
2606           isVREVMask(M, VT, 64) ||
2607           isVREVMask(M, VT, 32) ||
2608           isVREVMask(M, VT, 16) ||
2609           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
2610           isVTRNMask(M, VT, WhichResult) ||
2611           isVUZPMask(M, VT, WhichResult) ||
2612           isVZIPMask(M, VT, WhichResult));
2613 }
2614
2615 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
2616 /// the specified operations to build the shuffle.
2617 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
2618                                       SDValue RHS, SelectionDAG &DAG,
2619                                       DebugLoc dl) {
2620   unsigned OpNum = (PFEntry >> 26) & 0x0F;
2621   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
2622   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
2623
2624   enum {
2625     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
2626     OP_VREV,
2627     OP_VDUP0,
2628     OP_VDUP1,
2629     OP_VDUP2,
2630     OP_VDUP3,
2631     OP_VEXT1,
2632     OP_VEXT2,
2633     OP_VEXT3,
2634     OP_VUZPL, // VUZP, left result
2635     OP_VUZPR, // VUZP, right result
2636     OP_VZIPL, // VZIP, left result
2637     OP_VZIPR, // VZIP, right result
2638     OP_VTRNL, // VTRN, left result
2639     OP_VTRNR  // VTRN, right result
2640   };
2641
2642   if (OpNum == OP_COPY) {
2643     if (LHSID == (1*9+2)*9+3) return LHS;
2644     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
2645     return RHS;
2646   }
2647
2648   SDValue OpLHS, OpRHS;
2649   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
2650   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
2651   EVT VT = OpLHS.getValueType();
2652
2653   switch (OpNum) {
2654   default: llvm_unreachable("Unknown shuffle opcode!");
2655   case OP_VREV:
2656     return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
2657   case OP_VDUP0:
2658   case OP_VDUP1:
2659   case OP_VDUP2:
2660   case OP_VDUP3:
2661     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
2662                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
2663   case OP_VEXT1:
2664   case OP_VEXT2:
2665   case OP_VEXT3:
2666     return DAG.getNode(ARMISD::VEXT, dl, VT,
2667                        OpLHS, OpRHS,
2668                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
2669   case OP_VUZPL:
2670   case OP_VUZPR:
2671     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
2672                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
2673   case OP_VZIPL:
2674   case OP_VZIPR:
2675     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
2676                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
2677   case OP_VTRNL:
2678   case OP_VTRNR:
2679     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
2680                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
2681   }
2682 }
2683
2684 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2685   SDValue V1 = Op.getOperand(0);
2686   SDValue V2 = Op.getOperand(1);
2687   DebugLoc dl = Op.getDebugLoc();
2688   EVT VT = Op.getValueType();
2689   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2690   SmallVector<int, 8> ShuffleMask;
2691
2692   // Convert shuffles that are directly supported on NEON to target-specific
2693   // DAG nodes, instead of keeping them as shuffles and matching them again
2694   // during code selection.  This is more efficient and avoids the possibility
2695   // of inconsistencies between legalization and selection.
2696   // FIXME: floating-point vectors should be canonicalized to integer vectors
2697   // of the same time so that they get CSEd properly.
2698   SVN->getMask(ShuffleMask);
2699
2700   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
2701     int Lane = SVN->getSplatIndex();
2702     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
2703       return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
2704     }
2705     return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
2706                        DAG.getConstant(Lane, MVT::i32));
2707   }
2708
2709   bool ReverseVEXT;
2710   unsigned Imm;
2711   if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
2712     if (ReverseVEXT)
2713       std::swap(V1, V2);
2714     return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
2715                        DAG.getConstant(Imm, MVT::i32));
2716   }
2717
2718   if (isVREVMask(ShuffleMask, VT, 64))
2719     return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
2720   if (isVREVMask(ShuffleMask, VT, 32))
2721     return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
2722   if (isVREVMask(ShuffleMask, VT, 16))
2723     return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
2724
2725   // Check for Neon shuffles that modify both input vectors in place.
2726   // If both results are used, i.e., if there are two shuffles with the same
2727   // source operands and with masks corresponding to both results of one of
2728   // these operations, DAG memoization will ensure that a single node is
2729   // used for both shuffles.
2730   unsigned WhichResult;
2731   if (isVTRNMask(ShuffleMask, VT, WhichResult))
2732     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
2733                        V1, V2).getValue(WhichResult);
2734   if (isVUZPMask(ShuffleMask, VT, WhichResult))
2735     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
2736                        V1, V2).getValue(WhichResult);
2737   if (isVZIPMask(ShuffleMask, VT, WhichResult))
2738     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
2739                        V1, V2).getValue(WhichResult);
2740
2741   // If the shuffle is not directly supported and it has 4 elements, use
2742   // the PerfectShuffle-generated table to synthesize it from other shuffles.
2743   if (VT.getVectorNumElements() == 4 &&
2744       (VT.is128BitVector() || VT.is64BitVector())) {
2745     unsigned PFIndexes[4];
2746     for (unsigned i = 0; i != 4; ++i) {
2747       if (ShuffleMask[i] < 0)
2748         PFIndexes[i] = 8;
2749       else
2750         PFIndexes[i] = ShuffleMask[i];
2751     }
2752
2753     // Compute the index in the perfect shuffle table.
2754     unsigned PFTableIndex =
2755       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2756
2757     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2758     unsigned Cost = (PFEntry >> 30);
2759
2760     if (Cost <= 4)
2761       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
2762   }
2763
2764   return SDValue();
2765 }
2766
2767 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2768   EVT VT = Op.getValueType();
2769   DebugLoc dl = Op.getDebugLoc();
2770   SDValue Vec = Op.getOperand(0);
2771   SDValue Lane = Op.getOperand(1);
2772
2773   // FIXME: This is invalid for 8 and 16-bit elements - the information about
2774   // sign / zero extension is lost!
2775   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2776   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2777
2778   if (VT.bitsLT(MVT::i32))
2779     Op = DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2780   else if (VT.bitsGT(MVT::i32))
2781     Op = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op);
2782
2783   return Op;
2784 }
2785
2786 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2787   // The only time a CONCAT_VECTORS operation can have legal types is when
2788   // two 64-bit vectors are concatenated to a 128-bit vector.
2789   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
2790          "unexpected CONCAT_VECTORS");
2791   DebugLoc dl = Op.getDebugLoc();
2792   SDValue Val = DAG.getUNDEF(MVT::v2f64);
2793   SDValue Op0 = Op.getOperand(0);
2794   SDValue Op1 = Op.getOperand(1);
2795   if (Op0.getOpcode() != ISD::UNDEF)
2796     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2797                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
2798                       DAG.getIntPtrConstant(0));
2799   if (Op1.getOpcode() != ISD::UNDEF)
2800     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2801                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
2802                       DAG.getIntPtrConstant(1));
2803   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
2804 }
2805
2806 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2807   switch (Op.getOpcode()) {
2808   default: llvm_unreachable("Don't know how to custom lower this!");
2809   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2810   case ISD::GlobalAddress:
2811     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2812       LowerGlobalAddressELF(Op, DAG);
2813   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2814   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2815   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2816   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2817   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
2818   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2819   case ISD::SINT_TO_FP:
2820   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2821   case ISD::FP_TO_SINT:
2822   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2823   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2824   case ISD::RETURNADDR:    break;
2825   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2826   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2827   case ISD::INTRINSIC_VOID:
2828   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2829   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2830   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2831   case ISD::SHL:
2832   case ISD::SRL:
2833   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2834   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2835   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2836   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2837   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2838   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
2839   }
2840   return SDValue();
2841 }
2842
2843 /// ReplaceNodeResults - Replace the results of node with an illegal result
2844 /// type with new values built out of custom code.
2845 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2846                                            SmallVectorImpl<SDValue>&Results,
2847                                            SelectionDAG &DAG) {
2848   switch (N->getOpcode()) {
2849   default:
2850     llvm_unreachable("Don't know how to custom expand this!");
2851     return;
2852   case ISD::BIT_CONVERT:
2853     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2854     return;
2855   case ISD::SRL:
2856   case ISD::SRA: {
2857     SDValue Res = LowerShift(N, DAG, Subtarget);
2858     if (Res.getNode())
2859       Results.push_back(Res);
2860     return;
2861   }
2862   }
2863 }
2864
2865 //===----------------------------------------------------------------------===//
2866 //                           ARM Scheduler Hooks
2867 //===----------------------------------------------------------------------===//
2868
2869 MachineBasicBlock *
2870 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2871                                                MachineBasicBlock *BB) const {
2872   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2873   DebugLoc dl = MI->getDebugLoc();
2874   switch (MI->getOpcode()) {
2875   default:
2876     llvm_unreachable("Unexpected instr type to insert");
2877   case ARM::tMOVCCr_pseudo: {
2878     // To "insert" a SELECT_CC instruction, we actually have to insert the
2879     // diamond control-flow pattern.  The incoming instruction knows the
2880     // destination vreg to set, the condition code register to branch on, the
2881     // true/false values to select between, and a branch opcode to use.
2882     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2883     MachineFunction::iterator It = BB;
2884     ++It;
2885
2886     //  thisMBB:
2887     //  ...
2888     //   TrueVal = ...
2889     //   cmpTY ccX, r1, r2
2890     //   bCC copy1MBB
2891     //   fallthrough --> copy0MBB
2892     MachineBasicBlock *thisMBB  = BB;
2893     MachineFunction *F = BB->getParent();
2894     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2895     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2896     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2897       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2898     F->insert(It, copy0MBB);
2899     F->insert(It, sinkMBB);
2900     // Update machine-CFG edges by first adding all successors of the current
2901     // block to the new block which will contain the Phi node for the select.
2902     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2903         e = BB->succ_end(); i != e; ++i)
2904       sinkMBB->addSuccessor(*i);
2905     // Next, remove all successors of the current block, and add the true
2906     // and fallthrough blocks as its successors.
2907     while(!BB->succ_empty())
2908       BB->removeSuccessor(BB->succ_begin());
2909     BB->addSuccessor(copy0MBB);
2910     BB->addSuccessor(sinkMBB);
2911
2912     //  copy0MBB:
2913     //   %FalseValue = ...
2914     //   # fallthrough to sinkMBB
2915     BB = copy0MBB;
2916
2917     // Update machine-CFG edges
2918     BB->addSuccessor(sinkMBB);
2919
2920     //  sinkMBB:
2921     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2922     //  ...
2923     BB = sinkMBB;
2924     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2925       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2926       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2927
2928     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2929     return BB;
2930   }
2931
2932   case ARM::tANDsp:
2933   case ARM::tADDspr_:
2934   case ARM::tSUBspi_:
2935   case ARM::t2SUBrSPi_:
2936   case ARM::t2SUBrSPi12_:
2937   case ARM::t2SUBrSPs_: {
2938     MachineFunction *MF = BB->getParent();
2939     unsigned DstReg = MI->getOperand(0).getReg();
2940     unsigned SrcReg = MI->getOperand(1).getReg();
2941     bool DstIsDead = MI->getOperand(0).isDead();
2942     bool SrcIsKill = MI->getOperand(1).isKill();
2943
2944     if (SrcReg != ARM::SP) {
2945       // Copy the source to SP from virtual register.
2946       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(SrcReg);
2947       unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2948         ? ARM::tMOVtgpr2gpr : ARM::tMOVgpr2gpr;
2949       BuildMI(BB, dl, TII->get(CopyOpc), ARM::SP)
2950         .addReg(SrcReg, getKillRegState(SrcIsKill));
2951     }
2952
2953     unsigned OpOpc = 0;
2954     bool NeedPred = false, NeedCC = false, NeedOp3 = false;
2955     switch (MI->getOpcode()) {
2956     default:
2957       llvm_unreachable("Unexpected pseudo instruction!");
2958     case ARM::tANDsp:
2959       OpOpc = ARM::tAND;
2960       NeedPred = true;
2961       break;
2962     case ARM::tADDspr_:
2963       OpOpc = ARM::tADDspr;
2964       break;
2965     case ARM::tSUBspi_:
2966       OpOpc = ARM::tSUBspi;
2967       break;
2968     case ARM::t2SUBrSPi_:
2969       OpOpc = ARM::t2SUBrSPi;
2970       NeedPred = true; NeedCC = true;
2971       break;
2972     case ARM::t2SUBrSPi12_:
2973       OpOpc = ARM::t2SUBrSPi12;
2974       NeedPred = true;
2975       break;
2976     case ARM::t2SUBrSPs_:
2977       OpOpc = ARM::t2SUBrSPs;
2978       NeedPred = true; NeedCC = true; NeedOp3 = true;
2979       break;
2980     }
2981     MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(OpOpc), ARM::SP);
2982     if (OpOpc == ARM::tAND)
2983       AddDefaultT1CC(MIB);
2984     MIB.addReg(ARM::SP);
2985     MIB.addOperand(MI->getOperand(2));
2986     if (NeedOp3)
2987       MIB.addOperand(MI->getOperand(3));
2988     if (NeedPred)
2989       AddDefaultPred(MIB);
2990     if (NeedCC)
2991       AddDefaultCC(MIB);
2992
2993     // Copy the result from SP to virtual register.
2994     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(DstReg);
2995     unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2996       ? ARM::tMOVgpr2tgpr : ARM::tMOVgpr2gpr;
2997     BuildMI(BB, dl, TII->get(CopyOpc))
2998       .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstIsDead))
2999       .addReg(ARM::SP);
3000     MF->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
3001     return BB;
3002   }
3003   }
3004 }
3005
3006 //===----------------------------------------------------------------------===//
3007 //                           ARM Optimization Hooks
3008 //===----------------------------------------------------------------------===//
3009
3010 static
3011 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
3012                             TargetLowering::DAGCombinerInfo &DCI) {
3013   SelectionDAG &DAG = DCI.DAG;
3014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3015   EVT VT = N->getValueType(0);
3016   unsigned Opc = N->getOpcode();
3017   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
3018   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
3019   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
3020   ISD::CondCode CC = ISD::SETCC_INVALID;
3021
3022   if (isSlctCC) {
3023     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
3024   } else {
3025     SDValue CCOp = Slct.getOperand(0);
3026     if (CCOp.getOpcode() == ISD::SETCC)
3027       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
3028   }
3029
3030   bool DoXform = false;
3031   bool InvCC = false;
3032   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
3033           "Bad input!");
3034
3035   if (LHS.getOpcode() == ISD::Constant &&
3036       cast<ConstantSDNode>(LHS)->isNullValue()) {
3037     DoXform = true;
3038   } else if (CC != ISD::SETCC_INVALID &&
3039              RHS.getOpcode() == ISD::Constant &&
3040              cast<ConstantSDNode>(RHS)->isNullValue()) {
3041     std::swap(LHS, RHS);
3042     SDValue Op0 = Slct.getOperand(0);
3043     EVT OpVT = isSlctCC ? Op0.getValueType() :
3044                           Op0.getOperand(0).getValueType();
3045     bool isInt = OpVT.isInteger();
3046     CC = ISD::getSetCCInverse(CC, isInt);
3047
3048     if (!TLI.isCondCodeLegal(CC, OpVT))
3049       return SDValue();         // Inverse operator isn't legal.
3050
3051     DoXform = true;
3052     InvCC = true;
3053   }
3054
3055   if (DoXform) {
3056     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
3057     if (isSlctCC)
3058       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
3059                              Slct.getOperand(0), Slct.getOperand(1), CC);
3060     SDValue CCOp = Slct.getOperand(0);
3061     if (InvCC)
3062       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
3063                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
3064     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3065                        CCOp, OtherOp, Result);
3066   }
3067   return SDValue();
3068 }
3069
3070 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
3071 static SDValue PerformADDCombine(SDNode *N,
3072                                  TargetLowering::DAGCombinerInfo &DCI) {
3073   // added by evan in r37685 with no testcase.
3074   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3075
3076   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
3077   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
3078     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
3079     if (Result.getNode()) return Result;
3080   }
3081   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
3082     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
3083     if (Result.getNode()) return Result;
3084   }
3085
3086   return SDValue();
3087 }
3088
3089 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
3090 static SDValue PerformSUBCombine(SDNode *N,
3091                                  TargetLowering::DAGCombinerInfo &DCI) {
3092   // added by evan in r37685 with no testcase.
3093   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3094
3095   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
3096   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
3097     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
3098     if (Result.getNode()) return Result;
3099   }
3100
3101   return SDValue();
3102 }
3103
3104
3105 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
3106 static SDValue PerformFMRRDCombine(SDNode *N,
3107                                    TargetLowering::DAGCombinerInfo &DCI) {
3108   // fmrrd(fmdrr x, y) -> x,y
3109   SDValue InDouble = N->getOperand(0);
3110   if (InDouble.getOpcode() == ARMISD::FMDRR)
3111     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
3112   return SDValue();
3113 }
3114
3115 /// getVShiftImm - Check if this is a valid build_vector for the immediate
3116 /// operand of a vector shift operation, where all the elements of the
3117 /// build_vector must have the same constant integer value.
3118 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3119   // Ignore bit_converts.
3120   while (Op.getOpcode() == ISD::BIT_CONVERT)
3121     Op = Op.getOperand(0);
3122   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3123   APInt SplatBits, SplatUndef;
3124   unsigned SplatBitSize;
3125   bool HasAnyUndefs;
3126   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3127                                       HasAnyUndefs, ElementBits) ||
3128       SplatBitSize > ElementBits)
3129     return false;
3130   Cnt = SplatBits.getSExtValue();
3131   return true;
3132 }
3133
3134 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
3135 /// operand of a vector shift left operation.  That value must be in the range:
3136 ///   0 <= Value < ElementBits for a left shift; or
3137 ///   0 <= Value <= ElementBits for a long left shift.
3138 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
3139   assert(VT.isVector() && "vector shift count is not a vector type");
3140   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3141   if (! getVShiftImm(Op, ElementBits, Cnt))
3142     return false;
3143   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
3144 }
3145
3146 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
3147 /// operand of a vector shift right operation.  For a shift opcode, the value
3148 /// is positive, but for an intrinsic the value count must be negative. The
3149 /// absolute value must be in the range:
3150 ///   1 <= |Value| <= ElementBits for a right shift; or
3151 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
3152 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
3153                          int64_t &Cnt) {
3154   assert(VT.isVector() && "vector shift count is not a vector type");
3155   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3156   if (! getVShiftImm(Op, ElementBits, Cnt))
3157     return false;
3158   if (isIntrinsic)
3159     Cnt = -Cnt;
3160   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
3161 }
3162
3163 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
3164 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3165   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3166   switch (IntNo) {
3167   default:
3168     // Don't do anything for most intrinsics.
3169     break;
3170
3171   // Vector shifts: check for immediate versions and lower them.
3172   // Note: This is done during DAG combining instead of DAG legalizing because
3173   // the build_vectors for 64-bit vector element shift counts are generally
3174   // not legal, and it is hard to see their values after they get legalized to
3175   // loads from a constant pool.
3176   case Intrinsic::arm_neon_vshifts:
3177   case Intrinsic::arm_neon_vshiftu:
3178   case Intrinsic::arm_neon_vshiftls:
3179   case Intrinsic::arm_neon_vshiftlu:
3180   case Intrinsic::arm_neon_vshiftn:
3181   case Intrinsic::arm_neon_vrshifts:
3182   case Intrinsic::arm_neon_vrshiftu:
3183   case Intrinsic::arm_neon_vrshiftn:
3184   case Intrinsic::arm_neon_vqshifts:
3185   case Intrinsic::arm_neon_vqshiftu:
3186   case Intrinsic::arm_neon_vqshiftsu:
3187   case Intrinsic::arm_neon_vqshiftns:
3188   case Intrinsic::arm_neon_vqshiftnu:
3189   case Intrinsic::arm_neon_vqshiftnsu:
3190   case Intrinsic::arm_neon_vqrshiftns:
3191   case Intrinsic::arm_neon_vqrshiftnu:
3192   case Intrinsic::arm_neon_vqrshiftnsu: {
3193     EVT VT = N->getOperand(1).getValueType();
3194     int64_t Cnt;
3195     unsigned VShiftOpc = 0;
3196
3197     switch (IntNo) {
3198     case Intrinsic::arm_neon_vshifts:
3199     case Intrinsic::arm_neon_vshiftu:
3200       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
3201         VShiftOpc = ARMISD::VSHL;
3202         break;
3203       }
3204       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
3205         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
3206                      ARMISD::VSHRs : ARMISD::VSHRu);
3207         break;
3208       }
3209       return SDValue();
3210
3211     case Intrinsic::arm_neon_vshiftls:
3212     case Intrinsic::arm_neon_vshiftlu:
3213       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
3214         break;
3215       llvm_unreachable("invalid shift count for vshll intrinsic");
3216
3217     case Intrinsic::arm_neon_vrshifts:
3218     case Intrinsic::arm_neon_vrshiftu:
3219       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
3220         break;
3221       return SDValue();
3222
3223     case Intrinsic::arm_neon_vqshifts:
3224     case Intrinsic::arm_neon_vqshiftu:
3225       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3226         break;
3227       return SDValue();
3228
3229     case Intrinsic::arm_neon_vqshiftsu:
3230       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3231         break;
3232       llvm_unreachable("invalid shift count for vqshlu intrinsic");
3233
3234     case Intrinsic::arm_neon_vshiftn:
3235     case Intrinsic::arm_neon_vrshiftn:
3236     case Intrinsic::arm_neon_vqshiftns:
3237     case Intrinsic::arm_neon_vqshiftnu:
3238     case Intrinsic::arm_neon_vqshiftnsu:
3239     case Intrinsic::arm_neon_vqrshiftns:
3240     case Intrinsic::arm_neon_vqrshiftnu:
3241     case Intrinsic::arm_neon_vqrshiftnsu:
3242       // Narrowing shifts require an immediate right shift.
3243       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
3244         break;
3245       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
3246
3247     default:
3248       llvm_unreachable("unhandled vector shift");
3249     }
3250
3251     switch (IntNo) {
3252     case Intrinsic::arm_neon_vshifts:
3253     case Intrinsic::arm_neon_vshiftu:
3254       // Opcode already set above.
3255       break;
3256     case Intrinsic::arm_neon_vshiftls:
3257     case Intrinsic::arm_neon_vshiftlu:
3258       if (Cnt == VT.getVectorElementType().getSizeInBits())
3259         VShiftOpc = ARMISD::VSHLLi;
3260       else
3261         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
3262                      ARMISD::VSHLLs : ARMISD::VSHLLu);
3263       break;
3264     case Intrinsic::arm_neon_vshiftn:
3265       VShiftOpc = ARMISD::VSHRN; break;
3266     case Intrinsic::arm_neon_vrshifts:
3267       VShiftOpc = ARMISD::VRSHRs; break;
3268     case Intrinsic::arm_neon_vrshiftu:
3269       VShiftOpc = ARMISD::VRSHRu; break;
3270     case Intrinsic::arm_neon_vrshiftn:
3271       VShiftOpc = ARMISD::VRSHRN; break;
3272     case Intrinsic::arm_neon_vqshifts:
3273       VShiftOpc = ARMISD::VQSHLs; break;
3274     case Intrinsic::arm_neon_vqshiftu:
3275       VShiftOpc = ARMISD::VQSHLu; break;
3276     case Intrinsic::arm_neon_vqshiftsu:
3277       VShiftOpc = ARMISD::VQSHLsu; break;
3278     case Intrinsic::arm_neon_vqshiftns:
3279       VShiftOpc = ARMISD::VQSHRNs; break;
3280     case Intrinsic::arm_neon_vqshiftnu:
3281       VShiftOpc = ARMISD::VQSHRNu; break;
3282     case Intrinsic::arm_neon_vqshiftnsu:
3283       VShiftOpc = ARMISD::VQSHRNsu; break;
3284     case Intrinsic::arm_neon_vqrshiftns:
3285       VShiftOpc = ARMISD::VQRSHRNs; break;
3286     case Intrinsic::arm_neon_vqrshiftnu:
3287       VShiftOpc = ARMISD::VQRSHRNu; break;
3288     case Intrinsic::arm_neon_vqrshiftnsu:
3289       VShiftOpc = ARMISD::VQRSHRNsu; break;
3290     }
3291
3292     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3293                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3294   }
3295
3296   case Intrinsic::arm_neon_vshiftins: {
3297     EVT VT = N->getOperand(1).getValueType();
3298     int64_t Cnt;
3299     unsigned VShiftOpc = 0;
3300
3301     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
3302       VShiftOpc = ARMISD::VSLI;
3303     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
3304       VShiftOpc = ARMISD::VSRI;
3305     else {
3306       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
3307     }
3308
3309     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3310                        N->getOperand(1), N->getOperand(2),
3311                        DAG.getConstant(Cnt, MVT::i32));
3312   }
3313
3314   case Intrinsic::arm_neon_vqrshifts:
3315   case Intrinsic::arm_neon_vqrshiftu:
3316     // No immediate versions of these to check for.
3317     break;
3318   }
3319
3320   return SDValue();
3321 }
3322
3323 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
3324 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
3325 /// combining instead of DAG legalizing because the build_vectors for 64-bit
3326 /// vector element shift counts are generally not legal, and it is hard to see
3327 /// their values after they get legalized to loads from a constant pool.
3328 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
3329                                    const ARMSubtarget *ST) {
3330   EVT VT = N->getValueType(0);
3331
3332   // Nothing to be done for scalar shifts.
3333   if (! VT.isVector())
3334     return SDValue();
3335
3336   assert(ST->hasNEON() && "unexpected vector shift");
3337   int64_t Cnt;
3338
3339   switch (N->getOpcode()) {
3340   default: llvm_unreachable("unexpected shift opcode");
3341
3342   case ISD::SHL:
3343     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
3344       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
3345                          DAG.getConstant(Cnt, MVT::i32));
3346     break;
3347
3348   case ISD::SRA:
3349   case ISD::SRL:
3350     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
3351       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
3352                             ARMISD::VSHRs : ARMISD::VSHRu);
3353       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
3354                          DAG.getConstant(Cnt, MVT::i32));
3355     }
3356   }
3357   return SDValue();
3358 }
3359
3360 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
3361 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
3362 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
3363                                     const ARMSubtarget *ST) {
3364   SDValue N0 = N->getOperand(0);
3365
3366   // Check for sign- and zero-extensions of vector extract operations of 8-
3367   // and 16-bit vector elements.  NEON supports these directly.  They are
3368   // handled during DAG combining because type legalization will promote them
3369   // to 32-bit types and it is messy to recognize the operations after that.
3370   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3371     SDValue Vec = N0.getOperand(0);
3372     SDValue Lane = N0.getOperand(1);
3373     EVT VT = N->getValueType(0);
3374     EVT EltVT = N0.getValueType();
3375     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3376
3377     if (VT == MVT::i32 &&
3378         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
3379         TLI.isTypeLegal(Vec.getValueType())) {
3380
3381       unsigned Opc = 0;
3382       switch (N->getOpcode()) {
3383       default: llvm_unreachable("unexpected opcode");
3384       case ISD::SIGN_EXTEND:
3385         Opc = ARMISD::VGETLANEs;
3386         break;
3387       case ISD::ZERO_EXTEND:
3388       case ISD::ANY_EXTEND:
3389         Opc = ARMISD::VGETLANEu;
3390         break;
3391       }
3392       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
3393     }
3394   }
3395
3396   return SDValue();
3397 }
3398
3399 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
3400                                              DAGCombinerInfo &DCI) const {
3401   switch (N->getOpcode()) {
3402   default: break;
3403   case ISD::ADD:      return PerformADDCombine(N, DCI);
3404   case ISD::SUB:      return PerformSUBCombine(N, DCI);
3405   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
3406   case ISD::INTRINSIC_WO_CHAIN:
3407     return PerformIntrinsicCombine(N, DCI.DAG);
3408   case ISD::SHL:
3409   case ISD::SRA:
3410   case ISD::SRL:
3411     return PerformShiftCombine(N, DCI.DAG, Subtarget);
3412   case ISD::SIGN_EXTEND:
3413   case ISD::ZERO_EXTEND:
3414   case ISD::ANY_EXTEND:
3415     return PerformExtendCombine(N, DCI.DAG, Subtarget);
3416   }
3417   return SDValue();
3418 }
3419
3420 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
3421   if (!Subtarget->hasV6Ops())
3422     // Pre-v6 does not support unaligned mem access.
3423     return false;
3424   else if (!Subtarget->hasV6Ops()) {
3425     // v6 may or may not support unaligned mem access.
3426     if (!Subtarget->isTargetDarwin())
3427       return false;
3428   }
3429
3430   switch (VT.getSimpleVT().SimpleTy) {
3431   default:
3432     return false;
3433   case MVT::i8:
3434   case MVT::i16:
3435   case MVT::i32:
3436     return true;
3437   // FIXME: VLD1 etc with standard alignment is legal.
3438   }
3439 }
3440
3441 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
3442   if (V < 0)
3443     return false;
3444
3445   unsigned Scale = 1;
3446   switch (VT.getSimpleVT().SimpleTy) {
3447   default: return false;
3448   case MVT::i1:
3449   case MVT::i8:
3450     // Scale == 1;
3451     break;
3452   case MVT::i16:
3453     // Scale == 2;
3454     Scale = 2;
3455     break;
3456   case MVT::i32:
3457     // Scale == 4;
3458     Scale = 4;
3459     break;
3460   }
3461
3462   if ((V & (Scale - 1)) != 0)
3463     return false;
3464   V /= Scale;
3465   return V == (V & ((1LL << 5) - 1));
3466 }
3467
3468 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
3469                                       const ARMSubtarget *Subtarget) {
3470   bool isNeg = false;
3471   if (V < 0) {
3472     isNeg = true;
3473     V = - V;
3474   }
3475
3476   switch (VT.getSimpleVT().SimpleTy) {
3477   default: return false;
3478   case MVT::i1:
3479   case MVT::i8:
3480   case MVT::i16:
3481   case MVT::i32:
3482     // + imm12 or - imm8
3483     if (isNeg)
3484       return V == (V & ((1LL << 8) - 1));
3485     return V == (V & ((1LL << 12) - 1));
3486   case MVT::f32:
3487   case MVT::f64:
3488     // Same as ARM mode. FIXME: NEON?
3489     if (!Subtarget->hasVFP2())
3490       return false;
3491     if ((V & 3) != 0)
3492       return false;
3493     V >>= 2;
3494     return V == (V & ((1LL << 8) - 1));
3495   }
3496 }
3497
3498 /// isLegalAddressImmediate - Return true if the integer value can be used
3499 /// as the offset of the target addressing mode for load / store of the
3500 /// given type.
3501 static bool isLegalAddressImmediate(int64_t V, EVT VT,
3502                                     const ARMSubtarget *Subtarget) {
3503   if (V == 0)
3504     return true;
3505
3506   if (!VT.isSimple())
3507     return false;
3508
3509   if (Subtarget->isThumb1Only())
3510     return isLegalT1AddressImmediate(V, VT);
3511   else if (Subtarget->isThumb2())
3512     return isLegalT2AddressImmediate(V, VT, Subtarget);
3513
3514   // ARM mode.
3515   if (V < 0)
3516     V = - V;
3517   switch (VT.getSimpleVT().SimpleTy) {
3518   default: return false;
3519   case MVT::i1:
3520   case MVT::i8:
3521   case MVT::i32:
3522     // +- imm12
3523     return V == (V & ((1LL << 12) - 1));
3524   case MVT::i16:
3525     // +- imm8
3526     return V == (V & ((1LL << 8) - 1));
3527   case MVT::f32:
3528   case MVT::f64:
3529     if (!Subtarget->hasVFP2()) // FIXME: NEON?
3530       return false;
3531     if ((V & 3) != 0)
3532       return false;
3533     V >>= 2;
3534     return V == (V & ((1LL << 8) - 1));
3535   }
3536 }
3537
3538 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
3539                                                       EVT VT) const {
3540   int Scale = AM.Scale;
3541   if (Scale < 0)
3542     return false;
3543
3544   switch (VT.getSimpleVT().SimpleTy) {
3545   default: return false;
3546   case MVT::i1:
3547   case MVT::i8:
3548   case MVT::i16:
3549   case MVT::i32:
3550     if (Scale == 1)
3551       return true;
3552     // r + r << imm
3553     Scale = Scale & ~1;
3554     return Scale == 2 || Scale == 4 || Scale == 8;
3555   case MVT::i64:
3556     // r + r
3557     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3558       return true;
3559     return false;
3560   case MVT::isVoid:
3561     // Note, we allow "void" uses (basically, uses that aren't loads or
3562     // stores), because arm allows folding a scale into many arithmetic
3563     // operations.  This should be made more precise and revisited later.
3564
3565     // Allow r << imm, but the imm has to be a multiple of two.
3566     if (Scale & 1) return false;
3567     return isPowerOf2_32(Scale);
3568   }
3569 }
3570
3571 /// isLegalAddressingMode - Return true if the addressing mode represented
3572 /// by AM is legal for this target, for a load/store of the specified type.
3573 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3574                                               const Type *Ty) const {
3575   EVT VT = getValueType(Ty, true);
3576   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
3577     return false;
3578
3579   // Can never fold addr of global into load/store.
3580   if (AM.BaseGV)
3581     return false;
3582
3583   switch (AM.Scale) {
3584   case 0:  // no scale reg, must be "r+i" or "r", or "i".
3585     break;
3586   case 1:
3587     if (Subtarget->isThumb1Only())
3588       return false;
3589     // FALL THROUGH.
3590   default:
3591     // ARM doesn't support any R+R*scale+imm addr modes.
3592     if (AM.BaseOffs)
3593       return false;
3594
3595     if (!VT.isSimple())
3596       return false;
3597
3598     if (Subtarget->isThumb2())
3599       return isLegalT2ScaledAddressingMode(AM, VT);
3600
3601     int Scale = AM.Scale;
3602     switch (VT.getSimpleVT().SimpleTy) {
3603     default: return false;
3604     case MVT::i1:
3605     case MVT::i8:
3606     case MVT::i32:
3607       if (Scale < 0) Scale = -Scale;
3608       if (Scale == 1)
3609         return true;
3610       // r + r << imm
3611       return isPowerOf2_32(Scale & ~1);
3612     case MVT::i16:
3613     case MVT::i64:
3614       // r + r
3615       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3616         return true;
3617       return false;
3618
3619     case MVT::isVoid:
3620       // Note, we allow "void" uses (basically, uses that aren't loads or
3621       // stores), because arm allows folding a scale into many arithmetic
3622       // operations.  This should be made more precise and revisited later.
3623
3624       // Allow r << imm, but the imm has to be a multiple of two.
3625       if (Scale & 1) return false;
3626       return isPowerOf2_32(Scale);
3627     }
3628     break;
3629   }
3630   return true;
3631 }
3632
3633 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
3634                                       bool isSEXTLoad, SDValue &Base,
3635                                       SDValue &Offset, bool &isInc,
3636                                       SelectionDAG &DAG) {
3637   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3638     return false;
3639
3640   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
3641     // AddressingMode 3
3642     Base = Ptr->getOperand(0);
3643     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3644       int RHSC = (int)RHS->getZExtValue();
3645       if (RHSC < 0 && RHSC > -256) {
3646         assert(Ptr->getOpcode() == ISD::ADD);
3647         isInc = false;
3648         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3649         return true;
3650       }
3651     }
3652     isInc = (Ptr->getOpcode() == ISD::ADD);
3653     Offset = Ptr->getOperand(1);
3654     return true;
3655   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
3656     // AddressingMode 2
3657     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3658       int RHSC = (int)RHS->getZExtValue();
3659       if (RHSC < 0 && RHSC > -0x1000) {
3660         assert(Ptr->getOpcode() == ISD::ADD);
3661         isInc = false;
3662         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3663         Base = Ptr->getOperand(0);
3664         return true;
3665       }
3666     }
3667
3668     if (Ptr->getOpcode() == ISD::ADD) {
3669       isInc = true;
3670       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
3671       if (ShOpcVal != ARM_AM::no_shift) {
3672         Base = Ptr->getOperand(1);
3673         Offset = Ptr->getOperand(0);
3674       } else {
3675         Base = Ptr->getOperand(0);
3676         Offset = Ptr->getOperand(1);
3677       }
3678       return true;
3679     }
3680
3681     isInc = (Ptr->getOpcode() == ISD::ADD);
3682     Base = Ptr->getOperand(0);
3683     Offset = Ptr->getOperand(1);
3684     return true;
3685   }
3686
3687   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
3688   return false;
3689 }
3690
3691 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
3692                                      bool isSEXTLoad, SDValue &Base,
3693                                      SDValue &Offset, bool &isInc,
3694                                      SelectionDAG &DAG) {
3695   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3696     return false;
3697
3698   Base = Ptr->getOperand(0);
3699   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3700     int RHSC = (int)RHS->getZExtValue();
3701     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
3702       assert(Ptr->getOpcode() == ISD::ADD);
3703       isInc = false;
3704       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3705       return true;
3706     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3707       isInc = Ptr->getOpcode() == ISD::ADD;
3708       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3709       return true;
3710     }
3711   }
3712
3713   return false;
3714 }
3715
3716 /// getPreIndexedAddressParts - returns true by value, base pointer and
3717 /// offset pointer and addressing mode by reference if the node's address
3718 /// can be legally represented as pre-indexed load / store address.
3719 bool
3720 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3721                                              SDValue &Offset,
3722                                              ISD::MemIndexedMode &AM,
3723                                              SelectionDAG &DAG) const {
3724   if (Subtarget->isThumb1Only())
3725     return false;
3726
3727   EVT VT;
3728   SDValue Ptr;
3729   bool isSEXTLoad = false;
3730   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3731     Ptr = LD->getBasePtr();
3732     VT  = LD->getMemoryVT();
3733     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3734   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3735     Ptr = ST->getBasePtr();
3736     VT  = ST->getMemoryVT();
3737   } else
3738     return false;
3739
3740   bool isInc;
3741   bool isLegal = false;
3742   if (Subtarget->isThumb2())
3743     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3744                                        Offset, isInc, DAG);
3745   else
3746     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3747                                         Offset, isInc, DAG);
3748   if (!isLegal)
3749     return false;
3750
3751   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3752   return true;
3753 }
3754
3755 /// getPostIndexedAddressParts - returns true by value, base pointer and
3756 /// offset pointer and addressing mode by reference if this node can be
3757 /// combined with a load / store to form a post-indexed load / store.
3758 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3759                                                    SDValue &Base,
3760                                                    SDValue &Offset,
3761                                                    ISD::MemIndexedMode &AM,
3762                                                    SelectionDAG &DAG) const {
3763   if (Subtarget->isThumb1Only())
3764     return false;
3765
3766   EVT VT;
3767   SDValue Ptr;
3768   bool isSEXTLoad = false;
3769   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3770     VT  = LD->getMemoryVT();
3771     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3772   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3773     VT  = ST->getMemoryVT();
3774   } else
3775     return false;
3776
3777   bool isInc;
3778   bool isLegal = false;
3779   if (Subtarget->isThumb2())
3780     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3781                                         isInc, DAG);
3782   else
3783     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3784                                         isInc, DAG);
3785   if (!isLegal)
3786     return false;
3787
3788   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3789   return true;
3790 }
3791
3792 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3793                                                        const APInt &Mask,
3794                                                        APInt &KnownZero,
3795                                                        APInt &KnownOne,
3796                                                        const SelectionDAG &DAG,
3797                                                        unsigned Depth) const {
3798   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3799   switch (Op.getOpcode()) {
3800   default: break;
3801   case ARMISD::CMOV: {
3802     // Bits are known zero/one if known on the LHS and RHS.
3803     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3804     if (KnownZero == 0 && KnownOne == 0) return;
3805
3806     APInt KnownZeroRHS, KnownOneRHS;
3807     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3808                           KnownZeroRHS, KnownOneRHS, Depth+1);
3809     KnownZero &= KnownZeroRHS;
3810     KnownOne  &= KnownOneRHS;
3811     return;
3812   }
3813   }
3814 }
3815
3816 //===----------------------------------------------------------------------===//
3817 //                           ARM Inline Assembly Support
3818 //===----------------------------------------------------------------------===//
3819
3820 /// getConstraintType - Given a constraint letter, return the type of
3821 /// constraint it is for this target.
3822 ARMTargetLowering::ConstraintType
3823 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3824   if (Constraint.size() == 1) {
3825     switch (Constraint[0]) {
3826     default:  break;
3827     case 'l': return C_RegisterClass;
3828     case 'w': return C_RegisterClass;
3829     }
3830   }
3831   return TargetLowering::getConstraintType(Constraint);
3832 }
3833
3834 std::pair<unsigned, const TargetRegisterClass*>
3835 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3836                                                 EVT VT) const {
3837   if (Constraint.size() == 1) {
3838     // GCC RS6000 Constraint Letters
3839     switch (Constraint[0]) {
3840     case 'l':
3841       if (Subtarget->isThumb1Only())
3842         return std::make_pair(0U, ARM::tGPRRegisterClass);
3843       else
3844         return std::make_pair(0U, ARM::GPRRegisterClass);
3845     case 'r':
3846       return std::make_pair(0U, ARM::GPRRegisterClass);
3847     case 'w':
3848       if (VT == MVT::f32)
3849         return std::make_pair(0U, ARM::SPRRegisterClass);
3850       if (VT == MVT::f64)
3851         return std::make_pair(0U, ARM::DPRRegisterClass);
3852       break;
3853     }
3854   }
3855   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3856 }
3857
3858 std::vector<unsigned> ARMTargetLowering::
3859 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3860                                   EVT VT) const {
3861   if (Constraint.size() != 1)
3862     return std::vector<unsigned>();
3863
3864   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3865   default: break;
3866   case 'l':
3867     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3868                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3869                                  0);
3870   case 'r':
3871     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3872                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3873                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3874                                  ARM::R12, ARM::LR, 0);
3875   case 'w':
3876     if (VT == MVT::f32)
3877       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3878                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3879                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3880                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3881                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3882                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3883                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3884                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3885     if (VT == MVT::f64)
3886       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3887                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3888                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3889                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3890       break;
3891   }
3892
3893   return std::vector<unsigned>();
3894 }
3895
3896 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3897 /// vector.  If it is invalid, don't add anything to Ops.
3898 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3899                                                      char Constraint,
3900                                                      bool hasMemory,
3901                                                      std::vector<SDValue>&Ops,
3902                                                      SelectionDAG &DAG) const {
3903   SDValue Result(0, 0);
3904
3905   switch (Constraint) {
3906   default: break;
3907   case 'I': case 'J': case 'K': case 'L':
3908   case 'M': case 'N': case 'O':
3909     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3910     if (!C)
3911       return;
3912
3913     int64_t CVal64 = C->getSExtValue();
3914     int CVal = (int) CVal64;
3915     // None of these constraints allow values larger than 32 bits.  Check
3916     // that the value fits in an int.
3917     if (CVal != CVal64)
3918       return;
3919
3920     switch (Constraint) {
3921       case 'I':
3922         if (Subtarget->isThumb1Only()) {
3923           // This must be a constant between 0 and 255, for ADD
3924           // immediates.
3925           if (CVal >= 0 && CVal <= 255)
3926             break;
3927         } else if (Subtarget->isThumb2()) {
3928           // A constant that can be used as an immediate value in a
3929           // data-processing instruction.
3930           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3931             break;
3932         } else {
3933           // A constant that can be used as an immediate value in a
3934           // data-processing instruction.
3935           if (ARM_AM::getSOImmVal(CVal) != -1)
3936             break;
3937         }
3938         return;
3939
3940       case 'J':
3941         if (Subtarget->isThumb()) {  // FIXME thumb2
3942           // This must be a constant between -255 and -1, for negated ADD
3943           // immediates. This can be used in GCC with an "n" modifier that
3944           // prints the negated value, for use with SUB instructions. It is
3945           // not useful otherwise but is implemented for compatibility.
3946           if (CVal >= -255 && CVal <= -1)
3947             break;
3948         } else {
3949           // This must be a constant between -4095 and 4095. It is not clear
3950           // what this constraint is intended for. Implemented for
3951           // compatibility with GCC.
3952           if (CVal >= -4095 && CVal <= 4095)
3953             break;
3954         }
3955         return;
3956
3957       case 'K':
3958         if (Subtarget->isThumb1Only()) {
3959           // A 32-bit value where only one byte has a nonzero value. Exclude
3960           // zero to match GCC. This constraint is used by GCC internally for
3961           // constants that can be loaded with a move/shift combination.
3962           // It is not useful otherwise but is implemented for compatibility.
3963           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3964             break;
3965         } else if (Subtarget->isThumb2()) {
3966           // A constant whose bitwise inverse can be used as an immediate
3967           // value in a data-processing instruction. This can be used in GCC
3968           // with a "B" modifier that prints the inverted value, for use with
3969           // BIC and MVN instructions. It is not useful otherwise but is
3970           // implemented for compatibility.
3971           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3972             break;
3973         } else {
3974           // A constant whose bitwise inverse can be used as an immediate
3975           // value in a data-processing instruction. This can be used in GCC
3976           // with a "B" modifier that prints the inverted value, for use with
3977           // BIC and MVN instructions. It is not useful otherwise but is
3978           // implemented for compatibility.
3979           if (ARM_AM::getSOImmVal(~CVal) != -1)
3980             break;
3981         }
3982         return;
3983
3984       case 'L':
3985         if (Subtarget->isThumb1Only()) {
3986           // This must be a constant between -7 and 7,
3987           // for 3-operand ADD/SUB immediate instructions.
3988           if (CVal >= -7 && CVal < 7)
3989             break;
3990         } else if (Subtarget->isThumb2()) {
3991           // A constant whose negation can be used as an immediate value in a
3992           // data-processing instruction. This can be used in GCC with an "n"
3993           // modifier that prints the negated value, for use with SUB
3994           // instructions. It is not useful otherwise but is implemented for
3995           // compatibility.
3996           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
3997             break;
3998         } else {
3999           // A constant whose negation can be used as an immediate value in a
4000           // data-processing instruction. This can be used in GCC with an "n"
4001           // modifier that prints the negated value, for use with SUB
4002           // instructions. It is not useful otherwise but is implemented for
4003           // compatibility.
4004           if (ARM_AM::getSOImmVal(-CVal) != -1)
4005             break;
4006         }
4007         return;
4008
4009       case 'M':
4010         if (Subtarget->isThumb()) { // FIXME thumb2
4011           // This must be a multiple of 4 between 0 and 1020, for
4012           // ADD sp + immediate.
4013           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
4014             break;
4015         } else {
4016           // A power of two or a constant between 0 and 32.  This is used in
4017           // GCC for the shift amount on shifted register operands, but it is
4018           // useful in general for any shift amounts.
4019           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
4020             break;
4021         }
4022         return;
4023
4024       case 'N':
4025         if (Subtarget->isThumb()) {  // FIXME thumb2
4026           // This must be a constant between 0 and 31, for shift amounts.
4027           if (CVal >= 0 && CVal <= 31)
4028             break;
4029         }
4030         return;
4031
4032       case 'O':
4033         if (Subtarget->isThumb()) {  // FIXME thumb2
4034           // This must be a multiple of 4 between -508 and 508, for
4035           // ADD/SUB sp = sp + immediate.
4036           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
4037             break;
4038         }
4039         return;
4040     }
4041     Result = DAG.getTargetConstant(CVal, Op.getValueType());
4042     break;
4043   }
4044
4045   if (Result.getNode()) {
4046     Ops.push_back(Result);
4047     return;
4048   }
4049   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
4050                                                       Ops, DAG);
4051 }