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