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