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