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