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