Handle a v2f64 formal parameter that is split between registers and memory
[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     MachineFrameInfo *MFI = MF.getFrameInfo();
1617     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true, false);
1618
1619     // Create load node to retrieve arguments from the stack.
1620     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1621     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
1622                             PseudoSourceValue::getFixedStack(FI), 0,
1623                             false, false, 0);
1624   } else {
1625     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1626     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1627   }
1628
1629   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
1630 }
1631
1632 SDValue
1633 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1634                                         CallingConv::ID CallConv, bool isVarArg,
1635                                         const SmallVectorImpl<ISD::InputArg>
1636                                           &Ins,
1637                                         DebugLoc dl, SelectionDAG &DAG,
1638                                         SmallVectorImpl<SDValue> &InVals) {
1639
1640   MachineFunction &MF = DAG.getMachineFunction();
1641   MachineFrameInfo *MFI = MF.getFrameInfo();
1642
1643   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1644
1645   // Assign locations to all of the incoming arguments.
1646   SmallVector<CCValAssign, 16> ArgLocs;
1647   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1648                  *DAG.getContext());
1649   CCInfo.AnalyzeFormalArguments(Ins,
1650                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1651                                                   isVarArg));
1652
1653   SmallVector<SDValue, 16> ArgValues;
1654
1655   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1656     CCValAssign &VA = ArgLocs[i];
1657
1658     // Arguments stored in registers.
1659     if (VA.isRegLoc()) {
1660       EVT RegVT = VA.getLocVT();
1661
1662       SDValue ArgValue;
1663       if (VA.needsCustom()) {
1664         // f64 and vector types are split up into multiple registers or
1665         // combinations of registers and stack slots.
1666         if (VA.getLocVT() == MVT::v2f64) {
1667           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1668                                                    Chain, DAG, dl);
1669           VA = ArgLocs[++i]; // skip ahead to next loc
1670           SDValue ArgValue2;
1671           if (VA.isMemLoc()) {
1672             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(),
1673                                             true, false);
1674             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1675             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
1676                                     PseudoSourceValue::getFixedStack(FI), 0,
1677                                     false, false, 0);
1678           } else {
1679             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1680                                              Chain, DAG, dl);
1681           }
1682           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1683           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1684                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1685           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1686                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1687         } else
1688           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
1689
1690       } else {
1691         TargetRegisterClass *RC;
1692
1693         if (RegVT == MVT::f32)
1694           RC = ARM::SPRRegisterClass;
1695         else if (RegVT == MVT::f64)
1696           RC = ARM::DPRRegisterClass;
1697         else if (RegVT == MVT::v2f64)
1698           RC = ARM::QPRRegisterClass;
1699         else if (RegVT == MVT::i32)
1700           RC = (AFI->isThumb1OnlyFunction() ?
1701                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
1702         else
1703           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1704
1705         // Transform the arguments in physical registers into virtual ones.
1706         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1707         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1708       }
1709
1710       // If this is an 8 or 16-bit value, it is really passed promoted
1711       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1712       // truncate to the right size.
1713       switch (VA.getLocInfo()) {
1714       default: llvm_unreachable("Unknown loc info!");
1715       case CCValAssign::Full: break;
1716       case CCValAssign::BCvt:
1717         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1718         break;
1719       case CCValAssign::SExt:
1720         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1721                                DAG.getValueType(VA.getValVT()));
1722         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1723         break;
1724       case CCValAssign::ZExt:
1725         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1726                                DAG.getValueType(VA.getValVT()));
1727         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1728         break;
1729       }
1730
1731       InVals.push_back(ArgValue);
1732
1733     } else { // VA.isRegLoc()
1734
1735       // sanity check
1736       assert(VA.isMemLoc());
1737       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1738
1739       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1740       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1741                                       true, false);
1742
1743       // Create load nodes to retrieve arguments from the stack.
1744       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1745       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1746                                    PseudoSourceValue::getFixedStack(FI), 0,
1747                                    false, false, 0));
1748     }
1749   }
1750
1751   // varargs
1752   if (isVarArg) {
1753     static const unsigned GPRArgRegs[] = {
1754       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1755     };
1756
1757     unsigned NumGPRs = CCInfo.getFirstUnallocated
1758       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1759
1760     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1761     unsigned VARegSize = (4 - NumGPRs) * 4;
1762     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1763     unsigned ArgOffset = CCInfo.getNextStackOffset();
1764     if (VARegSaveSize) {
1765       // If this function is vararg, store any remaining integer argument regs
1766       // to their spots on the stack so that they may be loaded by deferencing
1767       // the result of va_next.
1768       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1769       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1770                                                  VARegSaveSize - VARegSize,
1771                                                  true, false);
1772       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1773
1774       SmallVector<SDValue, 4> MemOps;
1775       for (; NumGPRs < 4; ++NumGPRs) {
1776         TargetRegisterClass *RC;
1777         if (AFI->isThumb1OnlyFunction())
1778           RC = ARM::tGPRRegisterClass;
1779         else
1780           RC = ARM::GPRRegisterClass;
1781
1782         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1783         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1784         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1785                                      PseudoSourceValue::getFixedStack(VarArgsFrameIndex), 0,
1786                                      false, false, 0);
1787         MemOps.push_back(Store);
1788         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1789                           DAG.getConstant(4, getPointerTy()));
1790       }
1791       if (!MemOps.empty())
1792         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1793                             &MemOps[0], MemOps.size());
1794     } else
1795       // This will point to the next argument passed via stack.
1796       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset, true, false);
1797   }
1798
1799   return Chain;
1800 }
1801
1802 /// isFloatingPointZero - Return true if this is +0.0.
1803 static bool isFloatingPointZero(SDValue Op) {
1804   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1805     return CFP->getValueAPF().isPosZero();
1806   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1807     // Maybe this has already been legalized into the constant pool?
1808     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1809       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1810       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1811         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1812           return CFP->getValueAPF().isPosZero();
1813     }
1814   }
1815   return false;
1816 }
1817
1818 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1819 /// the given operands.
1820 SDValue
1821 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1822                              SDValue &ARMCC, SelectionDAG &DAG, DebugLoc dl) {
1823   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1824     unsigned C = RHSC->getZExtValue();
1825     if (!isLegalICmpImmediate(C)) {
1826       // Constant does not fit, try adjusting it by one?
1827       switch (CC) {
1828       default: break;
1829       case ISD::SETLT:
1830       case ISD::SETGE:
1831         if (isLegalICmpImmediate(C-1)) {
1832           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1833           RHS = DAG.getConstant(C-1, MVT::i32);
1834         }
1835         break;
1836       case ISD::SETULT:
1837       case ISD::SETUGE:
1838         if (C > 0 && isLegalICmpImmediate(C-1)) {
1839           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1840           RHS = DAG.getConstant(C-1, MVT::i32);
1841         }
1842         break;
1843       case ISD::SETLE:
1844       case ISD::SETGT:
1845         if (isLegalICmpImmediate(C+1)) {
1846           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1847           RHS = DAG.getConstant(C+1, MVT::i32);
1848         }
1849         break;
1850       case ISD::SETULE:
1851       case ISD::SETUGT:
1852         if (C < 0xffffffff && isLegalICmpImmediate(C+1)) {
1853           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1854           RHS = DAG.getConstant(C+1, MVT::i32);
1855         }
1856         break;
1857       }
1858     }
1859   }
1860
1861   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1862   ARMISD::NodeType CompareType;
1863   switch (CondCode) {
1864   default:
1865     CompareType = ARMISD::CMP;
1866     break;
1867   case ARMCC::EQ:
1868   case ARMCC::NE:
1869     // Uses only Z Flag
1870     CompareType = ARMISD::CMPZ;
1871     break;
1872   }
1873   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1874   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1875 }
1876
1877 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1878 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1879                          DebugLoc dl) {
1880   SDValue Cmp;
1881   if (!isFloatingPointZero(RHS))
1882     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1883   else
1884     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1885   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1886 }
1887
1888 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1889   EVT VT = Op.getValueType();
1890   SDValue LHS = Op.getOperand(0);
1891   SDValue RHS = Op.getOperand(1);
1892   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1893   SDValue TrueVal = Op.getOperand(2);
1894   SDValue FalseVal = Op.getOperand(3);
1895   DebugLoc dl = Op.getDebugLoc();
1896
1897   if (LHS.getValueType() == MVT::i32) {
1898     SDValue ARMCC;
1899     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1900     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, dl);
1901     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1902   }
1903
1904   ARMCC::CondCodes CondCode, CondCode2;
1905   FPCCToARMCC(CC, CondCode, CondCode2);
1906
1907   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1908   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1909   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1910   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1911                                  ARMCC, CCR, Cmp);
1912   if (CondCode2 != ARMCC::AL) {
1913     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1914     // FIXME: Needs another CMP because flag can have but one use.
1915     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1916     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1917                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1918   }
1919   return Result;
1920 }
1921
1922 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1923   SDValue  Chain = Op.getOperand(0);
1924   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1925   SDValue    LHS = Op.getOperand(2);
1926   SDValue    RHS = Op.getOperand(3);
1927   SDValue   Dest = Op.getOperand(4);
1928   DebugLoc dl = Op.getDebugLoc();
1929
1930   if (LHS.getValueType() == MVT::i32) {
1931     SDValue ARMCC;
1932     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1933     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, dl);
1934     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1935                        Chain, Dest, ARMCC, CCR,Cmp);
1936   }
1937
1938   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1939   ARMCC::CondCodes CondCode, CondCode2;
1940   FPCCToARMCC(CC, CondCode, CondCode2);
1941
1942   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1943   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1944   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1945   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1946   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1947   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1948   if (CondCode2 != ARMCC::AL) {
1949     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1950     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1951     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1952   }
1953   return Res;
1954 }
1955
1956 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1957   SDValue Chain = Op.getOperand(0);
1958   SDValue Table = Op.getOperand(1);
1959   SDValue Index = Op.getOperand(2);
1960   DebugLoc dl = Op.getDebugLoc();
1961
1962   EVT PTy = getPointerTy();
1963   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1964   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1965   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1966   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1967   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1968   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1969   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1970   if (Subtarget->isThumb2()) {
1971     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1972     // which does another jump to the destination. This also makes it easier
1973     // to translate it to TBB / TBH later.
1974     // FIXME: This might not work if the function is extremely large.
1975     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1976                        Addr, Op.getOperand(2), JTI, UId);
1977   }
1978   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1979     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
1980                        PseudoSourceValue::getJumpTable(), 0,
1981                        false, false, 0);
1982     Chain = Addr.getValue(1);
1983     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1984     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1985   } else {
1986     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
1987                        PseudoSourceValue::getJumpTable(), 0, false, false, 0);
1988     Chain = Addr.getValue(1);
1989     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1990   }
1991 }
1992
1993 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1994   DebugLoc dl = Op.getDebugLoc();
1995   unsigned Opc;
1996
1997   switch (Op.getOpcode()) {
1998   default:
1999     assert(0 && "Invalid opcode!");
2000   case ISD::FP_TO_SINT:
2001     Opc = ARMISD::FTOSI;
2002     break;
2003   case ISD::FP_TO_UINT:
2004     Opc = ARMISD::FTOUI;
2005     break;
2006   }
2007   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
2008   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
2009 }
2010
2011 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2012   EVT VT = Op.getValueType();
2013   DebugLoc dl = Op.getDebugLoc();
2014   unsigned Opc;
2015
2016   switch (Op.getOpcode()) {
2017   default:
2018     assert(0 && "Invalid opcode!");
2019   case ISD::SINT_TO_FP:
2020     Opc = ARMISD::SITOF;
2021     break;
2022   case ISD::UINT_TO_FP:
2023     Opc = ARMISD::UITOF;
2024     break;
2025   }
2026
2027   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
2028   return DAG.getNode(Opc, dl, VT, Op);
2029 }
2030
2031 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
2032   // Implement fcopysign with a fabs and a conditional fneg.
2033   SDValue Tmp0 = Op.getOperand(0);
2034   SDValue Tmp1 = Op.getOperand(1);
2035   DebugLoc dl = Op.getDebugLoc();
2036   EVT VT = Op.getValueType();
2037   EVT SrcVT = Tmp1.getValueType();
2038   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
2039   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
2040   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
2041   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2042   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
2043 }
2044
2045 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
2046   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2047   MFI->setFrameAddressIsTaken(true);
2048   EVT VT = Op.getValueType();
2049   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
2050   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2051   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
2052     ? ARM::R7 : ARM::R11;
2053   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2054   while (Depth--)
2055     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
2056                             false, false, 0);
2057   return FrameAddr;
2058 }
2059
2060 SDValue
2061 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
2062                                            SDValue Chain,
2063                                            SDValue Dst, SDValue Src,
2064                                            SDValue Size, unsigned Align,
2065                                            bool isVolatile, bool AlwaysInline,
2066                                          const Value *DstSV, uint64_t DstSVOff,
2067                                          const Value *SrcSV, uint64_t SrcSVOff){
2068   // Do repeated 4-byte loads and stores. To be improved.
2069   // This requires 4-byte alignment.
2070   if ((Align & 3) != 0)
2071     return SDValue();
2072   // This requires the copy size to be a constant, preferrably
2073   // within a subtarget-specific limit.
2074   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2075   if (!ConstantSize)
2076     return SDValue();
2077   uint64_t SizeVal = ConstantSize->getZExtValue();
2078   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
2079     return SDValue();
2080
2081   unsigned BytesLeft = SizeVal & 3;
2082   unsigned NumMemOps = SizeVal >> 2;
2083   unsigned EmittedNumMemOps = 0;
2084   EVT VT = MVT::i32;
2085   unsigned VTSize = 4;
2086   unsigned i = 0;
2087   const unsigned MAX_LOADS_IN_LDM = 6;
2088   SDValue TFOps[MAX_LOADS_IN_LDM];
2089   SDValue Loads[MAX_LOADS_IN_LDM];
2090   uint64_t SrcOff = 0, DstOff = 0;
2091
2092   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
2093   // same number of stores.  The loads and stores will get combined into
2094   // ldm/stm later on.
2095   while (EmittedNumMemOps < NumMemOps) {
2096     for (i = 0;
2097          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
2098       Loads[i] = DAG.getLoad(VT, dl, Chain,
2099                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2100                                          DAG.getConstant(SrcOff, MVT::i32)),
2101                              SrcSV, SrcSVOff + SrcOff, isVolatile, false, 0);
2102       TFOps[i] = Loads[i].getValue(1);
2103       SrcOff += VTSize;
2104     }
2105     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2106
2107     for (i = 0;
2108          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
2109       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2110                               DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2111                                           DAG.getConstant(DstOff, MVT::i32)),
2112                               DstSV, DstSVOff + DstOff, isVolatile, false, 0);
2113       DstOff += VTSize;
2114     }
2115     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2116
2117     EmittedNumMemOps += i;
2118   }
2119
2120   if (BytesLeft == 0)
2121     return Chain;
2122
2123   // Issue loads / stores for the trailing (1 - 3) bytes.
2124   unsigned BytesLeftSave = BytesLeft;
2125   i = 0;
2126   while (BytesLeft) {
2127     if (BytesLeft >= 2) {
2128       VT = MVT::i16;
2129       VTSize = 2;
2130     } else {
2131       VT = MVT::i8;
2132       VTSize = 1;
2133     }
2134
2135     Loads[i] = DAG.getLoad(VT, dl, Chain,
2136                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2137                                        DAG.getConstant(SrcOff, MVT::i32)),
2138                            SrcSV, SrcSVOff + SrcOff, false, false, 0);
2139     TFOps[i] = Loads[i].getValue(1);
2140     ++i;
2141     SrcOff += VTSize;
2142     BytesLeft -= VTSize;
2143   }
2144   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2145
2146   i = 0;
2147   BytesLeft = BytesLeftSave;
2148   while (BytesLeft) {
2149     if (BytesLeft >= 2) {
2150       VT = MVT::i16;
2151       VTSize = 2;
2152     } else {
2153       VT = MVT::i8;
2154       VTSize = 1;
2155     }
2156
2157     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2158                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2159                                         DAG.getConstant(DstOff, MVT::i32)),
2160                             DstSV, DstSVOff + DstOff, false, false, 0);
2161     ++i;
2162     DstOff += VTSize;
2163     BytesLeft -= VTSize;
2164   }
2165   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2166 }
2167
2168 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
2169   SDValue Op = N->getOperand(0);
2170   DebugLoc dl = N->getDebugLoc();
2171   if (N->getValueType(0) == MVT::f64) {
2172     // Turn i64->f64 into VMOVDRR.
2173     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2174                              DAG.getConstant(0, MVT::i32));
2175     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2176                              DAG.getConstant(1, MVT::i32));
2177     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2178   }
2179
2180   // Turn f64->i64 into VMOVRRD.
2181   SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
2182                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
2183
2184   // Merge the pieces into a single i64 value.
2185   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
2186 }
2187
2188 /// getZeroVector - Returns a vector of specified type with all zero elements.
2189 ///
2190 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2191   assert(VT.isVector() && "Expected a vector type");
2192
2193   // Zero vectors are used to represent vector negation and in those cases
2194   // will be implemented with the NEON VNEG instruction.  However, VNEG does
2195   // not support i64 elements, so sometimes the zero vectors will need to be
2196   // explicitly constructed.  For those cases, and potentially other uses in
2197   // the future, always build zero vectors as <16 x i8> or <8 x i8> bitcasted
2198   // to their dest type.  This ensures they get CSE'd.
2199   SDValue Vec;
2200   SDValue Cst = DAG.getTargetConstant(0, MVT::i8);
2201   SmallVector<SDValue, 8> Ops;
2202   MVT TVT;
2203
2204   if (VT.getSizeInBits() == 64) {
2205     Ops.assign(8, Cst); TVT = MVT::v8i8;
2206   } else {
2207     Ops.assign(16, Cst); TVT = MVT::v16i8;
2208   }
2209   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2210
2211   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2212 }
2213
2214 /// getOnesVector - Returns a vector of specified type with all bits set.
2215 ///
2216 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2217   assert(VT.isVector() && "Expected a vector type");
2218
2219   // Always build ones vectors as <16 x i8> or <8 x i8> bitcasted to their
2220   // dest type. This ensures they get CSE'd.
2221   SDValue Vec;
2222   SDValue Cst = DAG.getTargetConstant(0xFF, MVT::i8);
2223   SmallVector<SDValue, 8> Ops;
2224   MVT TVT;
2225
2226   if (VT.getSizeInBits() == 64) {
2227     Ops.assign(8, Cst); TVT = MVT::v8i8;
2228   } else {
2229     Ops.assign(16, Cst); TVT = MVT::v16i8;
2230   }
2231   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2232
2233   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2234 }
2235
2236 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
2237 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
2238 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG) {
2239   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2240   EVT VT = Op.getValueType();
2241   unsigned VTBits = VT.getSizeInBits();
2242   DebugLoc dl = Op.getDebugLoc();
2243   SDValue ShOpLo = Op.getOperand(0);
2244   SDValue ShOpHi = Op.getOperand(1);
2245   SDValue ShAmt  = Op.getOperand(2);
2246   SDValue ARMCC;
2247   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
2248
2249   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
2250
2251   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2252                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
2253   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
2254   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2255                                    DAG.getConstant(VTBits, MVT::i32));
2256   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
2257   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2258   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
2259
2260   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2261   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
2262                           ARMCC, DAG, dl);
2263   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
2264   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC,
2265                            CCR, Cmp);
2266
2267   SDValue Ops[2] = { Lo, Hi };
2268   return DAG.getMergeValues(Ops, 2, dl);
2269 }
2270
2271 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
2272 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
2273 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) {
2274   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2275   EVT VT = Op.getValueType();
2276   unsigned VTBits = VT.getSizeInBits();
2277   DebugLoc dl = Op.getDebugLoc();
2278   SDValue ShOpLo = Op.getOperand(0);
2279   SDValue ShOpHi = Op.getOperand(1);
2280   SDValue ShAmt  = Op.getOperand(2);
2281   SDValue ARMCC;
2282
2283   assert(Op.getOpcode() == ISD::SHL_PARTS);
2284   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2285                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
2286   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
2287   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2288                                    DAG.getConstant(VTBits, MVT::i32));
2289   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
2290   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
2291
2292   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2293   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2294   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
2295                           ARMCC, DAG, dl);
2296   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
2297   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMCC,
2298                            CCR, Cmp);
2299
2300   SDValue Ops[2] = { Lo, Hi };
2301   return DAG.getMergeValues(Ops, 2, dl);
2302 }
2303
2304 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
2305                          const ARMSubtarget *ST) {
2306   EVT VT = N->getValueType(0);
2307   DebugLoc dl = N->getDebugLoc();
2308
2309   if (!ST->hasV6T2Ops())
2310     return SDValue();
2311
2312   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
2313   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
2314 }
2315
2316 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
2317                           const ARMSubtarget *ST) {
2318   EVT VT = N->getValueType(0);
2319   DebugLoc dl = N->getDebugLoc();
2320
2321   // Lower vector shifts on NEON to use VSHL.
2322   if (VT.isVector()) {
2323     assert(ST->hasNEON() && "unexpected vector shift");
2324
2325     // Left shifts translate directly to the vshiftu intrinsic.
2326     if (N->getOpcode() == ISD::SHL)
2327       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2328                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2329                          N->getOperand(0), N->getOperand(1));
2330
2331     assert((N->getOpcode() == ISD::SRA ||
2332             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2333
2334     // NEON uses the same intrinsics for both left and right shifts.  For
2335     // right shifts, the shift amounts are negative, so negate the vector of
2336     // shift amounts.
2337     EVT ShiftVT = N->getOperand(1).getValueType();
2338     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2339                                        getZeroVector(ShiftVT, DAG, dl),
2340                                        N->getOperand(1));
2341     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2342                                Intrinsic::arm_neon_vshifts :
2343                                Intrinsic::arm_neon_vshiftu);
2344     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2345                        DAG.getConstant(vshiftInt, MVT::i32),
2346                        N->getOperand(0), NegatedCount);
2347   }
2348
2349   // We can get here for a node like i32 = ISD::SHL i32, i64
2350   if (VT != MVT::i64)
2351     return SDValue();
2352
2353   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2354          "Unknown shift to lower!");
2355
2356   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2357   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2358       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2359     return SDValue();
2360
2361   // If we are in thumb mode, we don't have RRX.
2362   if (ST->isThumb1Only()) return SDValue();
2363
2364   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2365   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2366                              DAG.getConstant(0, MVT::i32));
2367   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2368                              DAG.getConstant(1, MVT::i32));
2369
2370   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2371   // captures the result into a carry flag.
2372   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2373   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2374
2375   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2376   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2377
2378   // Merge the pieces into a single i64 value.
2379  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2380 }
2381
2382 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2383   SDValue TmpOp0, TmpOp1;
2384   bool Invert = false;
2385   bool Swap = false;
2386   unsigned Opc = 0;
2387
2388   SDValue Op0 = Op.getOperand(0);
2389   SDValue Op1 = Op.getOperand(1);
2390   SDValue CC = Op.getOperand(2);
2391   EVT VT = Op.getValueType();
2392   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2393   DebugLoc dl = Op.getDebugLoc();
2394
2395   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2396     switch (SetCCOpcode) {
2397     default: llvm_unreachable("Illegal FP comparison"); break;
2398     case ISD::SETUNE:
2399     case ISD::SETNE:  Invert = true; // Fallthrough
2400     case ISD::SETOEQ:
2401     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2402     case ISD::SETOLT:
2403     case ISD::SETLT: Swap = true; // Fallthrough
2404     case ISD::SETOGT:
2405     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2406     case ISD::SETOLE:
2407     case ISD::SETLE:  Swap = true; // Fallthrough
2408     case ISD::SETOGE:
2409     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2410     case ISD::SETUGE: Swap = true; // Fallthrough
2411     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2412     case ISD::SETUGT: Swap = true; // Fallthrough
2413     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2414     case ISD::SETUEQ: Invert = true; // Fallthrough
2415     case ISD::SETONE:
2416       // Expand this to (OLT | OGT).
2417       TmpOp0 = Op0;
2418       TmpOp1 = Op1;
2419       Opc = ISD::OR;
2420       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2421       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2422       break;
2423     case ISD::SETUO: Invert = true; // Fallthrough
2424     case ISD::SETO:
2425       // Expand this to (OLT | OGE).
2426       TmpOp0 = Op0;
2427       TmpOp1 = Op1;
2428       Opc = ISD::OR;
2429       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2430       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2431       break;
2432     }
2433   } else {
2434     // Integer comparisons.
2435     switch (SetCCOpcode) {
2436     default: llvm_unreachable("Illegal integer comparison"); break;
2437     case ISD::SETNE:  Invert = true;
2438     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2439     case ISD::SETLT:  Swap = true;
2440     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2441     case ISD::SETLE:  Swap = true;
2442     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2443     case ISD::SETULT: Swap = true;
2444     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2445     case ISD::SETULE: Swap = true;
2446     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2447     }
2448
2449     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2450     if (Opc == ARMISD::VCEQ) {
2451
2452       SDValue AndOp;
2453       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2454         AndOp = Op0;
2455       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2456         AndOp = Op1;
2457
2458       // Ignore bitconvert.
2459       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2460         AndOp = AndOp.getOperand(0);
2461
2462       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2463         Opc = ARMISD::VTST;
2464         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2465         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2466         Invert = !Invert;
2467       }
2468     }
2469   }
2470
2471   if (Swap)
2472     std::swap(Op0, Op1);
2473
2474   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2475
2476   if (Invert)
2477     Result = DAG.getNOT(dl, Result, VT);
2478
2479   return Result;
2480 }
2481
2482 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2483 /// VMOV instruction, and if so, return the constant being splatted.
2484 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2485                            unsigned SplatBitSize, SelectionDAG &DAG) {
2486   switch (SplatBitSize) {
2487   case 8:
2488     // Any 1-byte value is OK.
2489     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2490     return DAG.getTargetConstant(SplatBits, MVT::i8);
2491
2492   case 16:
2493     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2494     if ((SplatBits & ~0xff) == 0 ||
2495         (SplatBits & ~0xff00) == 0)
2496       return DAG.getTargetConstant(SplatBits, MVT::i16);
2497     break;
2498
2499   case 32:
2500     // NEON's 32-bit VMOV supports splat values where:
2501     // * only one byte is nonzero, or
2502     // * the least significant byte is 0xff and the second byte is nonzero, or
2503     // * the least significant 2 bytes are 0xff and the third is nonzero.
2504     if ((SplatBits & ~0xff) == 0 ||
2505         (SplatBits & ~0xff00) == 0 ||
2506         (SplatBits & ~0xff0000) == 0 ||
2507         (SplatBits & ~0xff000000) == 0)
2508       return DAG.getTargetConstant(SplatBits, MVT::i32);
2509
2510     if ((SplatBits & ~0xffff) == 0 &&
2511         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2512       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2513
2514     if ((SplatBits & ~0xffffff) == 0 &&
2515         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2516       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2517
2518     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2519     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2520     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2521     // and fall through here to test for a valid 64-bit splat.  But, then the
2522     // caller would also need to check and handle the change in size.
2523     break;
2524
2525   case 64: {
2526     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2527     uint64_t BitMask = 0xff;
2528     uint64_t Val = 0;
2529     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2530       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2531         Val |= BitMask;
2532       else if ((SplatBits & BitMask) != 0)
2533         return SDValue();
2534       BitMask <<= 8;
2535     }
2536     return DAG.getTargetConstant(Val, MVT::i64);
2537   }
2538
2539   default:
2540     llvm_unreachable("unexpected size for isVMOVSplat");
2541     break;
2542   }
2543
2544   return SDValue();
2545 }
2546
2547 /// getVMOVImm - If this is a build_vector of constants which can be
2548 /// formed by using a VMOV instruction of the specified element size,
2549 /// return the constant being splatted.  The ByteSize field indicates the
2550 /// number of bytes of each element [1248].
2551 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2552   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2553   APInt SplatBits, SplatUndef;
2554   unsigned SplatBitSize;
2555   bool HasAnyUndefs;
2556   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2557                                       HasAnyUndefs, ByteSize * 8))
2558     return SDValue();
2559
2560   if (SplatBitSize > ByteSize * 8)
2561     return SDValue();
2562
2563   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2564                      SplatBitSize, DAG);
2565 }
2566
2567 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
2568                        bool &ReverseVEXT, unsigned &Imm) {
2569   unsigned NumElts = VT.getVectorNumElements();
2570   ReverseVEXT = false;
2571   Imm = M[0];
2572
2573   // If this is a VEXT shuffle, the immediate value is the index of the first
2574   // element.  The other shuffle indices must be the successive elements after
2575   // the first one.
2576   unsigned ExpectedElt = Imm;
2577   for (unsigned i = 1; i < NumElts; ++i) {
2578     // Increment the expected index.  If it wraps around, it may still be
2579     // a VEXT but the source vectors must be swapped.
2580     ExpectedElt += 1;
2581     if (ExpectedElt == NumElts * 2) {
2582       ExpectedElt = 0;
2583       ReverseVEXT = true;
2584     }
2585
2586     if (ExpectedElt != static_cast<unsigned>(M[i]))
2587       return false;
2588   }
2589
2590   // Adjust the index value if the source operands will be swapped.
2591   if (ReverseVEXT)
2592     Imm -= NumElts;
2593
2594   return true;
2595 }
2596
2597 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2598 /// instruction with the specified blocksize.  (The order of the elements
2599 /// within each block of the vector is reversed.)
2600 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
2601                        unsigned BlockSize) {
2602   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2603          "Only possible block sizes for VREV are: 16, 32, 64");
2604
2605   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2606   if (EltSz == 64)
2607     return false;
2608
2609   unsigned NumElts = VT.getVectorNumElements();
2610   unsigned BlockElts = M[0] + 1;
2611
2612   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2613     return false;
2614
2615   for (unsigned i = 0; i < NumElts; ++i) {
2616     if ((unsigned) M[i] !=
2617         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2618       return false;
2619   }
2620
2621   return true;
2622 }
2623
2624 static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
2625                        unsigned &WhichResult) {
2626   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2627   if (EltSz == 64)
2628     return false;
2629
2630   unsigned NumElts = VT.getVectorNumElements();
2631   WhichResult = (M[0] == 0 ? 0 : 1);
2632   for (unsigned i = 0; i < NumElts; i += 2) {
2633     if ((unsigned) M[i] != i + WhichResult ||
2634         (unsigned) M[i+1] != i + NumElts + WhichResult)
2635       return false;
2636   }
2637   return true;
2638 }
2639
2640 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
2641 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
2642 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
2643 static bool isVTRN_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
2644                                 unsigned &WhichResult) {
2645   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2646   if (EltSz == 64)
2647     return false;
2648
2649   unsigned NumElts = VT.getVectorNumElements();
2650   WhichResult = (M[0] == 0 ? 0 : 1);
2651   for (unsigned i = 0; i < NumElts; i += 2) {
2652     if ((unsigned) M[i] != i + WhichResult ||
2653         (unsigned) M[i+1] != i + WhichResult)
2654       return false;
2655   }
2656   return true;
2657 }
2658
2659 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
2660                        unsigned &WhichResult) {
2661   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2662   if (EltSz == 64)
2663     return false;
2664
2665   unsigned NumElts = VT.getVectorNumElements();
2666   WhichResult = (M[0] == 0 ? 0 : 1);
2667   for (unsigned i = 0; i != NumElts; ++i) {
2668     if ((unsigned) M[i] != 2 * i + WhichResult)
2669       return false;
2670   }
2671
2672   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2673   if (VT.is64BitVector() && EltSz == 32)
2674     return false;
2675
2676   return true;
2677 }
2678
2679 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
2680 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
2681 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
2682 static bool isVUZP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
2683                                 unsigned &WhichResult) {
2684   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2685   if (EltSz == 64)
2686     return false;
2687
2688   unsigned Half = VT.getVectorNumElements() / 2;
2689   WhichResult = (M[0] == 0 ? 0 : 1);
2690   for (unsigned j = 0; j != 2; ++j) {
2691     unsigned Idx = WhichResult;
2692     for (unsigned i = 0; i != Half; ++i) {
2693       if ((unsigned) M[i + j * Half] != Idx)
2694         return false;
2695       Idx += 2;
2696     }
2697   }
2698
2699   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2700   if (VT.is64BitVector() && EltSz == 32)
2701     return false;
2702
2703   return true;
2704 }
2705
2706 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
2707                        unsigned &WhichResult) {
2708   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2709   if (EltSz == 64)
2710     return false;
2711
2712   unsigned NumElts = VT.getVectorNumElements();
2713   WhichResult = (M[0] == 0 ? 0 : 1);
2714   unsigned Idx = WhichResult * NumElts / 2;
2715   for (unsigned i = 0; i != NumElts; i += 2) {
2716     if ((unsigned) M[i] != Idx ||
2717         (unsigned) M[i+1] != Idx + NumElts)
2718       return false;
2719     Idx += 1;
2720   }
2721
2722   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2723   if (VT.is64BitVector() && EltSz == 32)
2724     return false;
2725
2726   return true;
2727 }
2728
2729 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
2730 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
2731 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
2732 static bool isVZIP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
2733                                 unsigned &WhichResult) {
2734   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2735   if (EltSz == 64)
2736     return false;
2737
2738   unsigned NumElts = VT.getVectorNumElements();
2739   WhichResult = (M[0] == 0 ? 0 : 1);
2740   unsigned Idx = WhichResult * NumElts / 2;
2741   for (unsigned i = 0; i != NumElts; i += 2) {
2742     if ((unsigned) M[i] != Idx ||
2743         (unsigned) M[i+1] != Idx)
2744       return false;
2745     Idx += 1;
2746   }
2747
2748   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
2749   if (VT.is64BitVector() && EltSz == 32)
2750     return false;
2751
2752   return true;
2753 }
2754
2755
2756 static SDValue BuildSplat(SDValue Val, EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2757   // Canonicalize all-zeros and all-ones vectors.
2758   ConstantSDNode *ConstVal = cast<ConstantSDNode>(Val.getNode());
2759   if (ConstVal->isNullValue())
2760     return getZeroVector(VT, DAG, dl);
2761   if (ConstVal->isAllOnesValue())
2762     return getOnesVector(VT, DAG, dl);
2763
2764   EVT CanonicalVT;
2765   if (VT.is64BitVector()) {
2766     switch (Val.getValueType().getSizeInBits()) {
2767     case 8:  CanonicalVT = MVT::v8i8; break;
2768     case 16: CanonicalVT = MVT::v4i16; break;
2769     case 32: CanonicalVT = MVT::v2i32; break;
2770     case 64: CanonicalVT = MVT::v1i64; break;
2771     default: llvm_unreachable("unexpected splat element type"); break;
2772     }
2773   } else {
2774     assert(VT.is128BitVector() && "unknown splat vector size");
2775     switch (Val.getValueType().getSizeInBits()) {
2776     case 8:  CanonicalVT = MVT::v16i8; break;
2777     case 16: CanonicalVT = MVT::v8i16; break;
2778     case 32: CanonicalVT = MVT::v4i32; break;
2779     case 64: CanonicalVT = MVT::v2i64; break;
2780     default: llvm_unreachable("unexpected splat element type"); break;
2781     }
2782   }
2783
2784   // Build a canonical splat for this value.
2785   SmallVector<SDValue, 8> Ops;
2786   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2787   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2788                             Ops.size());
2789   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2790 }
2791
2792 // If this is a case we can't handle, return null and let the default
2793 // expansion code take care of it.
2794 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2795   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
2796   DebugLoc dl = Op.getDebugLoc();
2797   EVT VT = Op.getValueType();
2798
2799   APInt SplatBits, SplatUndef;
2800   unsigned SplatBitSize;
2801   bool HasAnyUndefs;
2802   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2803     if (SplatBitSize <= 64) {
2804       SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2805                                 SplatUndef.getZExtValue(), SplatBitSize, DAG);
2806       if (Val.getNode())
2807         return BuildSplat(Val, VT, DAG, dl);
2808     }
2809   }
2810
2811   // If there are only 2 elements in a 128-bit vector, insert them into an
2812   // undef vector.  This handles the common case for 128-bit vector argument
2813   // passing, where the insertions should be translated to subreg accesses
2814   // with no real instructions.
2815   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2816     SDValue Val = DAG.getUNDEF(VT);
2817     SDValue Op0 = Op.getOperand(0);
2818     SDValue Op1 = Op.getOperand(1);
2819     if (Op0.getOpcode() != ISD::UNDEF)
2820       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2821                         DAG.getIntPtrConstant(0));
2822     if (Op1.getOpcode() != ISD::UNDEF)
2823       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2824                         DAG.getIntPtrConstant(1));
2825     return Val;
2826   }
2827
2828   return SDValue();
2829 }
2830
2831 /// isShuffleMaskLegal - Targets can use this to indicate that they only
2832 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
2833 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
2834 /// are assumed to be legal.
2835 bool
2836 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
2837                                       EVT VT) const {
2838   if (VT.getVectorNumElements() == 4 &&
2839       (VT.is128BitVector() || VT.is64BitVector())) {
2840     unsigned PFIndexes[4];
2841     for (unsigned i = 0; i != 4; ++i) {
2842       if (M[i] < 0)
2843         PFIndexes[i] = 8;
2844       else
2845         PFIndexes[i] = M[i];
2846     }
2847
2848     // Compute the index in the perfect shuffle table.
2849     unsigned PFTableIndex =
2850       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2851     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2852     unsigned Cost = (PFEntry >> 30);
2853
2854     if (Cost <= 4)
2855       return true;
2856   }
2857
2858   bool ReverseVEXT;
2859   unsigned Imm, WhichResult;
2860
2861   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
2862           isVREVMask(M, VT, 64) ||
2863           isVREVMask(M, VT, 32) ||
2864           isVREVMask(M, VT, 16) ||
2865           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
2866           isVTRNMask(M, VT, WhichResult) ||
2867           isVUZPMask(M, VT, WhichResult) ||
2868           isVZIPMask(M, VT, WhichResult) ||
2869           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
2870           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
2871           isVZIP_v_undef_Mask(M, VT, WhichResult));
2872 }
2873
2874 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
2875 /// the specified operations to build the shuffle.
2876 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
2877                                       SDValue RHS, SelectionDAG &DAG,
2878                                       DebugLoc dl) {
2879   unsigned OpNum = (PFEntry >> 26) & 0x0F;
2880   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
2881   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
2882
2883   enum {
2884     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
2885     OP_VREV,
2886     OP_VDUP0,
2887     OP_VDUP1,
2888     OP_VDUP2,
2889     OP_VDUP3,
2890     OP_VEXT1,
2891     OP_VEXT2,
2892     OP_VEXT3,
2893     OP_VUZPL, // VUZP, left result
2894     OP_VUZPR, // VUZP, right result
2895     OP_VZIPL, // VZIP, left result
2896     OP_VZIPR, // VZIP, right result
2897     OP_VTRNL, // VTRN, left result
2898     OP_VTRNR  // VTRN, right result
2899   };
2900
2901   if (OpNum == OP_COPY) {
2902     if (LHSID == (1*9+2)*9+3) return LHS;
2903     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
2904     return RHS;
2905   }
2906
2907   SDValue OpLHS, OpRHS;
2908   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
2909   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
2910   EVT VT = OpLHS.getValueType();
2911
2912   switch (OpNum) {
2913   default: llvm_unreachable("Unknown shuffle opcode!");
2914   case OP_VREV:
2915     return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
2916   case OP_VDUP0:
2917   case OP_VDUP1:
2918   case OP_VDUP2:
2919   case OP_VDUP3:
2920     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
2921                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
2922   case OP_VEXT1:
2923   case OP_VEXT2:
2924   case OP_VEXT3:
2925     return DAG.getNode(ARMISD::VEXT, dl, VT,
2926                        OpLHS, OpRHS,
2927                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
2928   case OP_VUZPL:
2929   case OP_VUZPR:
2930     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
2931                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
2932   case OP_VZIPL:
2933   case OP_VZIPR:
2934     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
2935                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
2936   case OP_VTRNL:
2937   case OP_VTRNR:
2938     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
2939                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
2940   }
2941 }
2942
2943 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2944   SDValue V1 = Op.getOperand(0);
2945   SDValue V2 = Op.getOperand(1);
2946   DebugLoc dl = Op.getDebugLoc();
2947   EVT VT = Op.getValueType();
2948   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2949   SmallVector<int, 8> ShuffleMask;
2950
2951   // Convert shuffles that are directly supported on NEON to target-specific
2952   // DAG nodes, instead of keeping them as shuffles and matching them again
2953   // during code selection.  This is more efficient and avoids the possibility
2954   // of inconsistencies between legalization and selection.
2955   // FIXME: floating-point vectors should be canonicalized to integer vectors
2956   // of the same time so that they get CSEd properly.
2957   SVN->getMask(ShuffleMask);
2958
2959   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
2960     int Lane = SVN->getSplatIndex();
2961     // If this is undef splat, generate it via "just" vdup, if possible.
2962     if (Lane == -1) Lane = 0;
2963
2964     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
2965       return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
2966     }
2967     return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
2968                        DAG.getConstant(Lane, MVT::i32));
2969   }
2970
2971   bool ReverseVEXT;
2972   unsigned Imm;
2973   if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
2974     if (ReverseVEXT)
2975       std::swap(V1, V2);
2976     return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
2977                        DAG.getConstant(Imm, MVT::i32));
2978   }
2979
2980   if (isVREVMask(ShuffleMask, VT, 64))
2981     return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
2982   if (isVREVMask(ShuffleMask, VT, 32))
2983     return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
2984   if (isVREVMask(ShuffleMask, VT, 16))
2985     return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
2986
2987   // Check for Neon shuffles that modify both input vectors in place.
2988   // If both results are used, i.e., if there are two shuffles with the same
2989   // source operands and with masks corresponding to both results of one of
2990   // these operations, DAG memoization will ensure that a single node is
2991   // used for both shuffles.
2992   unsigned WhichResult;
2993   if (isVTRNMask(ShuffleMask, VT, WhichResult))
2994     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
2995                        V1, V2).getValue(WhichResult);
2996   if (isVUZPMask(ShuffleMask, VT, WhichResult))
2997     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
2998                        V1, V2).getValue(WhichResult);
2999   if (isVZIPMask(ShuffleMask, VT, WhichResult))
3000     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
3001                        V1, V2).getValue(WhichResult);
3002
3003   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
3004     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
3005                        V1, V1).getValue(WhichResult);
3006   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
3007     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
3008                        V1, V1).getValue(WhichResult);
3009   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
3010     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
3011                        V1, V1).getValue(WhichResult);
3012
3013   // If the shuffle is not directly supported and it has 4 elements, use
3014   // the PerfectShuffle-generated table to synthesize it from other shuffles.
3015   if (VT.getVectorNumElements() == 4 &&
3016       (VT.is128BitVector() || VT.is64BitVector())) {
3017     unsigned PFIndexes[4];
3018     for (unsigned i = 0; i != 4; ++i) {
3019       if (ShuffleMask[i] < 0)
3020         PFIndexes[i] = 8;
3021       else
3022         PFIndexes[i] = ShuffleMask[i];
3023     }
3024
3025     // Compute the index in the perfect shuffle table.
3026     unsigned PFTableIndex =
3027       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3028
3029     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3030     unsigned Cost = (PFEntry >> 30);
3031
3032     if (Cost <= 4)
3033       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
3034   }
3035
3036   return SDValue();
3037 }
3038
3039 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
3040   EVT VT = Op.getValueType();
3041   DebugLoc dl = Op.getDebugLoc();
3042   SDValue Vec = Op.getOperand(0);
3043   SDValue Lane = Op.getOperand(1);
3044   assert(VT == MVT::i32 &&
3045          Vec.getValueType().getVectorElementType().getSizeInBits() < 32 &&
3046          "unexpected type for custom-lowering vector extract");
3047   return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
3048 }
3049
3050 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3051   // The only time a CONCAT_VECTORS operation can have legal types is when
3052   // two 64-bit vectors are concatenated to a 128-bit vector.
3053   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
3054          "unexpected CONCAT_VECTORS");
3055   DebugLoc dl = Op.getDebugLoc();
3056   SDValue Val = DAG.getUNDEF(MVT::v2f64);
3057   SDValue Op0 = Op.getOperand(0);
3058   SDValue Op1 = Op.getOperand(1);
3059   if (Op0.getOpcode() != ISD::UNDEF)
3060     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
3061                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
3062                       DAG.getIntPtrConstant(0));
3063   if (Op1.getOpcode() != ISD::UNDEF)
3064     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
3065                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
3066                       DAG.getIntPtrConstant(1));
3067   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
3068 }
3069
3070 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
3071   switch (Op.getOpcode()) {
3072   default: llvm_unreachable("Don't know how to custom lower this!");
3073   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
3074   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
3075   case ISD::GlobalAddress:
3076     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
3077       LowerGlobalAddressELF(Op, DAG);
3078   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
3079   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
3080   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
3081   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
3082   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
3083   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
3084   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
3085   case ISD::SINT_TO_FP:
3086   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
3087   case ISD::FP_TO_SINT:
3088   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
3089   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
3090   case ISD::RETURNADDR:    break;
3091   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
3092   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
3093   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
3094                                                                Subtarget);
3095   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
3096   case ISD::SHL:
3097   case ISD::SRL:
3098   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
3099   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
3100   case ISD::SRL_PARTS:
3101   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
3102   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
3103   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
3104   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
3105   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3106   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3107   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
3108   }
3109   return SDValue();
3110 }
3111
3112 /// ReplaceNodeResults - Replace the results of node with an illegal result
3113 /// type with new values built out of custom code.
3114 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
3115                                            SmallVectorImpl<SDValue>&Results,
3116                                            SelectionDAG &DAG) {
3117   switch (N->getOpcode()) {
3118   default:
3119     llvm_unreachable("Don't know how to custom expand this!");
3120     return;
3121   case ISD::BIT_CONVERT:
3122     Results.push_back(ExpandBIT_CONVERT(N, DAG));
3123     return;
3124   case ISD::SRL:
3125   case ISD::SRA: {
3126     SDValue Res = LowerShift(N, DAG, Subtarget);
3127     if (Res.getNode())
3128       Results.push_back(Res);
3129     return;
3130   }
3131   }
3132 }
3133
3134 //===----------------------------------------------------------------------===//
3135 //                           ARM Scheduler Hooks
3136 //===----------------------------------------------------------------------===//
3137
3138 MachineBasicBlock *
3139 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
3140                                      MachineBasicBlock *BB,
3141                                      unsigned Size) const {
3142   unsigned dest    = MI->getOperand(0).getReg();
3143   unsigned ptr     = MI->getOperand(1).getReg();
3144   unsigned oldval  = MI->getOperand(2).getReg();
3145   unsigned newval  = MI->getOperand(3).getReg();
3146   unsigned scratch = BB->getParent()->getRegInfo()
3147     .createVirtualRegister(ARM::GPRRegisterClass);
3148   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3149   DebugLoc dl = MI->getDebugLoc();
3150   bool isThumb2 = Subtarget->isThumb2();
3151
3152   unsigned ldrOpc, strOpc;
3153   switch (Size) {
3154   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
3155   case 1:
3156     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
3157     strOpc = isThumb2 ? ARM::t2LDREXB : ARM::STREXB;
3158     break;
3159   case 2:
3160     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
3161     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
3162     break;
3163   case 4:
3164     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
3165     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
3166     break;
3167   }
3168
3169   MachineFunction *MF = BB->getParent();
3170   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3171   MachineFunction::iterator It = BB;
3172   ++It; // insert the new blocks after the current block
3173
3174   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
3175   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
3176   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
3177   MF->insert(It, loop1MBB);
3178   MF->insert(It, loop2MBB);
3179   MF->insert(It, exitMBB);
3180   exitMBB->transferSuccessors(BB);
3181
3182   //  thisMBB:
3183   //   ...
3184   //   fallthrough --> loop1MBB
3185   BB->addSuccessor(loop1MBB);
3186
3187   // loop1MBB:
3188   //   ldrex dest, [ptr]
3189   //   cmp dest, oldval
3190   //   bne exitMBB
3191   BB = loop1MBB;
3192   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
3193   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
3194                  .addReg(dest).addReg(oldval));
3195   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
3196     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
3197   BB->addSuccessor(loop2MBB);
3198   BB->addSuccessor(exitMBB);
3199
3200   // loop2MBB:
3201   //   strex scratch, newval, [ptr]
3202   //   cmp scratch, #0
3203   //   bne loop1MBB
3204   BB = loop2MBB;
3205   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval)
3206                  .addReg(ptr));
3207   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
3208                  .addReg(scratch).addImm(0));
3209   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
3210     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
3211   BB->addSuccessor(loop1MBB);
3212   BB->addSuccessor(exitMBB);
3213
3214   //  exitMBB:
3215   //   ...
3216   BB = exitMBB;
3217
3218   MF->DeleteMachineInstr(MI);   // The instruction is gone now.
3219
3220   return BB;
3221 }
3222
3223 MachineBasicBlock *
3224 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
3225                                     unsigned Size, unsigned BinOpcode) const {
3226   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
3227   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3228
3229   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3230   MachineFunction *MF = BB->getParent();
3231   MachineFunction::iterator It = BB;
3232   ++It;
3233
3234   unsigned dest = MI->getOperand(0).getReg();
3235   unsigned ptr = MI->getOperand(1).getReg();
3236   unsigned incr = MI->getOperand(2).getReg();
3237   DebugLoc dl = MI->getDebugLoc();
3238
3239   bool isThumb2 = Subtarget->isThumb2();
3240   unsigned ldrOpc, strOpc;
3241   switch (Size) {
3242   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
3243   case 1:
3244     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
3245     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
3246     break;
3247   case 2:
3248     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
3249     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
3250     break;
3251   case 4:
3252     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
3253     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
3254     break;
3255   }
3256
3257   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
3258   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
3259   MF->insert(It, loopMBB);
3260   MF->insert(It, exitMBB);
3261   exitMBB->transferSuccessors(BB);
3262
3263   MachineRegisterInfo &RegInfo = MF->getRegInfo();
3264   unsigned scratch = RegInfo.createVirtualRegister(ARM::GPRRegisterClass);
3265   unsigned scratch2 = (!BinOpcode) ? incr :
3266     RegInfo.createVirtualRegister(ARM::GPRRegisterClass);
3267
3268   //  thisMBB:
3269   //   ...
3270   //   fallthrough --> loopMBB
3271   BB->addSuccessor(loopMBB);
3272
3273   //  loopMBB:
3274   //   ldrex dest, ptr
3275   //   <binop> scratch2, dest, incr
3276   //   strex scratch, scratch2, ptr
3277   //   cmp scratch, #0
3278   //   bne- loopMBB
3279   //   fallthrough --> exitMBB
3280   BB = loopMBB;
3281   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
3282   if (BinOpcode) {
3283     // operand order needs to go the other way for NAND
3284     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
3285       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
3286                      addReg(incr).addReg(dest)).addReg(0);
3287     else
3288       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
3289                      addReg(dest).addReg(incr)).addReg(0);
3290   }
3291
3292   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2)
3293                  .addReg(ptr));
3294   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
3295                  .addReg(scratch).addImm(0));
3296   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
3297     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
3298
3299   BB->addSuccessor(loopMBB);
3300   BB->addSuccessor(exitMBB);
3301
3302   //  exitMBB:
3303   //   ...
3304   BB = exitMBB;
3305
3306   MF->DeleteMachineInstr(MI);   // The instruction is gone now.
3307
3308   return BB;
3309 }
3310
3311 MachineBasicBlock *
3312 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
3313                                                MachineBasicBlock *BB,
3314                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
3315   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3316   DebugLoc dl = MI->getDebugLoc();
3317   bool isThumb2 = Subtarget->isThumb2();
3318   switch (MI->getOpcode()) {
3319   default:
3320     MI->dump();
3321     llvm_unreachable("Unexpected instr type to insert");
3322
3323   case ARM::ATOMIC_LOAD_ADD_I8:
3324      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
3325   case ARM::ATOMIC_LOAD_ADD_I16:
3326      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
3327   case ARM::ATOMIC_LOAD_ADD_I32:
3328      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
3329
3330   case ARM::ATOMIC_LOAD_AND_I8:
3331      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
3332   case ARM::ATOMIC_LOAD_AND_I16:
3333      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
3334   case ARM::ATOMIC_LOAD_AND_I32:
3335      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
3336
3337   case ARM::ATOMIC_LOAD_OR_I8:
3338      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
3339   case ARM::ATOMIC_LOAD_OR_I16:
3340      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
3341   case ARM::ATOMIC_LOAD_OR_I32:
3342      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
3343
3344   case ARM::ATOMIC_LOAD_XOR_I8:
3345      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
3346   case ARM::ATOMIC_LOAD_XOR_I16:
3347      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
3348   case ARM::ATOMIC_LOAD_XOR_I32:
3349      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
3350
3351   case ARM::ATOMIC_LOAD_NAND_I8:
3352      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
3353   case ARM::ATOMIC_LOAD_NAND_I16:
3354      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
3355   case ARM::ATOMIC_LOAD_NAND_I32:
3356      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
3357
3358   case ARM::ATOMIC_LOAD_SUB_I8:
3359      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
3360   case ARM::ATOMIC_LOAD_SUB_I16:
3361      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
3362   case ARM::ATOMIC_LOAD_SUB_I32:
3363      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
3364
3365   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
3366   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
3367   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
3368
3369   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
3370   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
3371   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
3372
3373   case ARM::tMOVCCr_pseudo: {
3374     // To "insert" a SELECT_CC instruction, we actually have to insert the
3375     // diamond control-flow pattern.  The incoming instruction knows the
3376     // destination vreg to set, the condition code register to branch on, the
3377     // true/false values to select between, and a branch opcode to use.
3378     const BasicBlock *LLVM_BB = BB->getBasicBlock();
3379     MachineFunction::iterator It = BB;
3380     ++It;
3381
3382     //  thisMBB:
3383     //  ...
3384     //   TrueVal = ...
3385     //   cmpTY ccX, r1, r2
3386     //   bCC copy1MBB
3387     //   fallthrough --> copy0MBB
3388     MachineBasicBlock *thisMBB  = BB;
3389     MachineFunction *F = BB->getParent();
3390     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3391     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
3392     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
3393       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
3394     F->insert(It, copy0MBB);
3395     F->insert(It, sinkMBB);
3396     // Update machine-CFG edges by first adding all successors of the current
3397     // block to the new block which will contain the Phi node for the select.
3398     // Also inform sdisel of the edge changes.
3399     for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), 
3400            E = BB->succ_end(); I != E; ++I) {
3401       EM->insert(std::make_pair(*I, sinkMBB));
3402       sinkMBB->addSuccessor(*I);
3403     }
3404     // Next, remove all successors of the current block, and add the true
3405     // and fallthrough blocks as its successors.
3406     while (!BB->succ_empty())
3407       BB->removeSuccessor(BB->succ_begin());
3408     BB->addSuccessor(copy0MBB);
3409     BB->addSuccessor(sinkMBB);
3410
3411     //  copy0MBB:
3412     //   %FalseValue = ...
3413     //   # fallthrough to sinkMBB
3414     BB = copy0MBB;
3415
3416     // Update machine-CFG edges
3417     BB->addSuccessor(sinkMBB);
3418
3419     //  sinkMBB:
3420     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
3421     //  ...
3422     BB = sinkMBB;
3423     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
3424       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
3425       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
3426
3427     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
3428     return BB;
3429   }
3430
3431   case ARM::tANDsp:
3432   case ARM::tADDspr_:
3433   case ARM::tSUBspi_:
3434   case ARM::t2SUBrSPi_:
3435   case ARM::t2SUBrSPi12_:
3436   case ARM::t2SUBrSPs_: {
3437     MachineFunction *MF = BB->getParent();
3438     unsigned DstReg = MI->getOperand(0).getReg();
3439     unsigned SrcReg = MI->getOperand(1).getReg();
3440     bool DstIsDead = MI->getOperand(0).isDead();
3441     bool SrcIsKill = MI->getOperand(1).isKill();
3442
3443     if (SrcReg != ARM::SP) {
3444       // Copy the source to SP from virtual register.
3445       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(SrcReg);
3446       unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
3447         ? ARM::tMOVtgpr2gpr : ARM::tMOVgpr2gpr;
3448       BuildMI(BB, dl, TII->get(CopyOpc), ARM::SP)
3449         .addReg(SrcReg, getKillRegState(SrcIsKill));
3450     }
3451
3452     unsigned OpOpc = 0;
3453     bool NeedPred = false, NeedCC = false, NeedOp3 = false;
3454     switch (MI->getOpcode()) {
3455     default:
3456       llvm_unreachable("Unexpected pseudo instruction!");
3457     case ARM::tANDsp:
3458       OpOpc = ARM::tAND;
3459       NeedPred = true;
3460       break;
3461     case ARM::tADDspr_:
3462       OpOpc = ARM::tADDspr;
3463       break;
3464     case ARM::tSUBspi_:
3465       OpOpc = ARM::tSUBspi;
3466       break;
3467     case ARM::t2SUBrSPi_:
3468       OpOpc = ARM::t2SUBrSPi;
3469       NeedPred = true; NeedCC = true;
3470       break;
3471     case ARM::t2SUBrSPi12_:
3472       OpOpc = ARM::t2SUBrSPi12;
3473       NeedPred = true;
3474       break;
3475     case ARM::t2SUBrSPs_:
3476       OpOpc = ARM::t2SUBrSPs;
3477       NeedPred = true; NeedCC = true; NeedOp3 = true;
3478       break;
3479     }
3480     MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(OpOpc), ARM::SP);
3481     if (OpOpc == ARM::tAND)
3482       AddDefaultT1CC(MIB);
3483     MIB.addReg(ARM::SP);
3484     MIB.addOperand(MI->getOperand(2));
3485     if (NeedOp3)
3486       MIB.addOperand(MI->getOperand(3));
3487     if (NeedPred)
3488       AddDefaultPred(MIB);
3489     if (NeedCC)
3490       AddDefaultCC(MIB);
3491
3492     // Copy the result from SP to virtual register.
3493     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(DstReg);
3494     unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
3495       ? ARM::tMOVgpr2tgpr : ARM::tMOVgpr2gpr;
3496     BuildMI(BB, dl, TII->get(CopyOpc))
3497       .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstIsDead))
3498       .addReg(ARM::SP);
3499     MF->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
3500     return BB;
3501   }
3502   }
3503 }
3504
3505 //===----------------------------------------------------------------------===//
3506 //                           ARM Optimization Hooks
3507 //===----------------------------------------------------------------------===//
3508
3509 static
3510 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
3511                             TargetLowering::DAGCombinerInfo &DCI) {
3512   SelectionDAG &DAG = DCI.DAG;
3513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3514   EVT VT = N->getValueType(0);
3515   unsigned Opc = N->getOpcode();
3516   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
3517   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
3518   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
3519   ISD::CondCode CC = ISD::SETCC_INVALID;
3520
3521   if (isSlctCC) {
3522     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
3523   } else {
3524     SDValue CCOp = Slct.getOperand(0);
3525     if (CCOp.getOpcode() == ISD::SETCC)
3526       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
3527   }
3528
3529   bool DoXform = false;
3530   bool InvCC = false;
3531   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
3532           "Bad input!");
3533
3534   if (LHS.getOpcode() == ISD::Constant &&
3535       cast<ConstantSDNode>(LHS)->isNullValue()) {
3536     DoXform = true;
3537   } else if (CC != ISD::SETCC_INVALID &&
3538              RHS.getOpcode() == ISD::Constant &&
3539              cast<ConstantSDNode>(RHS)->isNullValue()) {
3540     std::swap(LHS, RHS);
3541     SDValue Op0 = Slct.getOperand(0);
3542     EVT OpVT = isSlctCC ? Op0.getValueType() :
3543                           Op0.getOperand(0).getValueType();
3544     bool isInt = OpVT.isInteger();
3545     CC = ISD::getSetCCInverse(CC, isInt);
3546
3547     if (!TLI.isCondCodeLegal(CC, OpVT))
3548       return SDValue();         // Inverse operator isn't legal.
3549
3550     DoXform = true;
3551     InvCC = true;
3552   }
3553
3554   if (DoXform) {
3555     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
3556     if (isSlctCC)
3557       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
3558                              Slct.getOperand(0), Slct.getOperand(1), CC);
3559     SDValue CCOp = Slct.getOperand(0);
3560     if (InvCC)
3561       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
3562                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
3563     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3564                        CCOp, OtherOp, Result);
3565   }
3566   return SDValue();
3567 }
3568
3569 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
3570 static SDValue PerformADDCombine(SDNode *N,
3571                                  TargetLowering::DAGCombinerInfo &DCI) {
3572   // added by evan in r37685 with no testcase.
3573   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3574
3575   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
3576   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
3577     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
3578     if (Result.getNode()) return Result;
3579   }
3580   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
3581     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
3582     if (Result.getNode()) return Result;
3583   }
3584
3585   return SDValue();
3586 }
3587
3588 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
3589 static SDValue PerformSUBCombine(SDNode *N,
3590                                  TargetLowering::DAGCombinerInfo &DCI) {
3591   // added by evan in r37685 with no testcase.
3592   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3593
3594   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
3595   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
3596     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
3597     if (Result.getNode()) return Result;
3598   }
3599
3600   return SDValue();
3601 }
3602
3603 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
3604 /// ARMISD::VMOVRRD.
3605 static SDValue PerformVMOVRRDCombine(SDNode *N,
3606                                    TargetLowering::DAGCombinerInfo &DCI) {
3607   // fmrrd(fmdrr x, y) -> x,y
3608   SDValue InDouble = N->getOperand(0);
3609   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
3610     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
3611   return SDValue();
3612 }
3613
3614 /// getVShiftImm - Check if this is a valid build_vector for the immediate
3615 /// operand of a vector shift operation, where all the elements of the
3616 /// build_vector must have the same constant integer value.
3617 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3618   // Ignore bit_converts.
3619   while (Op.getOpcode() == ISD::BIT_CONVERT)
3620     Op = Op.getOperand(0);
3621   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3622   APInt SplatBits, SplatUndef;
3623   unsigned SplatBitSize;
3624   bool HasAnyUndefs;
3625   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3626                                       HasAnyUndefs, ElementBits) ||
3627       SplatBitSize > ElementBits)
3628     return false;
3629   Cnt = SplatBits.getSExtValue();
3630   return true;
3631 }
3632
3633 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
3634 /// operand of a vector shift left operation.  That value must be in the range:
3635 ///   0 <= Value < ElementBits for a left shift; or
3636 ///   0 <= Value <= ElementBits for a long left shift.
3637 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
3638   assert(VT.isVector() && "vector shift count is not a vector type");
3639   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3640   if (! getVShiftImm(Op, ElementBits, Cnt))
3641     return false;
3642   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
3643 }
3644
3645 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
3646 /// operand of a vector shift right operation.  For a shift opcode, the value
3647 /// is positive, but for an intrinsic the value count must be negative. The
3648 /// absolute value must be in the range:
3649 ///   1 <= |Value| <= ElementBits for a right shift; or
3650 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
3651 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
3652                          int64_t &Cnt) {
3653   assert(VT.isVector() && "vector shift count is not a vector type");
3654   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3655   if (! getVShiftImm(Op, ElementBits, Cnt))
3656     return false;
3657   if (isIntrinsic)
3658     Cnt = -Cnt;
3659   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
3660 }
3661
3662 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
3663 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3664   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3665   switch (IntNo) {
3666   default:
3667     // Don't do anything for most intrinsics.
3668     break;
3669
3670   // Vector shifts: check for immediate versions and lower them.
3671   // Note: This is done during DAG combining instead of DAG legalizing because
3672   // the build_vectors for 64-bit vector element shift counts are generally
3673   // not legal, and it is hard to see their values after they get legalized to
3674   // loads from a constant pool.
3675   case Intrinsic::arm_neon_vshifts:
3676   case Intrinsic::arm_neon_vshiftu:
3677   case Intrinsic::arm_neon_vshiftls:
3678   case Intrinsic::arm_neon_vshiftlu:
3679   case Intrinsic::arm_neon_vshiftn:
3680   case Intrinsic::arm_neon_vrshifts:
3681   case Intrinsic::arm_neon_vrshiftu:
3682   case Intrinsic::arm_neon_vrshiftn:
3683   case Intrinsic::arm_neon_vqshifts:
3684   case Intrinsic::arm_neon_vqshiftu:
3685   case Intrinsic::arm_neon_vqshiftsu:
3686   case Intrinsic::arm_neon_vqshiftns:
3687   case Intrinsic::arm_neon_vqshiftnu:
3688   case Intrinsic::arm_neon_vqshiftnsu:
3689   case Intrinsic::arm_neon_vqrshiftns:
3690   case Intrinsic::arm_neon_vqrshiftnu:
3691   case Intrinsic::arm_neon_vqrshiftnsu: {
3692     EVT VT = N->getOperand(1).getValueType();
3693     int64_t Cnt;
3694     unsigned VShiftOpc = 0;
3695
3696     switch (IntNo) {
3697     case Intrinsic::arm_neon_vshifts:
3698     case Intrinsic::arm_neon_vshiftu:
3699       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
3700         VShiftOpc = ARMISD::VSHL;
3701         break;
3702       }
3703       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
3704         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
3705                      ARMISD::VSHRs : ARMISD::VSHRu);
3706         break;
3707       }
3708       return SDValue();
3709
3710     case Intrinsic::arm_neon_vshiftls:
3711     case Intrinsic::arm_neon_vshiftlu:
3712       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
3713         break;
3714       llvm_unreachable("invalid shift count for vshll intrinsic");
3715
3716     case Intrinsic::arm_neon_vrshifts:
3717     case Intrinsic::arm_neon_vrshiftu:
3718       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
3719         break;
3720       return SDValue();
3721
3722     case Intrinsic::arm_neon_vqshifts:
3723     case Intrinsic::arm_neon_vqshiftu:
3724       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3725         break;
3726       return SDValue();
3727
3728     case Intrinsic::arm_neon_vqshiftsu:
3729       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3730         break;
3731       llvm_unreachable("invalid shift count for vqshlu intrinsic");
3732
3733     case Intrinsic::arm_neon_vshiftn:
3734     case Intrinsic::arm_neon_vrshiftn:
3735     case Intrinsic::arm_neon_vqshiftns:
3736     case Intrinsic::arm_neon_vqshiftnu:
3737     case Intrinsic::arm_neon_vqshiftnsu:
3738     case Intrinsic::arm_neon_vqrshiftns:
3739     case Intrinsic::arm_neon_vqrshiftnu:
3740     case Intrinsic::arm_neon_vqrshiftnsu:
3741       // Narrowing shifts require an immediate right shift.
3742       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
3743         break;
3744       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
3745
3746     default:
3747       llvm_unreachable("unhandled vector shift");
3748     }
3749
3750     switch (IntNo) {
3751     case Intrinsic::arm_neon_vshifts:
3752     case Intrinsic::arm_neon_vshiftu:
3753       // Opcode already set above.
3754       break;
3755     case Intrinsic::arm_neon_vshiftls:
3756     case Intrinsic::arm_neon_vshiftlu:
3757       if (Cnt == VT.getVectorElementType().getSizeInBits())
3758         VShiftOpc = ARMISD::VSHLLi;
3759       else
3760         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
3761                      ARMISD::VSHLLs : ARMISD::VSHLLu);
3762       break;
3763     case Intrinsic::arm_neon_vshiftn:
3764       VShiftOpc = ARMISD::VSHRN; break;
3765     case Intrinsic::arm_neon_vrshifts:
3766       VShiftOpc = ARMISD::VRSHRs; break;
3767     case Intrinsic::arm_neon_vrshiftu:
3768       VShiftOpc = ARMISD::VRSHRu; break;
3769     case Intrinsic::arm_neon_vrshiftn:
3770       VShiftOpc = ARMISD::VRSHRN; break;
3771     case Intrinsic::arm_neon_vqshifts:
3772       VShiftOpc = ARMISD::VQSHLs; break;
3773     case Intrinsic::arm_neon_vqshiftu:
3774       VShiftOpc = ARMISD::VQSHLu; break;
3775     case Intrinsic::arm_neon_vqshiftsu:
3776       VShiftOpc = ARMISD::VQSHLsu; break;
3777     case Intrinsic::arm_neon_vqshiftns:
3778       VShiftOpc = ARMISD::VQSHRNs; break;
3779     case Intrinsic::arm_neon_vqshiftnu:
3780       VShiftOpc = ARMISD::VQSHRNu; break;
3781     case Intrinsic::arm_neon_vqshiftnsu:
3782       VShiftOpc = ARMISD::VQSHRNsu; break;
3783     case Intrinsic::arm_neon_vqrshiftns:
3784       VShiftOpc = ARMISD::VQRSHRNs; break;
3785     case Intrinsic::arm_neon_vqrshiftnu:
3786       VShiftOpc = ARMISD::VQRSHRNu; break;
3787     case Intrinsic::arm_neon_vqrshiftnsu:
3788       VShiftOpc = ARMISD::VQRSHRNsu; break;
3789     }
3790
3791     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3792                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3793   }
3794
3795   case Intrinsic::arm_neon_vshiftins: {
3796     EVT VT = N->getOperand(1).getValueType();
3797     int64_t Cnt;
3798     unsigned VShiftOpc = 0;
3799
3800     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
3801       VShiftOpc = ARMISD::VSLI;
3802     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
3803       VShiftOpc = ARMISD::VSRI;
3804     else {
3805       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
3806     }
3807
3808     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3809                        N->getOperand(1), N->getOperand(2),
3810                        DAG.getConstant(Cnt, MVT::i32));
3811   }
3812
3813   case Intrinsic::arm_neon_vqrshifts:
3814   case Intrinsic::arm_neon_vqrshiftu:
3815     // No immediate versions of these to check for.
3816     break;
3817   }
3818
3819   return SDValue();
3820 }
3821
3822 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
3823 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
3824 /// combining instead of DAG legalizing because the build_vectors for 64-bit
3825 /// vector element shift counts are generally not legal, and it is hard to see
3826 /// their values after they get legalized to loads from a constant pool.
3827 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
3828                                    const ARMSubtarget *ST) {
3829   EVT VT = N->getValueType(0);
3830
3831   // Nothing to be done for scalar shifts.
3832   if (! VT.isVector())
3833     return SDValue();
3834
3835   assert(ST->hasNEON() && "unexpected vector shift");
3836   int64_t Cnt;
3837
3838   switch (N->getOpcode()) {
3839   default: llvm_unreachable("unexpected shift opcode");
3840
3841   case ISD::SHL:
3842     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
3843       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
3844                          DAG.getConstant(Cnt, MVT::i32));
3845     break;
3846
3847   case ISD::SRA:
3848   case ISD::SRL:
3849     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
3850       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
3851                             ARMISD::VSHRs : ARMISD::VSHRu);
3852       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
3853                          DAG.getConstant(Cnt, MVT::i32));
3854     }
3855   }
3856   return SDValue();
3857 }
3858
3859 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
3860 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
3861 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
3862                                     const ARMSubtarget *ST) {
3863   SDValue N0 = N->getOperand(0);
3864
3865   // Check for sign- and zero-extensions of vector extract operations of 8-
3866   // and 16-bit vector elements.  NEON supports these directly.  They are
3867   // handled during DAG combining because type legalization will promote them
3868   // to 32-bit types and it is messy to recognize the operations after that.
3869   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3870     SDValue Vec = N0.getOperand(0);
3871     SDValue Lane = N0.getOperand(1);
3872     EVT VT = N->getValueType(0);
3873     EVT EltVT = N0.getValueType();
3874     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3875
3876     if (VT == MVT::i32 &&
3877         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
3878         TLI.isTypeLegal(Vec.getValueType())) {
3879
3880       unsigned Opc = 0;
3881       switch (N->getOpcode()) {
3882       default: llvm_unreachable("unexpected opcode");
3883       case ISD::SIGN_EXTEND:
3884         Opc = ARMISD::VGETLANEs;
3885         break;
3886       case ISD::ZERO_EXTEND:
3887       case ISD::ANY_EXTEND:
3888         Opc = ARMISD::VGETLANEu;
3889         break;
3890       }
3891       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
3892     }
3893   }
3894
3895   return SDValue();
3896 }
3897
3898 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
3899 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
3900 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
3901                                        const ARMSubtarget *ST) {
3902   // If the target supports NEON, try to use vmax/vmin instructions for f32
3903   // selects like "x < y ? x : y".  Unless the FiniteOnlyFPMath option is set,
3904   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
3905   // a NaN; only do the transformation when it matches that behavior.
3906
3907   // For now only do this when using NEON for FP operations; if using VFP, it
3908   // is not obvious that the benefit outweighs the cost of switching to the
3909   // NEON pipeline.
3910   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
3911       N->getValueType(0) != MVT::f32)
3912     return SDValue();
3913
3914   SDValue CondLHS = N->getOperand(0);
3915   SDValue CondRHS = N->getOperand(1);
3916   SDValue LHS = N->getOperand(2);
3917   SDValue RHS = N->getOperand(3);
3918   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
3919
3920   unsigned Opcode = 0;
3921   bool IsReversed;
3922   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
3923     IsReversed = false; // x CC y ? x : y
3924   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
3925     IsReversed = true ; // x CC y ? y : x
3926   } else {
3927     return SDValue();
3928   }
3929
3930   bool IsUnordered;
3931   switch (CC) {
3932   default: break;
3933   case ISD::SETOLT:
3934   case ISD::SETOLE:
3935   case ISD::SETLT:
3936   case ISD::SETLE:
3937   case ISD::SETULT:
3938   case ISD::SETULE:
3939     // If LHS is NaN, an ordered comparison will be false and the result will
3940     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
3941     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
3942     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
3943     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
3944       break;
3945     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
3946     // will return -0, so vmin can only be used for unsafe math or if one of
3947     // the operands is known to be nonzero.
3948     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
3949         !UnsafeFPMath &&
3950         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
3951       break;
3952     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
3953     break;
3954
3955   case ISD::SETOGT:
3956   case ISD::SETOGE:
3957   case ISD::SETGT:
3958   case ISD::SETGE:
3959   case ISD::SETUGT:
3960   case ISD::SETUGE:
3961     // If LHS is NaN, an ordered comparison will be false and the result will
3962     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
3963     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
3964     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
3965     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
3966       break;
3967     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
3968     // will return +0, so vmax can only be used for unsafe math or if one of
3969     // the operands is known to be nonzero.
3970     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
3971         !UnsafeFPMath &&
3972         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
3973       break;
3974     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
3975     break;
3976   }
3977
3978   if (!Opcode)
3979     return SDValue();
3980   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
3981 }
3982
3983 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
3984                                              DAGCombinerInfo &DCI) const {
3985   switch (N->getOpcode()) {
3986   default: break;
3987   case ISD::ADD:        return PerformADDCombine(N, DCI);
3988   case ISD::SUB:        return PerformSUBCombine(N, DCI);
3989   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
3990   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
3991   case ISD::SHL:
3992   case ISD::SRA:
3993   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
3994   case ISD::SIGN_EXTEND:
3995   case ISD::ZERO_EXTEND:
3996   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
3997   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
3998   }
3999   return SDValue();
4000 }
4001
4002 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
4003   if (!Subtarget->hasV6Ops())
4004     // Pre-v6 does not support unaligned mem access.
4005     return false;
4006   else {
4007     // v6+ may or may not support unaligned mem access depending on the system
4008     // configuration.
4009     // FIXME: This is pretty conservative. Should we provide cmdline option to
4010     // control the behaviour?
4011     if (!Subtarget->isTargetDarwin())
4012       return false;
4013   }
4014
4015   switch (VT.getSimpleVT().SimpleTy) {
4016   default:
4017     return false;
4018   case MVT::i8:
4019   case MVT::i16:
4020   case MVT::i32:
4021     return true;
4022   // FIXME: VLD1 etc with standard alignment is legal.
4023   }
4024 }
4025
4026 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
4027   if (V < 0)
4028     return false;
4029
4030   unsigned Scale = 1;
4031   switch (VT.getSimpleVT().SimpleTy) {
4032   default: return false;
4033   case MVT::i1:
4034   case MVT::i8:
4035     // Scale == 1;
4036     break;
4037   case MVT::i16:
4038     // Scale == 2;
4039     Scale = 2;
4040     break;
4041   case MVT::i32:
4042     // Scale == 4;
4043     Scale = 4;
4044     break;
4045   }
4046
4047   if ((V & (Scale - 1)) != 0)
4048     return false;
4049   V /= Scale;
4050   return V == (V & ((1LL << 5) - 1));
4051 }
4052
4053 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
4054                                       const ARMSubtarget *Subtarget) {
4055   bool isNeg = false;
4056   if (V < 0) {
4057     isNeg = true;
4058     V = - V;
4059   }
4060
4061   switch (VT.getSimpleVT().SimpleTy) {
4062   default: return false;
4063   case MVT::i1:
4064   case MVT::i8:
4065   case MVT::i16:
4066   case MVT::i32:
4067     // + imm12 or - imm8
4068     if (isNeg)
4069       return V == (V & ((1LL << 8) - 1));
4070     return V == (V & ((1LL << 12) - 1));
4071   case MVT::f32:
4072   case MVT::f64:
4073     // Same as ARM mode. FIXME: NEON?
4074     if (!Subtarget->hasVFP2())
4075       return false;
4076     if ((V & 3) != 0)
4077       return false;
4078     V >>= 2;
4079     return V == (V & ((1LL << 8) - 1));
4080   }
4081 }
4082
4083 /// isLegalAddressImmediate - Return true if the integer value can be used
4084 /// as the offset of the target addressing mode for load / store of the
4085 /// given type.
4086 static bool isLegalAddressImmediate(int64_t V, EVT VT,
4087                                     const ARMSubtarget *Subtarget) {
4088   if (V == 0)
4089     return true;
4090
4091   if (!VT.isSimple())
4092     return false;
4093
4094   if (Subtarget->isThumb1Only())
4095     return isLegalT1AddressImmediate(V, VT);
4096   else if (Subtarget->isThumb2())
4097     return isLegalT2AddressImmediate(V, VT, Subtarget);
4098
4099   // ARM mode.
4100   if (V < 0)
4101     V = - V;
4102   switch (VT.getSimpleVT().SimpleTy) {
4103   default: return false;
4104   case MVT::i1:
4105   case MVT::i8:
4106   case MVT::i32:
4107     // +- imm12
4108     return V == (V & ((1LL << 12) - 1));
4109   case MVT::i16:
4110     // +- imm8
4111     return V == (V & ((1LL << 8) - 1));
4112   case MVT::f32:
4113   case MVT::f64:
4114     if (!Subtarget->hasVFP2()) // FIXME: NEON?
4115       return false;
4116     if ((V & 3) != 0)
4117       return false;
4118     V >>= 2;
4119     return V == (V & ((1LL << 8) - 1));
4120   }
4121 }
4122
4123 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
4124                                                       EVT VT) const {
4125   int Scale = AM.Scale;
4126   if (Scale < 0)
4127     return false;
4128
4129   switch (VT.getSimpleVT().SimpleTy) {
4130   default: return false;
4131   case MVT::i1:
4132   case MVT::i8:
4133   case MVT::i16:
4134   case MVT::i32:
4135     if (Scale == 1)
4136       return true;
4137     // r + r << imm
4138     Scale = Scale & ~1;
4139     return Scale == 2 || Scale == 4 || Scale == 8;
4140   case MVT::i64:
4141     // r + r
4142     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
4143       return true;
4144     return false;
4145   case MVT::isVoid:
4146     // Note, we allow "void" uses (basically, uses that aren't loads or
4147     // stores), because arm allows folding a scale into many arithmetic
4148     // operations.  This should be made more precise and revisited later.
4149
4150     // Allow r << imm, but the imm has to be a multiple of two.
4151     if (Scale & 1) return false;
4152     return isPowerOf2_32(Scale);
4153   }
4154 }
4155
4156 /// isLegalAddressingMode - Return true if the addressing mode represented
4157 /// by AM is legal for this target, for a load/store of the specified type.
4158 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
4159                                               const Type *Ty) const {
4160   EVT VT = getValueType(Ty, true);
4161   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
4162     return false;
4163
4164   // Can never fold addr of global into load/store.
4165   if (AM.BaseGV)
4166     return false;
4167
4168   switch (AM.Scale) {
4169   case 0:  // no scale reg, must be "r+i" or "r", or "i".
4170     break;
4171   case 1:
4172     if (Subtarget->isThumb1Only())
4173       return false;
4174     // FALL THROUGH.
4175   default:
4176     // ARM doesn't support any R+R*scale+imm addr modes.
4177     if (AM.BaseOffs)
4178       return false;
4179
4180     if (!VT.isSimple())
4181       return false;
4182
4183     if (Subtarget->isThumb2())
4184       return isLegalT2ScaledAddressingMode(AM, VT);
4185
4186     int Scale = AM.Scale;
4187     switch (VT.getSimpleVT().SimpleTy) {
4188     default: return false;
4189     case MVT::i1:
4190     case MVT::i8:
4191     case MVT::i32:
4192       if (Scale < 0) Scale = -Scale;
4193       if (Scale == 1)
4194         return true;
4195       // r + r << imm
4196       return isPowerOf2_32(Scale & ~1);
4197     case MVT::i16:
4198     case MVT::i64:
4199       // r + r
4200       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
4201         return true;
4202       return false;
4203
4204     case MVT::isVoid:
4205       // Note, we allow "void" uses (basically, uses that aren't loads or
4206       // stores), because arm allows folding a scale into many arithmetic
4207       // operations.  This should be made more precise and revisited later.
4208
4209       // Allow r << imm, but the imm has to be a multiple of two.
4210       if (Scale & 1) return false;
4211       return isPowerOf2_32(Scale);
4212     }
4213     break;
4214   }
4215   return true;
4216 }
4217
4218 /// isLegalICmpImmediate - Return true if the specified immediate is legal
4219 /// icmp immediate, that is the target has icmp instructions which can compare
4220 /// a register against the immediate without having to materialize the
4221 /// immediate into a register.
4222 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
4223   if (!Subtarget->isThumb())
4224     return ARM_AM::getSOImmVal(Imm) != -1;
4225   if (Subtarget->isThumb2())
4226     return ARM_AM::getT2SOImmVal(Imm) != -1; 
4227   return Imm >= 0 && Imm <= 255;
4228 }
4229
4230 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
4231                                       bool isSEXTLoad, SDValue &Base,
4232                                       SDValue &Offset, bool &isInc,
4233                                       SelectionDAG &DAG) {
4234   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
4235     return false;
4236
4237   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
4238     // AddressingMode 3
4239     Base = Ptr->getOperand(0);
4240     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
4241       int RHSC = (int)RHS->getZExtValue();
4242       if (RHSC < 0 && RHSC > -256) {
4243         assert(Ptr->getOpcode() == ISD::ADD);
4244         isInc = false;
4245         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
4246         return true;
4247       }
4248     }
4249     isInc = (Ptr->getOpcode() == ISD::ADD);
4250     Offset = Ptr->getOperand(1);
4251     return true;
4252   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
4253     // AddressingMode 2
4254     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
4255       int RHSC = (int)RHS->getZExtValue();
4256       if (RHSC < 0 && RHSC > -0x1000) {
4257         assert(Ptr->getOpcode() == ISD::ADD);
4258         isInc = false;
4259         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
4260         Base = Ptr->getOperand(0);
4261         return true;
4262       }
4263     }
4264
4265     if (Ptr->getOpcode() == ISD::ADD) {
4266       isInc = true;
4267       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
4268       if (ShOpcVal != ARM_AM::no_shift) {
4269         Base = Ptr->getOperand(1);
4270         Offset = Ptr->getOperand(0);
4271       } else {
4272         Base = Ptr->getOperand(0);
4273         Offset = Ptr->getOperand(1);
4274       }
4275       return true;
4276     }
4277
4278     isInc = (Ptr->getOpcode() == ISD::ADD);
4279     Base = Ptr->getOperand(0);
4280     Offset = Ptr->getOperand(1);
4281     return true;
4282   }
4283
4284   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
4285   return false;
4286 }
4287
4288 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
4289                                      bool isSEXTLoad, SDValue &Base,
4290                                      SDValue &Offset, bool &isInc,
4291                                      SelectionDAG &DAG) {
4292   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
4293     return false;
4294
4295   Base = Ptr->getOperand(0);
4296   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
4297     int RHSC = (int)RHS->getZExtValue();
4298     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
4299       assert(Ptr->getOpcode() == ISD::ADD);
4300       isInc = false;
4301       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
4302       return true;
4303     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
4304       isInc = Ptr->getOpcode() == ISD::ADD;
4305       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
4306       return true;
4307     }
4308   }
4309
4310   return false;
4311 }
4312
4313 /// getPreIndexedAddressParts - returns true by value, base pointer and
4314 /// offset pointer and addressing mode by reference if the node's address
4315 /// can be legally represented as pre-indexed load / store address.
4316 bool
4317 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
4318                                              SDValue &Offset,
4319                                              ISD::MemIndexedMode &AM,
4320                                              SelectionDAG &DAG) const {
4321   if (Subtarget->isThumb1Only())
4322     return false;
4323
4324   EVT VT;
4325   SDValue Ptr;
4326   bool isSEXTLoad = false;
4327   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4328     Ptr = LD->getBasePtr();
4329     VT  = LD->getMemoryVT();
4330     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
4331   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4332     Ptr = ST->getBasePtr();
4333     VT  = ST->getMemoryVT();
4334   } else
4335     return false;
4336
4337   bool isInc;
4338   bool isLegal = false;
4339   if (Subtarget->isThumb2())
4340     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
4341                                        Offset, isInc, DAG);
4342   else
4343     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
4344                                         Offset, isInc, DAG);
4345   if (!isLegal)
4346     return false;
4347
4348   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
4349   return true;
4350 }
4351
4352 /// getPostIndexedAddressParts - returns true by value, base pointer and
4353 /// offset pointer and addressing mode by reference if this node can be
4354 /// combined with a load / store to form a post-indexed load / store.
4355 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
4356                                                    SDValue &Base,
4357                                                    SDValue &Offset,
4358                                                    ISD::MemIndexedMode &AM,
4359                                                    SelectionDAG &DAG) const {
4360   if (Subtarget->isThumb1Only())
4361     return false;
4362
4363   EVT VT;
4364   SDValue Ptr;
4365   bool isSEXTLoad = false;
4366   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4367     VT  = LD->getMemoryVT();
4368     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
4369   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4370     VT  = ST->getMemoryVT();
4371   } else
4372     return false;
4373
4374   bool isInc;
4375   bool isLegal = false;
4376   if (Subtarget->isThumb2())
4377     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
4378                                         isInc, DAG);
4379   else
4380     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
4381                                         isInc, DAG);
4382   if (!isLegal)
4383     return false;
4384
4385   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
4386   return true;
4387 }
4388
4389 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
4390                                                        const APInt &Mask,
4391                                                        APInt &KnownZero,
4392                                                        APInt &KnownOne,
4393                                                        const SelectionDAG &DAG,
4394                                                        unsigned Depth) const {
4395   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
4396   switch (Op.getOpcode()) {
4397   default: break;
4398   case ARMISD::CMOV: {
4399     // Bits are known zero/one if known on the LHS and RHS.
4400     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
4401     if (KnownZero == 0 && KnownOne == 0) return;
4402
4403     APInt KnownZeroRHS, KnownOneRHS;
4404     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
4405                           KnownZeroRHS, KnownOneRHS, Depth+1);
4406     KnownZero &= KnownZeroRHS;
4407     KnownOne  &= KnownOneRHS;
4408     return;
4409   }
4410   }
4411 }
4412
4413 //===----------------------------------------------------------------------===//
4414 //                           ARM Inline Assembly Support
4415 //===----------------------------------------------------------------------===//
4416
4417 /// getConstraintType - Given a constraint letter, return the type of
4418 /// constraint it is for this target.
4419 ARMTargetLowering::ConstraintType
4420 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
4421   if (Constraint.size() == 1) {
4422     switch (Constraint[0]) {
4423     default:  break;
4424     case 'l': return C_RegisterClass;
4425     case 'w': return C_RegisterClass;
4426     }
4427   }
4428   return TargetLowering::getConstraintType(Constraint);
4429 }
4430
4431 std::pair<unsigned, const TargetRegisterClass*>
4432 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4433                                                 EVT VT) const {
4434   if (Constraint.size() == 1) {
4435     // GCC ARM Constraint Letters
4436     switch (Constraint[0]) {
4437     case 'l':
4438       if (Subtarget->isThumb())
4439         return std::make_pair(0U, ARM::tGPRRegisterClass);
4440       else
4441         return std::make_pair(0U, ARM::GPRRegisterClass);
4442     case 'r':
4443       return std::make_pair(0U, ARM::GPRRegisterClass);
4444     case 'w':
4445       if (VT == MVT::f32)
4446         return std::make_pair(0U, ARM::SPRRegisterClass);
4447       if (VT.getSizeInBits() == 64)
4448         return std::make_pair(0U, ARM::DPRRegisterClass);
4449       if (VT.getSizeInBits() == 128)
4450         return std::make_pair(0U, ARM::QPRRegisterClass);
4451       break;
4452     }
4453   }
4454   if (StringRef("{cc}").equals_lower(Constraint))
4455     return std::make_pair(0U, ARM::CCRRegisterClass);
4456
4457   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4458 }
4459
4460 std::vector<unsigned> ARMTargetLowering::
4461 getRegClassForInlineAsmConstraint(const std::string &Constraint,
4462                                   EVT VT) const {
4463   if (Constraint.size() != 1)
4464     return std::vector<unsigned>();
4465
4466   switch (Constraint[0]) {      // GCC ARM Constraint Letters
4467   default: break;
4468   case 'l':
4469     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
4470                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
4471                                  0);
4472   case 'r':
4473     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
4474                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
4475                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
4476                                  ARM::R12, ARM::LR, 0);
4477   case 'w':
4478     if (VT == MVT::f32)
4479       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
4480                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
4481                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
4482                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
4483                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
4484                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
4485                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
4486                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
4487     if (VT.getSizeInBits() == 64)
4488       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
4489                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
4490                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
4491                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
4492     if (VT.getSizeInBits() == 128)
4493       return make_vector<unsigned>(ARM::Q0, ARM::Q1, ARM::Q2, ARM::Q3,
4494                                    ARM::Q4, ARM::Q5, ARM::Q6, ARM::Q7, 0);
4495       break;
4496   }
4497
4498   return std::vector<unsigned>();
4499 }
4500
4501 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4502 /// vector.  If it is invalid, don't add anything to Ops.
4503 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4504                                                      char Constraint,
4505                                                      bool hasMemory,
4506                                                      std::vector<SDValue>&Ops,
4507                                                      SelectionDAG &DAG) const {
4508   SDValue Result(0, 0);
4509
4510   switch (Constraint) {
4511   default: break;
4512   case 'I': case 'J': case 'K': case 'L':
4513   case 'M': case 'N': case 'O':
4514     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4515     if (!C)
4516       return;
4517
4518     int64_t CVal64 = C->getSExtValue();
4519     int CVal = (int) CVal64;
4520     // None of these constraints allow values larger than 32 bits.  Check
4521     // that the value fits in an int.
4522     if (CVal != CVal64)
4523       return;
4524
4525     switch (Constraint) {
4526       case 'I':
4527         if (Subtarget->isThumb1Only()) {
4528           // This must be a constant between 0 and 255, for ADD
4529           // immediates.
4530           if (CVal >= 0 && CVal <= 255)
4531             break;
4532         } else if (Subtarget->isThumb2()) {
4533           // A constant that can be used as an immediate value in a
4534           // data-processing instruction.
4535           if (ARM_AM::getT2SOImmVal(CVal) != -1)
4536             break;
4537         } else {
4538           // A constant that can be used as an immediate value in a
4539           // data-processing instruction.
4540           if (ARM_AM::getSOImmVal(CVal) != -1)
4541             break;
4542         }
4543         return;
4544
4545       case 'J':
4546         if (Subtarget->isThumb()) {  // FIXME thumb2
4547           // This must be a constant between -255 and -1, for negated ADD
4548           // immediates. This can be used in GCC with an "n" modifier that
4549           // prints the negated value, for use with SUB instructions. It is
4550           // not useful otherwise but is implemented for compatibility.
4551           if (CVal >= -255 && CVal <= -1)
4552             break;
4553         } else {
4554           // This must be a constant between -4095 and 4095. It is not clear
4555           // what this constraint is intended for. Implemented for
4556           // compatibility with GCC.
4557           if (CVal >= -4095 && CVal <= 4095)
4558             break;
4559         }
4560         return;
4561
4562       case 'K':
4563         if (Subtarget->isThumb1Only()) {
4564           // A 32-bit value where only one byte has a nonzero value. Exclude
4565           // zero to match GCC. This constraint is used by GCC internally for
4566           // constants that can be loaded with a move/shift combination.
4567           // It is not useful otherwise but is implemented for compatibility.
4568           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
4569             break;
4570         } else if (Subtarget->isThumb2()) {
4571           // A constant whose bitwise inverse can be used as an immediate
4572           // value in a data-processing instruction. This can be used in GCC
4573           // with a "B" modifier that prints the inverted value, for use with
4574           // BIC and MVN instructions. It is not useful otherwise but is
4575           // implemented for compatibility.
4576           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
4577             break;
4578         } else {
4579           // A constant whose bitwise inverse can be used as an immediate
4580           // value in a data-processing instruction. This can be used in GCC
4581           // with a "B" modifier that prints the inverted value, for use with
4582           // BIC and MVN instructions. It is not useful otherwise but is
4583           // implemented for compatibility.
4584           if (ARM_AM::getSOImmVal(~CVal) != -1)
4585             break;
4586         }
4587         return;
4588
4589       case 'L':
4590         if (Subtarget->isThumb1Only()) {
4591           // This must be a constant between -7 and 7,
4592           // for 3-operand ADD/SUB immediate instructions.
4593           if (CVal >= -7 && CVal < 7)
4594             break;
4595         } else if (Subtarget->isThumb2()) {
4596           // A constant whose negation can be used as an immediate value in a
4597           // data-processing instruction. This can be used in GCC with an "n"
4598           // modifier that prints the negated value, for use with SUB
4599           // instructions. It is not useful otherwise but is implemented for
4600           // compatibility.
4601           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
4602             break;
4603         } else {
4604           // A constant whose negation can be used as an immediate value in a
4605           // data-processing instruction. This can be used in GCC with an "n"
4606           // modifier that prints the negated value, for use with SUB
4607           // instructions. It is not useful otherwise but is implemented for
4608           // compatibility.
4609           if (ARM_AM::getSOImmVal(-CVal) != -1)
4610             break;
4611         }
4612         return;
4613
4614       case 'M':
4615         if (Subtarget->isThumb()) { // FIXME thumb2
4616           // This must be a multiple of 4 between 0 and 1020, for
4617           // ADD sp + immediate.
4618           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
4619             break;
4620         } else {
4621           // A power of two or a constant between 0 and 32.  This is used in
4622           // GCC for the shift amount on shifted register operands, but it is
4623           // useful in general for any shift amounts.
4624           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
4625             break;
4626         }
4627         return;
4628
4629       case 'N':
4630         if (Subtarget->isThumb()) {  // FIXME thumb2
4631           // This must be a constant between 0 and 31, for shift amounts.
4632           if (CVal >= 0 && CVal <= 31)
4633             break;
4634         }
4635         return;
4636
4637       case 'O':
4638         if (Subtarget->isThumb()) {  // FIXME thumb2
4639           // This must be a multiple of 4 between -508 and 508, for
4640           // ADD/SUB sp = sp + immediate.
4641           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
4642             break;
4643         }
4644         return;
4645     }
4646     Result = DAG.getTargetConstant(CVal, Op.getValueType());
4647     break;
4648   }
4649
4650   if (Result.getNode()) {
4651     Ops.push_back(Result);
4652     return;
4653   }
4654   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
4655                                                       Ops, DAG);
4656 }
4657
4658 bool
4659 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4660   // The ARM target isn't yet aware of offsets.
4661   return false;
4662 }
4663
4664 int ARM::getVFPf32Imm(const APFloat &FPImm) {
4665   APInt Imm = FPImm.bitcastToAPInt();
4666   uint32_t Sign = Imm.lshr(31).getZExtValue() & 1;
4667   int32_t Exp = (Imm.lshr(23).getSExtValue() & 0xff) - 127;  // -126 to 127
4668   int64_t Mantissa = Imm.getZExtValue() & 0x7fffff;  // 23 bits
4669
4670   // We can handle 4 bits of mantissa.
4671   // mantissa = (16+UInt(e:f:g:h))/16.
4672   if (Mantissa & 0x7ffff)
4673     return -1;
4674   Mantissa >>= 19;
4675   if ((Mantissa & 0xf) != Mantissa)
4676     return -1;
4677
4678   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
4679   if (Exp < -3 || Exp > 4)
4680     return -1;
4681   Exp = ((Exp+3) & 0x7) ^ 4;
4682
4683   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
4684 }
4685
4686 int ARM::getVFPf64Imm(const APFloat &FPImm) {
4687   APInt Imm = FPImm.bitcastToAPInt();
4688   uint64_t Sign = Imm.lshr(63).getZExtValue() & 1;
4689   int64_t Exp = (Imm.lshr(52).getSExtValue() & 0x7ff) - 1023;   // -1022 to 1023
4690   uint64_t Mantissa = Imm.getZExtValue() & 0xfffffffffffffLL;
4691
4692   // We can handle 4 bits of mantissa.
4693   // mantissa = (16+UInt(e:f:g:h))/16.
4694   if (Mantissa & 0xffffffffffffLL)
4695     return -1;
4696   Mantissa >>= 48;
4697   if ((Mantissa & 0xf) != Mantissa)
4698     return -1;
4699
4700   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
4701   if (Exp < -3 || Exp > 4)
4702     return -1;
4703   Exp = ((Exp+3) & 0x7) ^ 4;
4704
4705   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
4706 }
4707
4708 /// isFPImmLegal - Returns true if the target can instruction select the
4709 /// specified FP immediate natively. If false, the legalizer will
4710 /// materialize the FP immediate as a load from a constant pool.
4711 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4712   if (!Subtarget->hasVFP3())
4713     return false;
4714   if (VT == MVT::f32)
4715     return ARM::getVFPf32Imm(Imm) != -1;
4716   if (VT == MVT::f64)
4717     return ARM::getVFPf64Imm(Imm) != -1;
4718   return false;
4719 }