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