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