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