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