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