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