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