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