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