It turns out most of the thumb2 instructions are not allowed to touch SP. The semanti...
[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 "ARMRegisterInfo.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "ARMTargetObjectFile.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instruction.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/GlobalValue.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/VectorExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 using namespace llvm;
43
44 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
45                                    CCValAssign::LocInfo &LocInfo,
46                                    ISD::ArgFlagsTy &ArgFlags,
47                                    CCState &State);
48 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
49                                     CCValAssign::LocInfo &LocInfo,
50                                     ISD::ArgFlagsTy &ArgFlags,
51                                     CCState &State);
52 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
53                                       CCValAssign::LocInfo &LocInfo,
54                                       ISD::ArgFlagsTy &ArgFlags,
55                                       CCState &State);
56 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
57                                        CCValAssign::LocInfo &LocInfo,
58                                        ISD::ArgFlagsTy &ArgFlags,
59                                        CCState &State);
60
61 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
62                                        MVT PromotedBitwiseVT) {
63   if (VT != PromotedLdStVT) {
64     setOperationAction(ISD::LOAD, VT, Promote);
65     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
66
67     setOperationAction(ISD::STORE, VT, Promote);
68     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
69   }
70
71   MVT ElemTy = VT.getVectorElementType();
72   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
73     setOperationAction(ISD::VSETCC, VT, Custom);
74   if (ElemTy == MVT::i8 || ElemTy == MVT::i16)
75     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
76   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
77   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
78   setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
79   setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
80   if (VT.isInteger()) {
81     setOperationAction(ISD::SHL, VT, Custom);
82     setOperationAction(ISD::SRA, VT, Custom);
83     setOperationAction(ISD::SRL, VT, Custom);
84   }
85
86   // Promote all bit-wise operations.
87   if (VT.isInteger() && VT != PromotedBitwiseVT) {
88     setOperationAction(ISD::AND, VT, Promote);
89     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
90     setOperationAction(ISD::OR,  VT, Promote);
91     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
92     setOperationAction(ISD::XOR, VT, Promote);
93     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
94   }
95 }
96
97 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
98   addRegisterClass(VT, ARM::DPRRegisterClass);
99   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
100 }
101
102 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
103   addRegisterClass(VT, ARM::QPRRegisterClass);
104   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
105 }
106
107 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
108   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
109     return new TargetLoweringObjectFileMachO();
110   return new ARMElfTargetObjectFile();
111 }
112
113 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
114     : TargetLowering(TM, createTLOF(TM)), ARMPCLabelIndex(0) {
115   Subtarget = &TM.getSubtarget<ARMSubtarget>();
116
117   if (Subtarget->isTargetDarwin()) {
118     // Uses VFP for Thumb libfuncs if available.
119     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
120       // Single-precision floating-point arithmetic.
121       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
122       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
123       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
124       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
125
126       // Double-precision floating-point arithmetic.
127       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
128       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
129       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
130       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
131
132       // Single-precision comparisons.
133       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
134       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
135       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
136       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
137       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
138       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
139       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
140       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
141
142       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
143       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
144       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
145       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
146       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
147       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
148       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
149       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
150
151       // Double-precision comparisons.
152       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
153       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
154       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
155       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
156       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
157       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
158       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
159       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
160
161       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
162       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
163       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
164       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
165       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
166       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
167       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
168       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
169
170       // Floating-point to integer conversions.
171       // i64 conversions are done via library routines even when generating VFP
172       // instructions, so use the same ones.
173       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
174       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
175       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
176       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
177
178       // Conversions between floating types.
179       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
180       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
181
182       // Integer to floating-point conversions.
183       // i64 conversions are done via library routines even when generating VFP
184       // instructions, so use the same ones.
185       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
186       // e.g., __floatunsidf vs. __floatunssidfvfp.
187       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
188       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
189       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
190       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
191     }
192   }
193
194   // These libcalls are not available in 32-bit.
195   setLibcallName(RTLIB::SHL_I128, 0);
196   setLibcallName(RTLIB::SRL_I128, 0);
197   setLibcallName(RTLIB::SRA_I128, 0);
198
199   if (Subtarget->isThumb1Only())
200     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
201   else
202     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
203   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
204     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
205     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
206
207     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
208   }
209
210   if (Subtarget->hasNEON()) {
211     addDRTypeForNEON(MVT::v2f32);
212     addDRTypeForNEON(MVT::v8i8);
213     addDRTypeForNEON(MVT::v4i16);
214     addDRTypeForNEON(MVT::v2i32);
215     addDRTypeForNEON(MVT::v1i64);
216
217     addQRTypeForNEON(MVT::v4f32);
218     addQRTypeForNEON(MVT::v2f64);
219     addQRTypeForNEON(MVT::v16i8);
220     addQRTypeForNEON(MVT::v8i16);
221     addQRTypeForNEON(MVT::v4i32);
222     addQRTypeForNEON(MVT::v2i64);
223
224     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
225     setTargetDAGCombine(ISD::SHL);
226     setTargetDAGCombine(ISD::SRL);
227     setTargetDAGCombine(ISD::SRA);
228     setTargetDAGCombine(ISD::SIGN_EXTEND);
229     setTargetDAGCombine(ISD::ZERO_EXTEND);
230     setTargetDAGCombine(ISD::ANY_EXTEND);
231   }
232
233   computeRegisterProperties();
234
235   // ARM does not have f32 extending load.
236   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
237
238   // ARM does not have i1 sign extending load.
239   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
240
241   // ARM supports all 4 flavors of integer indexed load / store.
242   if (!Subtarget->isThumb1Only()) {
243     for (unsigned im = (unsigned)ISD::PRE_INC;
244          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
245       setIndexedLoadAction(im,  MVT::i1,  Legal);
246       setIndexedLoadAction(im,  MVT::i8,  Legal);
247       setIndexedLoadAction(im,  MVT::i16, Legal);
248       setIndexedLoadAction(im,  MVT::i32, Legal);
249       setIndexedStoreAction(im, MVT::i1,  Legal);
250       setIndexedStoreAction(im, MVT::i8,  Legal);
251       setIndexedStoreAction(im, MVT::i16, Legal);
252       setIndexedStoreAction(im, MVT::i32, Legal);
253     }
254   }
255
256   // i64 operation support.
257   if (Subtarget->isThumb1Only()) {
258     setOperationAction(ISD::MUL,     MVT::i64, Expand);
259     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
260     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
261     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
262     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
263   } else {
264     setOperationAction(ISD::MUL,     MVT::i64, Expand);
265     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
266     if (!Subtarget->hasV6Ops())
267       setOperationAction(ISD::MULHS, MVT::i32, Expand);
268   }
269   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
270   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
271   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
272   setOperationAction(ISD::SRL,       MVT::i64, Custom);
273   setOperationAction(ISD::SRA,       MVT::i64, Custom);
274
275   // ARM does not have ROTL.
276   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
277   setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
278   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
279   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
280     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
281
282   // Only ARMv6 has BSWAP.
283   if (!Subtarget->hasV6Ops())
284     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
285
286   // These are expanded into libcalls.
287   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
288   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
289   setOperationAction(ISD::SREM,  MVT::i32, Expand);
290   setOperationAction(ISD::UREM,  MVT::i32, Expand);
291   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
292   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
293
294   // Support label based line numbers.
295   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
296   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
297
298   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
299   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
300   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
301   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
302
303   // Use the default implementation.
304   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
305   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
306   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
307   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
308   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
309   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
310   if (Subtarget->isThumb())
311     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
312   else
313     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
314   setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
315
316   if (!Subtarget->hasV6Ops() && !Subtarget->isThumb2()) {
317     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
318     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
319   }
320   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
321
322   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())
323     // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
324     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
325
326   // We want to custom lower some of our intrinsics.
327   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
328   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
329   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
330
331   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
332   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
333   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
334   setOperationAction(ISD::SELECT,    MVT::i32, Expand);
335   setOperationAction(ISD::SELECT,    MVT::f32, Expand);
336   setOperationAction(ISD::SELECT,    MVT::f64, Expand);
337   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
338   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
339   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
340
341   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
342   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
343   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
344   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
345   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
346
347   // We don't support sin/cos/fmod/copysign/pow
348   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
349   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
350   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
351   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
352   setOperationAction(ISD::FREM,      MVT::f64, Expand);
353   setOperationAction(ISD::FREM,      MVT::f32, Expand);
354   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
355     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
356     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
357   }
358   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
359   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
360
361   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
362   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
363     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
365     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
366     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
367   }
368
369   // We have target-specific dag combine patterns for the following nodes:
370   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
371   setTargetDAGCombine(ISD::ADD);
372   setTargetDAGCombine(ISD::SUB);
373
374   setStackPointerRegisterToSaveRestore(ARM::SP);
375   setSchedulingPreference(SchedulingForRegPressure);
376   setIfCvtBlockSizeLimit(Subtarget->isThumb() ? 0 : 10);
377   setIfCvtDupBlockSizeLimit(Subtarget->isThumb() ? 0 : 2);
378
379   if (!Subtarget->isThumb()) {
380     // Use branch latency information to determine if-conversion limits.
381     // FIXME: If-converter should use instruction latency of the branch being
382     // eliminated to compute the threshold. For ARMv6, the branch "latency"
383     // varies depending on whether it's dynamically or statically predicted
384     // and on whether the destination is in the prefetch buffer.
385     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
386     const InstrItineraryData &InstrItins = Subtarget->getInstrItineraryData();
387     unsigned Latency= InstrItins.getLatency(TII->get(ARM::Bcc).getSchedClass());
388     if (Latency > 1) {
389       setIfCvtBlockSizeLimit(Latency-1);
390       if (Latency > 2)
391         setIfCvtDupBlockSizeLimit(Latency-2);
392     } else {
393       setIfCvtBlockSizeLimit(10);
394       setIfCvtDupBlockSizeLimit(2);
395     }
396   }
397
398   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
399   // Do not enable CodePlacementOpt for now: it currently runs after the
400   // ARMConstantIslandPass and messes up branch relaxation and placement
401   // of constant islands.
402   // benefitFromCodePlacementOpt = true;
403 }
404
405 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
406   switch (Opcode) {
407   default: return 0;
408   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
409   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
410   case ARMISD::CALL:          return "ARMISD::CALL";
411   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
412   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
413   case ARMISD::tCALL:         return "ARMISD::tCALL";
414   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
415   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
416   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
417   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
418   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
419   case ARMISD::CMP:           return "ARMISD::CMP";
420   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
421   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
422   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
423   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
424   case ARMISD::CMOV:          return "ARMISD::CMOV";
425   case ARMISD::CNEG:          return "ARMISD::CNEG";
426
427   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
428   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
429   case ARMISD::SITOF:         return "ARMISD::SITOF";
430   case ARMISD::UITOF:         return "ARMISD::UITOF";
431
432   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
433   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
434   case ARMISD::RRX:           return "ARMISD::RRX";
435
436   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
437   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
438
439   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
440
441   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
442
443   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
444   case ARMISD::VCGE:          return "ARMISD::VCGE";
445   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
446   case ARMISD::VCGT:          return "ARMISD::VCGT";
447   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
448   case ARMISD::VTST:          return "ARMISD::VTST";
449
450   case ARMISD::VSHL:          return "ARMISD::VSHL";
451   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
452   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
453   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
454   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
455   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
456   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
457   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
458   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
459   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
460   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
461   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
462   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
463   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
464   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
465   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
466   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
467   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
468   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
469   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
470   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
471   case ARMISD::VDUPLANEQ:     return "ARMISD::VDUPLANEQ";
472   case ARMISD::VLD2D:         return "ARMISD::VLD2D";
473   case ARMISD::VLD3D:         return "ARMISD::VLD3D";
474   case ARMISD::VLD4D:         return "ARMISD::VLD4D";
475   case ARMISD::VST2D:         return "ARMISD::VST2D";
476   case ARMISD::VST3D:         return "ARMISD::VST3D";
477   case ARMISD::VST4D:         return "ARMISD::VST4D";
478   }
479 }
480
481 /// getFunctionAlignment - Return the Log2 alignment of this function.
482 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
483   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
484 }
485
486 //===----------------------------------------------------------------------===//
487 // Lowering Code
488 //===----------------------------------------------------------------------===//
489
490 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
491 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
492   switch (CC) {
493   default: llvm_unreachable("Unknown condition code!");
494   case ISD::SETNE:  return ARMCC::NE;
495   case ISD::SETEQ:  return ARMCC::EQ;
496   case ISD::SETGT:  return ARMCC::GT;
497   case ISD::SETGE:  return ARMCC::GE;
498   case ISD::SETLT:  return ARMCC::LT;
499   case ISD::SETLE:  return ARMCC::LE;
500   case ISD::SETUGT: return ARMCC::HI;
501   case ISD::SETUGE: return ARMCC::HS;
502   case ISD::SETULT: return ARMCC::LO;
503   case ISD::SETULE: return ARMCC::LS;
504   }
505 }
506
507 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
508 /// returns true if the operands should be inverted to form the proper
509 /// comparison.
510 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
511                         ARMCC::CondCodes &CondCode2) {
512   bool Invert = false;
513   CondCode2 = ARMCC::AL;
514   switch (CC) {
515   default: llvm_unreachable("Unknown FP condition!");
516   case ISD::SETEQ:
517   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
518   case ISD::SETGT:
519   case ISD::SETOGT: CondCode = ARMCC::GT; break;
520   case ISD::SETGE:
521   case ISD::SETOGE: CondCode = ARMCC::GE; break;
522   case ISD::SETOLT: CondCode = ARMCC::MI; break;
523   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
524   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
525   case ISD::SETO:   CondCode = ARMCC::VC; break;
526   case ISD::SETUO:  CondCode = ARMCC::VS; break;
527   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
528   case ISD::SETUGT: CondCode = ARMCC::HI; break;
529   case ISD::SETUGE: CondCode = ARMCC::PL; break;
530   case ISD::SETLT:
531   case ISD::SETULT: CondCode = ARMCC::LT; break;
532   case ISD::SETLE:
533   case ISD::SETULE: CondCode = ARMCC::LE; break;
534   case ISD::SETNE:
535   case ISD::SETUNE: CondCode = ARMCC::NE; break;
536   }
537   return Invert;
538 }
539
540 //===----------------------------------------------------------------------===//
541 //                      Calling Convention Implementation
542 //===----------------------------------------------------------------------===//
543
544 #include "ARMGenCallingConv.inc"
545
546 // APCS f64 is in register pairs, possibly split to stack
547 static bool f64AssignAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
548                           CCValAssign::LocInfo &LocInfo,
549                           CCState &State, bool CanFail) {
550   static const unsigned RegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
551
552   // Try to get the first register.
553   if (unsigned Reg = State.AllocateReg(RegList, 4))
554     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
555   else {
556     // For the 2nd half of a v2f64, do not fail.
557     if (CanFail)
558       return false;
559
560     // Put the whole thing on the stack.
561     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
562                                            State.AllocateStack(8, 4),
563                                            LocVT, LocInfo));
564     return true;
565   }
566
567   // Try to get the second register.
568   if (unsigned Reg = State.AllocateReg(RegList, 4))
569     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
570   else
571     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
572                                            State.AllocateStack(4, 4),
573                                            LocVT, LocInfo));
574   return true;
575 }
576
577 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
578                                    CCValAssign::LocInfo &LocInfo,
579                                    ISD::ArgFlagsTy &ArgFlags,
580                                    CCState &State) {
581   if (!f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
582     return false;
583   if (LocVT == MVT::v2f64 &&
584       !f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
585     return false;
586   return true;  // we handled it
587 }
588
589 // AAPCS f64 is in aligned register pairs
590 static bool f64AssignAAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
591                            CCValAssign::LocInfo &LocInfo,
592                            CCState &State, bool CanFail) {
593   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
594   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
595
596   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
597   if (Reg == 0) {
598     // For the 2nd half of a v2f64, do not just fail.
599     if (CanFail)
600       return false;
601
602     // Put the whole thing on the stack.
603     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
604                                            State.AllocateStack(8, 8),
605                                            LocVT, LocInfo));
606     return true;
607   }
608
609   unsigned i;
610   for (i = 0; i < 2; ++i)
611     if (HiRegList[i] == Reg)
612       break;
613
614   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
615   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
616                                          LocVT, LocInfo));
617   return true;
618 }
619
620 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
621                                     CCValAssign::LocInfo &LocInfo,
622                                     ISD::ArgFlagsTy &ArgFlags,
623                                     CCState &State) {
624   if (!f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
625     return false;
626   if (LocVT == MVT::v2f64 &&
627       !f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
628     return false;
629   return true;  // we handled it
630 }
631
632 static bool f64RetAssign(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
633                          CCValAssign::LocInfo &LocInfo, CCState &State) {
634   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
635   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
636
637   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
638   if (Reg == 0)
639     return false; // we didn't handle it
640
641   unsigned i;
642   for (i = 0; i < 2; ++i)
643     if (HiRegList[i] == Reg)
644       break;
645
646   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
647   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
648                                          LocVT, LocInfo));
649   return true;
650 }
651
652 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
653                                       CCValAssign::LocInfo &LocInfo,
654                                       ISD::ArgFlagsTy &ArgFlags,
655                                       CCState &State) {
656   if (!f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
657     return false;
658   if (LocVT == MVT::v2f64 && !f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
659     return false;
660   return true;  // we handled it
661 }
662
663 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
664                                        CCValAssign::LocInfo &LocInfo,
665                                        ISD::ArgFlagsTy &ArgFlags,
666                                        CCState &State) {
667   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
668                                    State);
669 }
670
671 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
672 /// given CallingConvention value.
673 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(unsigned CC,
674                                                  bool Return,
675                                                  bool isVarArg) const {
676   switch (CC) {
677   default:
678     llvm_unreachable("Unsupported calling convention");
679   case CallingConv::C:
680   case CallingConv::Fast:
681     // Use target triple & subtarget features to do actual dispatch.
682     if (Subtarget->isAAPCS_ABI()) {
683       if (Subtarget->hasVFP2() &&
684           FloatABIType == FloatABI::Hard && !isVarArg)
685         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
686       else
687         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
688     } else
689         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
690   case CallingConv::ARM_AAPCS_VFP:
691     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
692   case CallingConv::ARM_AAPCS:
693     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
694   case CallingConv::ARM_APCS:
695     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
696   }
697 }
698
699 /// LowerCallResult - Lower the result values of a call into the
700 /// appropriate copies out of appropriate physical registers.
701 SDValue
702 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
703                                    unsigned CallConv, bool isVarArg,
704                                    const SmallVectorImpl<ISD::InputArg> &Ins,
705                                    DebugLoc dl, SelectionDAG &DAG,
706                                    SmallVectorImpl<SDValue> &InVals) {
707
708   // Assign locations to each value returned by this call.
709   SmallVector<CCValAssign, 16> RVLocs;
710   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
711                  RVLocs, *DAG.getContext());
712   CCInfo.AnalyzeCallResult(Ins,
713                            CCAssignFnForNode(CallConv, /* Return*/ true,
714                                              isVarArg));
715
716   // Copy all of the result registers out of their specified physreg.
717   for (unsigned i = 0; i != RVLocs.size(); ++i) {
718     CCValAssign VA = RVLocs[i];
719
720     SDValue Val;
721     if (VA.needsCustom()) {
722       // Handle f64 or half of a v2f64.
723       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
724                                       InFlag);
725       Chain = Lo.getValue(1);
726       InFlag = Lo.getValue(2);
727       VA = RVLocs[++i]; // skip ahead to next loc
728       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
729                                       InFlag);
730       Chain = Hi.getValue(1);
731       InFlag = Hi.getValue(2);
732       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
733
734       if (VA.getLocVT() == MVT::v2f64) {
735         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
736         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
737                           DAG.getConstant(0, MVT::i32));
738
739         VA = RVLocs[++i]; // skip ahead to next loc
740         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
741         Chain = Lo.getValue(1);
742         InFlag = Lo.getValue(2);
743         VA = RVLocs[++i]; // skip ahead to next loc
744         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
745         Chain = Hi.getValue(1);
746         InFlag = Hi.getValue(2);
747         Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
748         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
749                           DAG.getConstant(1, MVT::i32));
750       }
751     } else {
752       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
753                                InFlag);
754       Chain = Val.getValue(1);
755       InFlag = Val.getValue(2);
756     }
757
758     switch (VA.getLocInfo()) {
759     default: llvm_unreachable("Unknown loc info!");
760     case CCValAssign::Full: break;
761     case CCValAssign::BCvt:
762       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
763       break;
764     }
765
766     InVals.push_back(Val);
767   }
768
769   return Chain;
770 }
771
772 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
773 /// by "Src" to address "Dst" of size "Size".  Alignment information is
774 /// specified by the specific parameter attribute.  The copy will be passed as
775 /// a byval function parameter.
776 /// Sometimes what we are copying is the end of a larger object, the part that
777 /// does not fit in registers.
778 static SDValue
779 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
780                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
781                           DebugLoc dl) {
782   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
783   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
784                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
785 }
786
787 /// LowerMemOpCallTo - Store the argument to the stack.
788 SDValue
789 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
790                                     SDValue StackPtr, SDValue Arg,
791                                     DebugLoc dl, SelectionDAG &DAG,
792                                     const CCValAssign &VA,
793                                     ISD::ArgFlagsTy Flags) {
794   unsigned LocMemOffset = VA.getLocMemOffset();
795   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
796   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
797   if (Flags.isByVal()) {
798     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
799   }
800   return DAG.getStore(Chain, dl, Arg, PtrOff,
801                       PseudoSourceValue::getStack(), LocMemOffset);
802 }
803
804 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
805                                          SDValue Chain, SDValue &Arg,
806                                          RegsToPassVector &RegsToPass,
807                                          CCValAssign &VA, CCValAssign &NextVA,
808                                          SDValue &StackPtr,
809                                          SmallVector<SDValue, 8> &MemOpChains,
810                                          ISD::ArgFlagsTy Flags) {
811
812   SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
813                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
814   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
815
816   if (NextVA.isRegLoc())
817     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
818   else {
819     assert(NextVA.isMemLoc());
820     if (StackPtr.getNode() == 0)
821       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
822
823     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
824                                            dl, DAG, NextVA,
825                                            Flags));
826   }
827 }
828
829 /// LowerCall - Lowering a call into a callseq_start <-
830 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
831 /// nodes.
832 SDValue
833 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
834                              unsigned CallConv, bool isVarArg,
835                              bool isTailCall,
836                              const SmallVectorImpl<ISD::OutputArg> &Outs,
837                              const SmallVectorImpl<ISD::InputArg> &Ins,
838                              DebugLoc dl, SelectionDAG &DAG,
839                              SmallVectorImpl<SDValue> &InVals) {
840
841   // Analyze operands of the call, assigning locations to each operand.
842   SmallVector<CCValAssign, 16> ArgLocs;
843   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
844                  *DAG.getContext());
845   CCInfo.AnalyzeCallOperands(Outs,
846                              CCAssignFnForNode(CallConv, /* Return*/ false,
847                                                isVarArg));
848
849   // Get a count of how many bytes are to be pushed on the stack.
850   unsigned NumBytes = CCInfo.getNextStackOffset();
851
852   // Adjust the stack pointer for the new arguments...
853   // These operations are automatically eliminated by the prolog/epilog pass
854   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
855
856   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
857
858   RegsToPassVector RegsToPass;
859   SmallVector<SDValue, 8> MemOpChains;
860
861   // Walk the register/memloc assignments, inserting copies/loads.  In the case
862   // of tail call optimization, arguments are handled later.
863   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
864        i != e;
865        ++i, ++realArgIdx) {
866     CCValAssign &VA = ArgLocs[i];
867     SDValue Arg = Outs[realArgIdx].Val;
868     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
869
870     // Promote the value if needed.
871     switch (VA.getLocInfo()) {
872     default: llvm_unreachable("Unknown loc info!");
873     case CCValAssign::Full: break;
874     case CCValAssign::SExt:
875       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
876       break;
877     case CCValAssign::ZExt:
878       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
879       break;
880     case CCValAssign::AExt:
881       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
882       break;
883     case CCValAssign::BCvt:
884       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
885       break;
886     }
887
888     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
889     if (VA.needsCustom()) {
890       if (VA.getLocVT() == MVT::v2f64) {
891         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
892                                   DAG.getConstant(0, MVT::i32));
893         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
894                                   DAG.getConstant(1, MVT::i32));
895
896         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
897                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
898
899         VA = ArgLocs[++i]; // skip ahead to next loc
900         if (VA.isRegLoc()) {
901           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
902                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
903         } else {
904           assert(VA.isMemLoc());
905           if (StackPtr.getNode() == 0)
906             StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
907
908           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
909                                                  dl, DAG, VA, Flags));
910         }
911       } else {
912         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
913                          StackPtr, MemOpChains, Flags);
914       }
915     } else if (VA.isRegLoc()) {
916       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
917     } else {
918       assert(VA.isMemLoc());
919       if (StackPtr.getNode() == 0)
920         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
921
922       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
923                                              dl, DAG, VA, Flags));
924     }
925   }
926
927   if (!MemOpChains.empty())
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
929                         &MemOpChains[0], MemOpChains.size());
930
931   // Build a sequence of copy-to-reg nodes chained together with token chain
932   // and flag operands which copy the outgoing args into the appropriate regs.
933   SDValue InFlag;
934   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
935     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
936                              RegsToPass[i].second, InFlag);
937     InFlag = Chain.getValue(1);
938   }
939
940   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
941   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
942   // node so that legalize doesn't hack it.
943   bool isDirect = false;
944   bool isARMFunc = false;
945   bool isLocalARMFunc = false;
946   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
947     GlobalValue *GV = G->getGlobal();
948     isDirect = true;
949     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
950     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
951                    getTargetMachine().getRelocationModel() != Reloc::Static;
952     isARMFunc = !Subtarget->isThumb() || isStub;
953     // ARM call to a local ARM function is predicable.
954     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
955     // tBX takes a register source operand.
956     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
957       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
958                                                            ARMCP::CPStub, 4);
959       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
960       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
961       Callee = DAG.getLoad(getPointerTy(), dl,
962                            DAG.getEntryNode(), CPAddr, NULL, 0);
963       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
964       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
965                            getPointerTy(), Callee, PICLabel);
966    } else
967       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
968   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
969     isDirect = true;
970     bool isStub = Subtarget->isTargetDarwin() &&
971                   getTargetMachine().getRelocationModel() != Reloc::Static;
972     isARMFunc = !Subtarget->isThumb() || isStub;
973     // tBX takes a register source operand.
974     const char *Sym = S->getSymbol();
975     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
976       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(Sym, ARMPCLabelIndex,
977                                                            ARMCP::CPStub, 4);
978       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
979       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
980       Callee = DAG.getLoad(getPointerTy(), dl,
981                            DAG.getEntryNode(), CPAddr, NULL, 0);
982       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
983       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
984                            getPointerTy(), Callee, PICLabel);
985     } else
986       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
987   }
988
989   // FIXME: handle tail calls differently.
990   unsigned CallOpc;
991   if (Subtarget->isThumb()) {
992     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
993       CallOpc = ARMISD::CALL_NOLINK;
994     else
995       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
996   } else {
997     CallOpc = (isDirect || Subtarget->hasV5TOps())
998       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
999       : ARMISD::CALL_NOLINK;
1000   }
1001   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb1Only()) {
1002     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
1003     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
1004     InFlag = Chain.getValue(1);
1005   }
1006
1007   std::vector<SDValue> Ops;
1008   Ops.push_back(Chain);
1009   Ops.push_back(Callee);
1010
1011   // Add argument registers to the end of the list so that they are known live
1012   // into the call.
1013   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1014     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1015                                   RegsToPass[i].second.getValueType()));
1016
1017   if (InFlag.getNode())
1018     Ops.push_back(InFlag);
1019   // Returns a chain and a flag for retval copy to use.
1020   Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
1021                       &Ops[0], Ops.size());
1022   InFlag = Chain.getValue(1);
1023
1024   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1025                              DAG.getIntPtrConstant(0, true), InFlag);
1026   if (!Ins.empty())
1027     InFlag = Chain.getValue(1);
1028
1029   // Handle result values, copying them out of physregs into vregs that we
1030   // return.
1031   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1032                          dl, DAG, InVals);
1033 }
1034
1035 SDValue
1036 ARMTargetLowering::LowerReturn(SDValue Chain,
1037                                unsigned CallConv, bool isVarArg,
1038                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1039                                DebugLoc dl, SelectionDAG &DAG) {
1040
1041   // CCValAssign - represent the assignment of the return value to a location.
1042   SmallVector<CCValAssign, 16> RVLocs;
1043
1044   // CCState - Info about the registers and stack slots.
1045   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1046                  *DAG.getContext());
1047
1048   // Analyze outgoing return values.
1049   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1050                                                isVarArg));
1051
1052   // If this is the first return lowered for this function, add
1053   // the regs to the liveout set for the function.
1054   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1055     for (unsigned i = 0; i != RVLocs.size(); ++i)
1056       if (RVLocs[i].isRegLoc())
1057         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1058   }
1059
1060   SDValue Flag;
1061
1062   // Copy the result values into the output registers.
1063   for (unsigned i = 0, realRVLocIdx = 0;
1064        i != RVLocs.size();
1065        ++i, ++realRVLocIdx) {
1066     CCValAssign &VA = RVLocs[i];
1067     assert(VA.isRegLoc() && "Can only return in registers!");
1068
1069     SDValue Arg = Outs[realRVLocIdx].Val;
1070
1071     switch (VA.getLocInfo()) {
1072     default: llvm_unreachable("Unknown loc info!");
1073     case CCValAssign::Full: break;
1074     case CCValAssign::BCvt:
1075       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
1076       break;
1077     }
1078
1079     if (VA.needsCustom()) {
1080       if (VA.getLocVT() == MVT::v2f64) {
1081         // Extract the first half and return it in two registers.
1082         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1083                                    DAG.getConstant(0, MVT::i32));
1084         SDValue HalfGPRs = DAG.getNode(ARMISD::FMRRD, dl,
1085                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1086
1087         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1088         Flag = Chain.getValue(1);
1089         VA = RVLocs[++i]; // skip ahead to next loc
1090         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1091                                  HalfGPRs.getValue(1), Flag);
1092         Flag = Chain.getValue(1);
1093         VA = RVLocs[++i]; // skip ahead to next loc
1094
1095         // Extract the 2nd half and fall through to handle it as an f64 value.
1096         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1097                           DAG.getConstant(1, MVT::i32));
1098       }
1099       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1100       // available.
1101       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
1102                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1103       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1104       Flag = Chain.getValue(1);
1105       VA = RVLocs[++i]; // skip ahead to next loc
1106       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1107                                Flag);
1108     } else
1109       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1110
1111     // Guarantee that all emitted copies are
1112     // stuck together, avoiding something bad.
1113     Flag = Chain.getValue(1);
1114   }
1115
1116   SDValue result;
1117   if (Flag.getNode())
1118     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1119   else // Return Void
1120     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1121
1122   return result;
1123 }
1124
1125 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1126 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1127 // one of the above mentioned nodes. It has to be wrapped because otherwise
1128 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1129 // be used to form addressing mode. These wrapped nodes will be selected
1130 // into MOVi.
1131 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1132   MVT PtrVT = Op.getValueType();
1133   // FIXME there is no actual debug info here
1134   DebugLoc dl = Op.getDebugLoc();
1135   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1136   SDValue Res;
1137   if (CP->isMachineConstantPoolEntry())
1138     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1139                                     CP->getAlignment());
1140   else
1141     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1142                                     CP->getAlignment());
1143   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1144 }
1145
1146 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1147 SDValue
1148 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1149                                                  SelectionDAG &DAG) {
1150   DebugLoc dl = GA->getDebugLoc();
1151   MVT PtrVT = getPointerTy();
1152   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1153   ARMConstantPoolValue *CPV =
1154     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
1155                              PCAdj, "tlsgd", true);
1156   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1157   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1158   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
1159   SDValue Chain = Argument.getValue(1);
1160
1161   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1162   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1163
1164   // call __tls_get_addr.
1165   ArgListTy Args;
1166   ArgListEntry Entry;
1167   Entry.Node = Argument;
1168   Entry.Ty = (const Type *) Type::Int32Ty;
1169   Args.push_back(Entry);
1170   // FIXME: is there useful debug info available here?
1171   std::pair<SDValue, SDValue> CallResult =
1172     LowerCallTo(Chain, (const Type *) Type::Int32Ty, false, false, false, false,
1173                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1174                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1175   return CallResult.first;
1176 }
1177
1178 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1179 // "local exec" model.
1180 SDValue
1181 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1182                                         SelectionDAG &DAG) {
1183   GlobalValue *GV = GA->getGlobal();
1184   DebugLoc dl = GA->getDebugLoc();
1185   SDValue Offset;
1186   SDValue Chain = DAG.getEntryNode();
1187   MVT PtrVT = getPointerTy();
1188   // Get the Thread Pointer
1189   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1190
1191   if (GV->isDeclaration()) {
1192     // initial exec model
1193     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1194     ARMConstantPoolValue *CPV =
1195       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
1196                                PCAdj, "gottpoff", true);
1197     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1198     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1199     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1200     Chain = Offset.getValue(1);
1201
1202     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1203     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1204
1205     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1206   } else {
1207     // local exec model
1208     ARMConstantPoolValue *CPV =
1209       new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
1210     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1211     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1212     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1213   }
1214
1215   // The address of the thread local variable is the add of the thread
1216   // pointer with the offset of the variable.
1217   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1218 }
1219
1220 SDValue
1221 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
1222   // TODO: implement the "local dynamic" model
1223   assert(Subtarget->isTargetELF() &&
1224          "TLS not implemented for non-ELF targets");
1225   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1226   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1227   // otherwise use the "Local Exec" TLS Model
1228   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1229     return LowerToTLSGeneralDynamicModel(GA, DAG);
1230   else
1231     return LowerToTLSExecModels(GA, DAG);
1232 }
1233
1234 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1235                                                  SelectionDAG &DAG) {
1236   MVT PtrVT = getPointerTy();
1237   DebugLoc dl = Op.getDebugLoc();
1238   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1239   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1240   if (RelocM == Reloc::PIC_) {
1241     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1242     ARMConstantPoolValue *CPV =
1243       new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
1244     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1245     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1246     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1247                                  CPAddr, NULL, 0);
1248     SDValue Chain = Result.getValue(1);
1249     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1250     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
1251     if (!UseGOTOFF)
1252       Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1253     return Result;
1254   } else {
1255     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1256     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1257     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1258   }
1259 }
1260
1261 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
1262 /// even in non-static mode.
1263 static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
1264   // If symbol visibility is hidden, the extra load is not needed if
1265   // the symbol is definitely defined in the current translation unit.
1266   bool isDecl = GV->isDeclaration() || GV->hasAvailableExternallyLinkage();
1267   if (GV->hasHiddenVisibility() && (!isDecl && !GV->hasCommonLinkage()))
1268     return false;
1269   return RelocM != Reloc::Static && (isDecl || GV->isWeakForLinker());
1270 }
1271
1272 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
1273                                                     SelectionDAG &DAG) {
1274   MVT PtrVT = getPointerTy();
1275   DebugLoc dl = Op.getDebugLoc();
1276   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1277   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1278   bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
1279   SDValue CPAddr;
1280   if (RelocM == Reloc::Static)
1281     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1282   else {
1283     unsigned PCAdj = (RelocM != Reloc::PIC_)
1284       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1285     ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
1286       : ARMCP::CPValue;
1287     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
1288                                                          Kind, PCAdj);
1289     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1290   }
1291   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1292
1293   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1294   SDValue Chain = Result.getValue(1);
1295
1296   if (RelocM == Reloc::PIC_) {
1297     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1298     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1299   }
1300   if (IsIndirect)
1301     Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1302
1303   return Result;
1304 }
1305
1306 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1307                                                     SelectionDAG &DAG){
1308   assert(Subtarget->isTargetELF() &&
1309          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1310   MVT PtrVT = getPointerTy();
1311   DebugLoc dl = Op.getDebugLoc();
1312   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1313   ARMConstantPoolValue *CPV = new ARMConstantPoolValue("_GLOBAL_OFFSET_TABLE_",
1314                                                        ARMPCLabelIndex,
1315                                                        ARMCP::CPValue, PCAdj);
1316   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1317   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1318   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1319   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1320   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1321 }
1322
1323 static SDValue LowerNeonVLDIntrinsic(SDValue Op, SelectionDAG &DAG,
1324                                      unsigned Opcode) {
1325   SDNode *Node = Op.getNode();
1326   MVT VT = Node->getValueType(0);
1327   DebugLoc dl = Op.getDebugLoc();
1328
1329   if (!VT.is64BitVector())
1330     return SDValue(); // unimplemented
1331
1332   SDValue Ops[] = { Node->getOperand(0),
1333                     Node->getOperand(2) };
1334   return DAG.getNode(Opcode, dl, Node->getVTList(), Ops, 2);
1335 }
1336
1337 static SDValue LowerNeonVSTIntrinsic(SDValue Op, SelectionDAG &DAG,
1338                                      unsigned Opcode, unsigned NumVecs) {
1339   SDNode *Node = Op.getNode();
1340   MVT VT = Node->getOperand(3).getValueType();
1341   DebugLoc dl = Op.getDebugLoc();
1342
1343   if (!VT.is64BitVector())
1344     return SDValue(); // unimplemented
1345
1346   SmallVector<SDValue, 6> Ops;
1347   Ops.push_back(Node->getOperand(0));
1348   Ops.push_back(Node->getOperand(2));
1349   for (unsigned N = 0; N < NumVecs; ++N)
1350     Ops.push_back(Node->getOperand(N + 3));
1351   return DAG.getNode(Opcode, dl, MVT::Other, Ops.data(), Ops.size());
1352 }
1353
1354 SDValue
1355 ARMTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
1356   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1357   switch (IntNo) {
1358   case Intrinsic::arm_neon_vld2i:
1359   case Intrinsic::arm_neon_vld2f:
1360     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD2D);
1361   case Intrinsic::arm_neon_vld3i:
1362   case Intrinsic::arm_neon_vld3f:
1363     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD3D);
1364   case Intrinsic::arm_neon_vld4i:
1365   case Intrinsic::arm_neon_vld4f:
1366     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD4D);
1367   case Intrinsic::arm_neon_vst2i:
1368   case Intrinsic::arm_neon_vst2f:
1369     return LowerNeonVSTIntrinsic(Op, DAG, ARMISD::VST2D, 2);
1370   case Intrinsic::arm_neon_vst3i:
1371   case Intrinsic::arm_neon_vst3f:
1372     return LowerNeonVSTIntrinsic(Op, DAG, ARMISD::VST3D, 3);
1373   case Intrinsic::arm_neon_vst4i:
1374   case Intrinsic::arm_neon_vst4f:
1375     return LowerNeonVSTIntrinsic(Op, DAG, ARMISD::VST4D, 4);
1376   default: return SDValue();    // Don't custom lower most intrinsics.
1377   }
1378 }
1379
1380 SDValue
1381 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1382   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1383   DebugLoc dl = Op.getDebugLoc();
1384   switch (IntNo) {
1385   default: return SDValue();    // Don't custom lower most intrinsics.
1386   case Intrinsic::arm_thread_pointer: {
1387     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1388     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1389   }
1390   case Intrinsic::eh_sjlj_setjmp:
1391     return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(1));
1392   }
1393 }
1394
1395 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1396                             unsigned VarArgsFrameIndex) {
1397   // vastart just stores the address of the VarArgsFrameIndex slot into the
1398   // memory location argument.
1399   DebugLoc dl = Op.getDebugLoc();
1400   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1401   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1402   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1403   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1404 }
1405
1406 SDValue
1407 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1408   SDNode *Node = Op.getNode();
1409   DebugLoc dl = Node->getDebugLoc();
1410   MVT VT = Node->getValueType(0);
1411   SDValue Chain = Op.getOperand(0);
1412   SDValue Size  = Op.getOperand(1);
1413   SDValue Align = Op.getOperand(2);
1414
1415   // Chain the dynamic stack allocation so that it doesn't modify the stack
1416   // pointer when other instructions are using the stack.
1417   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1418
1419   unsigned AlignVal = cast<ConstantSDNode>(Align)->getZExtValue();
1420   unsigned StackAlign = getTargetMachine().getFrameInfo()->getStackAlignment();
1421   if (AlignVal > StackAlign)
1422     // Do this now since selection pass cannot introduce new target
1423     // independent node.
1424     Align = DAG.getConstant(-(uint64_t)AlignVal, VT);
1425
1426   // In Thumb1 mode, there isn't a "sub r, sp, r" instruction, we will end up
1427   // using a "add r, sp, r" instead. Negate the size now so we don't have to
1428   // do even more horrible hack later.
1429   MachineFunction &MF = DAG.getMachineFunction();
1430   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1431   if (AFI->isThumb1OnlyFunction()) {
1432     bool Negate = true;
1433     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Size);
1434     if (C) {
1435       uint32_t Val = C->getZExtValue();
1436       if (Val <= 508 && ((Val & 3) == 0))
1437         Negate = false;
1438     }
1439     if (Negate)
1440       Size = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, VT), Size);
1441   }
1442
1443   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1444   SDValue Ops1[] = { Chain, Size, Align };
1445   SDValue Res = DAG.getNode(ARMISD::DYN_ALLOC, dl, VTList, Ops1, 3);
1446   Chain = Res.getValue(1);
1447   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1448                              DAG.getIntPtrConstant(0, true), SDValue());
1449   SDValue Ops2[] = { Res, Chain };
1450   return DAG.getMergeValues(Ops2, 2, dl);
1451 }
1452
1453 SDValue
1454 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1455                                         SDValue &Root, SelectionDAG &DAG,
1456                                         DebugLoc dl) {
1457   MachineFunction &MF = DAG.getMachineFunction();
1458   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1459
1460   TargetRegisterClass *RC;
1461   if (AFI->isThumb1OnlyFunction())
1462     RC = ARM::tGPRRegisterClass;
1463   else
1464     RC = ARM::GPRRegisterClass;
1465
1466   // Transform the arguments stored in physical registers into virtual ones.
1467   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1468   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1469
1470   SDValue ArgValue2;
1471   if (NextVA.isMemLoc()) {
1472     unsigned ArgSize = NextVA.getLocVT().getSizeInBits()/8;
1473     MachineFrameInfo *MFI = MF.getFrameInfo();
1474     int FI = MFI->CreateFixedObject(ArgSize, NextVA.getLocMemOffset());
1475
1476     // Create load node to retrieve arguments from the stack.
1477     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1478     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1479   } else {
1480     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1481     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1482   }
1483
1484   return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
1485 }
1486
1487 SDValue
1488 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1489                                         unsigned CallConv, bool isVarArg,
1490                                         const SmallVectorImpl<ISD::InputArg>
1491                                           &Ins,
1492                                         DebugLoc dl, SelectionDAG &DAG,
1493                                         SmallVectorImpl<SDValue> &InVals) {
1494
1495   MachineFunction &MF = DAG.getMachineFunction();
1496   MachineFrameInfo *MFI = MF.getFrameInfo();
1497
1498   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1499
1500   // Assign locations to all of the incoming arguments.
1501   SmallVector<CCValAssign, 16> ArgLocs;
1502   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1503                  *DAG.getContext());
1504   CCInfo.AnalyzeFormalArguments(Ins,
1505                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1506                                                   isVarArg));
1507
1508   SmallVector<SDValue, 16> ArgValues;
1509
1510   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1511     CCValAssign &VA = ArgLocs[i];
1512
1513     // Arguments stored in registers.
1514     if (VA.isRegLoc()) {
1515       MVT RegVT = VA.getLocVT();
1516
1517       SDValue ArgValue;
1518       if (VA.needsCustom()) {
1519         // f64 and vector types are split up into multiple registers or
1520         // combinations of registers and stack slots.
1521         RegVT = MVT::i32;
1522
1523         if (VA.getLocVT() == MVT::v2f64) {
1524           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1525                                                    Chain, DAG, dl);
1526           VA = ArgLocs[++i]; // skip ahead to next loc
1527           SDValue ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1528                                                    Chain, DAG, dl);
1529           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1530           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1531                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1532           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1533                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1534         } else
1535           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
1536
1537       } else {
1538         TargetRegisterClass *RC;
1539
1540         if (RegVT == MVT::f32)
1541           RC = ARM::SPRRegisterClass;
1542         else if (RegVT == MVT::f64)
1543           RC = ARM::DPRRegisterClass;
1544         else if (RegVT == MVT::v2f64)
1545           RC = ARM::QPRRegisterClass;
1546         else if (RegVT == MVT::i32)
1547           RC = (AFI->isThumb1OnlyFunction() ?
1548                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
1549         else
1550           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1551
1552         // Transform the arguments in physical registers into virtual ones.
1553         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1554         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1555       }
1556
1557       // If this is an 8 or 16-bit value, it is really passed promoted
1558       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1559       // truncate to the right size.
1560       switch (VA.getLocInfo()) {
1561       default: llvm_unreachable("Unknown loc info!");
1562       case CCValAssign::Full: break;
1563       case CCValAssign::BCvt:
1564         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1565         break;
1566       case CCValAssign::SExt:
1567         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1568                                DAG.getValueType(VA.getValVT()));
1569         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1570         break;
1571       case CCValAssign::ZExt:
1572         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1573                                DAG.getValueType(VA.getValVT()));
1574         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1575         break;
1576       }
1577
1578       InVals.push_back(ArgValue);
1579
1580     } else { // VA.isRegLoc()
1581
1582       // sanity check
1583       assert(VA.isMemLoc());
1584       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1585
1586       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1587       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1588
1589       // Create load nodes to retrieve arguments from the stack.
1590       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1591       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
1592     }
1593   }
1594
1595   // varargs
1596   if (isVarArg) {
1597     static const unsigned GPRArgRegs[] = {
1598       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1599     };
1600
1601     unsigned NumGPRs = CCInfo.getFirstUnallocated
1602       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1603
1604     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1605     unsigned VARegSize = (4 - NumGPRs) * 4;
1606     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1607     unsigned ArgOffset = 0;
1608     if (VARegSaveSize) {
1609       // If this function is vararg, store any remaining integer argument regs
1610       // to their spots on the stack so that they may be loaded by deferencing
1611       // the result of va_next.
1612       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1613       ArgOffset = CCInfo.getNextStackOffset();
1614       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1615                                                  VARegSaveSize - VARegSize);
1616       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1617
1618       SmallVector<SDValue, 4> MemOps;
1619       for (; NumGPRs < 4; ++NumGPRs) {
1620         TargetRegisterClass *RC;
1621         if (AFI->isThumb1OnlyFunction())
1622           RC = ARM::tGPRRegisterClass;
1623         else
1624           RC = ARM::GPRRegisterClass;
1625
1626         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1627         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1628         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1629         MemOps.push_back(Store);
1630         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1631                           DAG.getConstant(4, getPointerTy()));
1632       }
1633       if (!MemOps.empty())
1634         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1635                             &MemOps[0], MemOps.size());
1636     } else
1637       // This will point to the next argument passed via stack.
1638       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1639   }
1640
1641   return Chain;
1642 }
1643
1644 /// isFloatingPointZero - Return true if this is +0.0.
1645 static bool isFloatingPointZero(SDValue Op) {
1646   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1647     return CFP->getValueAPF().isPosZero();
1648   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1649     // Maybe this has already been legalized into the constant pool?
1650     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1651       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1652       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1653         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1654           return CFP->getValueAPF().isPosZero();
1655     }
1656   }
1657   return false;
1658 }
1659
1660 static bool isLegalCmpImmediate(unsigned C, bool isThumb1Only) {
1661   return ( isThumb1Only && (C & ~255U) == 0) ||
1662          (!isThumb1Only && ARM_AM::getSOImmVal(C) != -1);
1663 }
1664
1665 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1666 /// the given operands.
1667 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1668                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb1Only,
1669                          DebugLoc dl) {
1670   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1671     unsigned C = RHSC->getZExtValue();
1672     if (!isLegalCmpImmediate(C, isThumb1Only)) {
1673       // Constant does not fit, try adjusting it by one?
1674       switch (CC) {
1675       default: break;
1676       case ISD::SETLT:
1677       case ISD::SETGE:
1678         if (isLegalCmpImmediate(C-1, isThumb1Only)) {
1679           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1680           RHS = DAG.getConstant(C-1, MVT::i32);
1681         }
1682         break;
1683       case ISD::SETULT:
1684       case ISD::SETUGE:
1685         if (C > 0 && isLegalCmpImmediate(C-1, isThumb1Only)) {
1686           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1687           RHS = DAG.getConstant(C-1, MVT::i32);
1688         }
1689         break;
1690       case ISD::SETLE:
1691       case ISD::SETGT:
1692         if (isLegalCmpImmediate(C+1, isThumb1Only)) {
1693           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1694           RHS = DAG.getConstant(C+1, MVT::i32);
1695         }
1696         break;
1697       case ISD::SETULE:
1698       case ISD::SETUGT:
1699         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb1Only)) {
1700           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1701           RHS = DAG.getConstant(C+1, MVT::i32);
1702         }
1703         break;
1704       }
1705     }
1706   }
1707
1708   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1709   ARMISD::NodeType CompareType;
1710   switch (CondCode) {
1711   default:
1712     CompareType = ARMISD::CMP;
1713     break;
1714   case ARMCC::EQ:
1715   case ARMCC::NE:
1716     // Uses only Z Flag
1717     CompareType = ARMISD::CMPZ;
1718     break;
1719   }
1720   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1721   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1722 }
1723
1724 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1725 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1726                          DebugLoc dl) {
1727   SDValue Cmp;
1728   if (!isFloatingPointZero(RHS))
1729     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1730   else
1731     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1732   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1733 }
1734
1735 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1736                               const ARMSubtarget *ST) {
1737   MVT VT = Op.getValueType();
1738   SDValue LHS = Op.getOperand(0);
1739   SDValue RHS = Op.getOperand(1);
1740   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1741   SDValue TrueVal = Op.getOperand(2);
1742   SDValue FalseVal = Op.getOperand(3);
1743   DebugLoc dl = Op.getDebugLoc();
1744
1745   if (LHS.getValueType() == MVT::i32) {
1746     SDValue ARMCC;
1747     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1748     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1749     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1750   }
1751
1752   ARMCC::CondCodes CondCode, CondCode2;
1753   if (FPCCToARMCC(CC, CondCode, CondCode2))
1754     std::swap(TrueVal, FalseVal);
1755
1756   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1757   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1758   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1759   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1760                                  ARMCC, CCR, Cmp);
1761   if (CondCode2 != ARMCC::AL) {
1762     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1763     // FIXME: Needs another CMP because flag can have but one use.
1764     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1765     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1766                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1767   }
1768   return Result;
1769 }
1770
1771 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1772                           const ARMSubtarget *ST) {
1773   SDValue  Chain = Op.getOperand(0);
1774   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1775   SDValue    LHS = Op.getOperand(2);
1776   SDValue    RHS = Op.getOperand(3);
1777   SDValue   Dest = Op.getOperand(4);
1778   DebugLoc dl = Op.getDebugLoc();
1779
1780   if (LHS.getValueType() == MVT::i32) {
1781     SDValue ARMCC;
1782     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1783     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1784     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1785                        Chain, Dest, ARMCC, CCR,Cmp);
1786   }
1787
1788   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1789   ARMCC::CondCodes CondCode, CondCode2;
1790   if (FPCCToARMCC(CC, CondCode, CondCode2))
1791     // Swap the LHS/RHS of the comparison if needed.
1792     std::swap(LHS, RHS);
1793
1794   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1795   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1796   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1797   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1798   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1799   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1800   if (CondCode2 != ARMCC::AL) {
1801     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1802     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1803     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1804   }
1805   return Res;
1806 }
1807
1808 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1809   SDValue Chain = Op.getOperand(0);
1810   SDValue Table = Op.getOperand(1);
1811   SDValue Index = Op.getOperand(2);
1812   DebugLoc dl = Op.getDebugLoc();
1813
1814   MVT PTy = getPointerTy();
1815   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1816   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1817   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1818   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1819   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1820   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1821   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1822   if (Subtarget->isThumb2()) {
1823     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1824     // which does another jump to the destination. This also makes it easier
1825     // to translate it to TBB / TBH later.
1826     // FIXME: This might not work if the function is extremely large.
1827     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1828                        Addr, Op.getOperand(2), JTI, UId);
1829   }
1830   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1831     Addr = DAG.getLoad((MVT)MVT::i32, dl, Chain, Addr, NULL, 0);
1832     Chain = Addr.getValue(1);
1833     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1834     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1835   } else {
1836     Addr = DAG.getLoad(PTy, dl, Chain, Addr, NULL, 0);
1837     Chain = Addr.getValue(1);
1838     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1839   }
1840 }
1841
1842 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1843   DebugLoc dl = Op.getDebugLoc();
1844   unsigned Opc =
1845     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1846   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1847   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1848 }
1849
1850 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1851   MVT VT = Op.getValueType();
1852   DebugLoc dl = Op.getDebugLoc();
1853   unsigned Opc =
1854     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1855
1856   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1857   return DAG.getNode(Opc, dl, VT, Op);
1858 }
1859
1860 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1861   // Implement fcopysign with a fabs and a conditional fneg.
1862   SDValue Tmp0 = Op.getOperand(0);
1863   SDValue Tmp1 = Op.getOperand(1);
1864   DebugLoc dl = Op.getDebugLoc();
1865   MVT VT = Op.getValueType();
1866   MVT SrcVT = Tmp1.getValueType();
1867   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1868   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1869   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1870   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1871   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1872 }
1873
1874 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1875   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1876   MFI->setFrameAddressIsTaken(true);
1877   MVT VT = Op.getValueType();
1878   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1879   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1880   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1881     ? ARM::R7 : ARM::R11;
1882   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1883   while (Depth--)
1884     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1885   return FrameAddr;
1886 }
1887
1888 SDValue
1889 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1890                                            SDValue Chain,
1891                                            SDValue Dst, SDValue Src,
1892                                            SDValue Size, unsigned Align,
1893                                            bool AlwaysInline,
1894                                          const Value *DstSV, uint64_t DstSVOff,
1895                                          const Value *SrcSV, uint64_t SrcSVOff){
1896   // Do repeated 4-byte loads and stores. To be improved.
1897   // This requires 4-byte alignment.
1898   if ((Align & 3) != 0)
1899     return SDValue();
1900   // This requires the copy size to be a constant, preferrably
1901   // within a subtarget-specific limit.
1902   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1903   if (!ConstantSize)
1904     return SDValue();
1905   uint64_t SizeVal = ConstantSize->getZExtValue();
1906   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1907     return SDValue();
1908
1909   unsigned BytesLeft = SizeVal & 3;
1910   unsigned NumMemOps = SizeVal >> 2;
1911   unsigned EmittedNumMemOps = 0;
1912   MVT VT = MVT::i32;
1913   unsigned VTSize = 4;
1914   unsigned i = 0;
1915   const unsigned MAX_LOADS_IN_LDM = 6;
1916   SDValue TFOps[MAX_LOADS_IN_LDM];
1917   SDValue Loads[MAX_LOADS_IN_LDM];
1918   uint64_t SrcOff = 0, DstOff = 0;
1919
1920   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1921   // same number of stores.  The loads and stores will get combined into
1922   // ldm/stm later on.
1923   while (EmittedNumMemOps < NumMemOps) {
1924     for (i = 0;
1925          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1926       Loads[i] = DAG.getLoad(VT, dl, Chain,
1927                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1928                                          DAG.getConstant(SrcOff, MVT::i32)),
1929                              SrcSV, SrcSVOff + SrcOff);
1930       TFOps[i] = Loads[i].getValue(1);
1931       SrcOff += VTSize;
1932     }
1933     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1934
1935     for (i = 0;
1936          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1937       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1938                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1939                                        DAG.getConstant(DstOff, MVT::i32)),
1940                            DstSV, DstSVOff + DstOff);
1941       DstOff += VTSize;
1942     }
1943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1944
1945     EmittedNumMemOps += i;
1946   }
1947
1948   if (BytesLeft == 0)
1949     return Chain;
1950
1951   // Issue loads / stores for the trailing (1 - 3) bytes.
1952   unsigned BytesLeftSave = BytesLeft;
1953   i = 0;
1954   while (BytesLeft) {
1955     if (BytesLeft >= 2) {
1956       VT = MVT::i16;
1957       VTSize = 2;
1958     } else {
1959       VT = MVT::i8;
1960       VTSize = 1;
1961     }
1962
1963     Loads[i] = DAG.getLoad(VT, dl, Chain,
1964                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1965                                        DAG.getConstant(SrcOff, MVT::i32)),
1966                            SrcSV, SrcSVOff + SrcOff);
1967     TFOps[i] = Loads[i].getValue(1);
1968     ++i;
1969     SrcOff += VTSize;
1970     BytesLeft -= VTSize;
1971   }
1972   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1973
1974   i = 0;
1975   BytesLeft = BytesLeftSave;
1976   while (BytesLeft) {
1977     if (BytesLeft >= 2) {
1978       VT = MVT::i16;
1979       VTSize = 2;
1980     } else {
1981       VT = MVT::i8;
1982       VTSize = 1;
1983     }
1984
1985     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1986                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1987                                         DAG.getConstant(DstOff, MVT::i32)),
1988                             DstSV, DstSVOff + DstOff);
1989     ++i;
1990     DstOff += VTSize;
1991     BytesLeft -= VTSize;
1992   }
1993   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1994 }
1995
1996 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1997   SDValue Op = N->getOperand(0);
1998   DebugLoc dl = N->getDebugLoc();
1999   if (N->getValueType(0) == MVT::f64) {
2000     // Turn i64->f64 into FMDRR.
2001     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2002                              DAG.getConstant(0, MVT::i32));
2003     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2004                              DAG.getConstant(1, MVT::i32));
2005     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
2006   }
2007
2008   // Turn f64->i64 into FMRRD.
2009   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
2010                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
2011
2012   // Merge the pieces into a single i64 value.
2013   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
2014 }
2015
2016 /// getZeroVector - Returns a vector of specified type with all zero elements.
2017 ///
2018 static SDValue getZeroVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2019   assert(VT.isVector() && "Expected a vector type");
2020
2021   // Zero vectors are used to represent vector negation and in those cases
2022   // will be implemented with the NEON VNEG instruction.  However, VNEG does
2023   // not support i64 elements, so sometimes the zero vectors will need to be
2024   // explicitly constructed.  For those cases, and potentially other uses in
2025   // the future, always build zero vectors as <4 x i32> or <2 x i32> bitcasted
2026   // to their dest type.  This ensures they get CSE'd.
2027   SDValue Vec;
2028   SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2029   if (VT.getSizeInBits() == 64)
2030     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2031   else
2032     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2033
2034   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2035 }
2036
2037 /// getOnesVector - Returns a vector of specified type with all bits set.
2038 ///
2039 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2040   assert(VT.isVector() && "Expected a vector type");
2041
2042   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2043   // type.  This ensures they get CSE'd.
2044   SDValue Vec;
2045   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2046   if (VT.getSizeInBits() == 64)
2047     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2048   else
2049     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2050
2051   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2052 }
2053
2054 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
2055                           const ARMSubtarget *ST) {
2056   MVT VT = N->getValueType(0);
2057   DebugLoc dl = N->getDebugLoc();
2058
2059   // Lower vector shifts on NEON to use VSHL.
2060   if (VT.isVector()) {
2061     assert(ST->hasNEON() && "unexpected vector shift");
2062
2063     // Left shifts translate directly to the vshiftu intrinsic.
2064     if (N->getOpcode() == ISD::SHL)
2065       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2066                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2067                          N->getOperand(0), N->getOperand(1));
2068
2069     assert((N->getOpcode() == ISD::SRA ||
2070             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2071
2072     // NEON uses the same intrinsics for both left and right shifts.  For
2073     // right shifts, the shift amounts are negative, so negate the vector of
2074     // shift amounts.
2075     MVT ShiftVT = N->getOperand(1).getValueType();
2076     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2077                                        getZeroVector(ShiftVT, DAG, dl),
2078                                        N->getOperand(1));
2079     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2080                                Intrinsic::arm_neon_vshifts :
2081                                Intrinsic::arm_neon_vshiftu);
2082     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2083                        DAG.getConstant(vshiftInt, MVT::i32),
2084                        N->getOperand(0), NegatedCount);
2085   }
2086
2087   assert(VT == MVT::i64 &&
2088          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2089          "Unknown shift to lower!");
2090
2091   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2092   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2093       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2094     return SDValue();
2095
2096   // If we are in thumb mode, we don't have RRX.
2097   if (ST->isThumb1Only()) return SDValue();
2098
2099   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2100   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2101                              DAG.getConstant(0, MVT::i32));
2102   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2103                              DAG.getConstant(1, MVT::i32));
2104
2105   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2106   // captures the result into a carry flag.
2107   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2108   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2109
2110   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2111   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2112
2113   // Merge the pieces into a single i64 value.
2114  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2115 }
2116
2117 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2118   SDValue TmpOp0, TmpOp1;
2119   bool Invert = false;
2120   bool Swap = false;
2121   unsigned Opc = 0;
2122
2123   SDValue Op0 = Op.getOperand(0);
2124   SDValue Op1 = Op.getOperand(1);
2125   SDValue CC = Op.getOperand(2);
2126   MVT VT = Op.getValueType();
2127   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2128   DebugLoc dl = Op.getDebugLoc();
2129
2130   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2131     switch (SetCCOpcode) {
2132     default: llvm_unreachable("Illegal FP comparison"); break;
2133     case ISD::SETUNE:
2134     case ISD::SETNE:  Invert = true; // Fallthrough
2135     case ISD::SETOEQ:
2136     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2137     case ISD::SETOLT:
2138     case ISD::SETLT: Swap = true; // Fallthrough
2139     case ISD::SETOGT:
2140     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2141     case ISD::SETOLE:
2142     case ISD::SETLE:  Swap = true; // Fallthrough
2143     case ISD::SETOGE:
2144     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2145     case ISD::SETUGE: Swap = true; // Fallthrough
2146     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2147     case ISD::SETUGT: Swap = true; // Fallthrough
2148     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2149     case ISD::SETUEQ: Invert = true; // Fallthrough
2150     case ISD::SETONE:
2151       // Expand this to (OLT | OGT).
2152       TmpOp0 = Op0;
2153       TmpOp1 = Op1;
2154       Opc = ISD::OR;
2155       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2156       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2157       break;
2158     case ISD::SETUO: Invert = true; // Fallthrough
2159     case ISD::SETO:
2160       // Expand this to (OLT | OGE).
2161       TmpOp0 = Op0;
2162       TmpOp1 = Op1;
2163       Opc = ISD::OR;
2164       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2165       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2166       break;
2167     }
2168   } else {
2169     // Integer comparisons.
2170     switch (SetCCOpcode) {
2171     default: llvm_unreachable("Illegal integer comparison"); break;
2172     case ISD::SETNE:  Invert = true;
2173     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2174     case ISD::SETLT:  Swap = true;
2175     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2176     case ISD::SETLE:  Swap = true;
2177     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2178     case ISD::SETULT: Swap = true;
2179     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2180     case ISD::SETULE: Swap = true;
2181     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2182     }
2183
2184     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2185     if (Opc == ARMISD::VCEQ) {
2186
2187       SDValue AndOp;
2188       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2189         AndOp = Op0;
2190       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2191         AndOp = Op1;
2192
2193       // Ignore bitconvert.
2194       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2195         AndOp = AndOp.getOperand(0);
2196
2197       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2198         Opc = ARMISD::VTST;
2199         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2200         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2201         Invert = !Invert;
2202       }
2203     }
2204   }
2205
2206   if (Swap)
2207     std::swap(Op0, Op1);
2208
2209   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2210
2211   if (Invert)
2212     Result = DAG.getNOT(dl, Result, VT);
2213
2214   return Result;
2215 }
2216
2217 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2218 /// VMOV instruction, and if so, return the constant being splatted.
2219 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2220                            unsigned SplatBitSize, SelectionDAG &DAG) {
2221   switch (SplatBitSize) {
2222   case 8:
2223     // Any 1-byte value is OK.
2224     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2225     return DAG.getTargetConstant(SplatBits, MVT::i8);
2226
2227   case 16:
2228     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2229     if ((SplatBits & ~0xff) == 0 ||
2230         (SplatBits & ~0xff00) == 0)
2231       return DAG.getTargetConstant(SplatBits, MVT::i16);
2232     break;
2233
2234   case 32:
2235     // NEON's 32-bit VMOV supports splat values where:
2236     // * only one byte is nonzero, or
2237     // * the least significant byte is 0xff and the second byte is nonzero, or
2238     // * the least significant 2 bytes are 0xff and the third is nonzero.
2239     if ((SplatBits & ~0xff) == 0 ||
2240         (SplatBits & ~0xff00) == 0 ||
2241         (SplatBits & ~0xff0000) == 0 ||
2242         (SplatBits & ~0xff000000) == 0)
2243       return DAG.getTargetConstant(SplatBits, MVT::i32);
2244
2245     if ((SplatBits & ~0xffff) == 0 &&
2246         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2247       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2248
2249     if ((SplatBits & ~0xffffff) == 0 &&
2250         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2251       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2252
2253     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2254     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2255     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2256     // and fall through here to test for a valid 64-bit splat.  But, then the
2257     // caller would also need to check and handle the change in size.
2258     break;
2259
2260   case 64: {
2261     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2262     uint64_t BitMask = 0xff;
2263     uint64_t Val = 0;
2264     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2265       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2266         Val |= BitMask;
2267       else if ((SplatBits & BitMask) != 0)
2268         return SDValue();
2269       BitMask <<= 8;
2270     }
2271     return DAG.getTargetConstant(Val, MVT::i64);
2272   }
2273
2274   default:
2275     llvm_unreachable("unexpected size for isVMOVSplat");
2276     break;
2277   }
2278
2279   return SDValue();
2280 }
2281
2282 /// getVMOVImm - If this is a build_vector of constants which can be
2283 /// formed by using a VMOV instruction of the specified element size,
2284 /// return the constant being splatted.  The ByteSize field indicates the
2285 /// number of bytes of each element [1248].
2286 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2287   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2288   APInt SplatBits, SplatUndef;
2289   unsigned SplatBitSize;
2290   bool HasAnyUndefs;
2291   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2292                                       HasAnyUndefs, ByteSize * 8))
2293     return SDValue();
2294
2295   if (SplatBitSize > ByteSize * 8)
2296     return SDValue();
2297
2298   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2299                      SplatBitSize, DAG);
2300 }
2301
2302 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2303 /// instruction with the specified blocksize.  (The order of the elements
2304 /// within each block of the vector is reversed.)
2305 bool ARM::isVREVMask(ShuffleVectorSDNode *N, unsigned BlockSize) {
2306   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2307          "Only possible block sizes for VREV are: 16, 32, 64");
2308
2309   MVT VT = N->getValueType(0);
2310   unsigned NumElts = VT.getVectorNumElements();
2311   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2312   unsigned BlockElts = N->getMaskElt(0) + 1;
2313
2314   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2315     return false;
2316
2317   for (unsigned i = 0; i < NumElts; ++i) {
2318     if ((unsigned) N->getMaskElt(i) !=
2319         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2320       return false;
2321   }
2322
2323   return true;
2324 }
2325
2326 static SDValue BuildSplat(SDValue Val, MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2327   // Canonicalize all-zeros and all-ones vectors.
2328   ConstantSDNode *ConstVal = dyn_cast<ConstantSDNode>(Val.getNode());
2329   if (ConstVal->isNullValue())
2330     return getZeroVector(VT, DAG, dl);
2331   if (ConstVal->isAllOnesValue())
2332     return getOnesVector(VT, DAG, dl);
2333
2334   MVT CanonicalVT;
2335   if (VT.is64BitVector()) {
2336     switch (Val.getValueType().getSizeInBits()) {
2337     case 8:  CanonicalVT = MVT::v8i8; break;
2338     case 16: CanonicalVT = MVT::v4i16; break;
2339     case 32: CanonicalVT = MVT::v2i32; break;
2340     case 64: CanonicalVT = MVT::v1i64; break;
2341     default: llvm_unreachable("unexpected splat element type"); break;
2342     }
2343   } else {
2344     assert(VT.is128BitVector() && "unknown splat vector size");
2345     switch (Val.getValueType().getSizeInBits()) {
2346     case 8:  CanonicalVT = MVT::v16i8; break;
2347     case 16: CanonicalVT = MVT::v8i16; break;
2348     case 32: CanonicalVT = MVT::v4i32; break;
2349     case 64: CanonicalVT = MVT::v2i64; break;
2350     default: llvm_unreachable("unexpected splat element type"); break;
2351     }
2352   }
2353
2354   // Build a canonical splat for this value.
2355   SmallVector<SDValue, 8> Ops;
2356   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2357   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2358                             Ops.size());
2359   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2360 }
2361
2362 // If this is a case we can't handle, return null and let the default
2363 // expansion code take care of it.
2364 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2365   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2366   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
2367   DebugLoc dl = Op.getDebugLoc();
2368   MVT VT = Op.getValueType();
2369
2370   APInt SplatBits, SplatUndef;
2371   unsigned SplatBitSize;
2372   bool HasAnyUndefs;
2373   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2374     SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2375                               SplatUndef.getZExtValue(), SplatBitSize, DAG);
2376     if (Val.getNode())
2377       return BuildSplat(Val, VT, DAG, dl);
2378   }
2379
2380   // If there are only 2 elements in a 128-bit vector, insert them into an
2381   // undef vector.  This handles the common case for 128-bit vector argument
2382   // passing, where the insertions should be translated to subreg accesses
2383   // with no real instructions.
2384   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2385     SDValue Val = DAG.getUNDEF(VT);
2386     SDValue Op0 = Op.getOperand(0);
2387     SDValue Op1 = Op.getOperand(1);
2388     if (Op0.getOpcode() != ISD::UNDEF)
2389       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2390                         DAG.getIntPtrConstant(0));
2391     if (Op1.getOpcode() != ISD::UNDEF)
2392       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2393                         DAG.getIntPtrConstant(1));
2394     return Val;
2395   }
2396
2397   return SDValue();
2398 }
2399
2400 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2401   return Op;
2402 }
2403
2404 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
2405   return Op;
2406 }
2407
2408 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2409   MVT VT = Op.getValueType();
2410   DebugLoc dl = Op.getDebugLoc();
2411   assert((VT == MVT::i8 || VT == MVT::i16) &&
2412          "unexpected type for custom-lowering vector extract");
2413   SDValue Vec = Op.getOperand(0);
2414   SDValue Lane = Op.getOperand(1);
2415   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2416   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2417   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2418 }
2419
2420 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2421   // The only time a CONCAT_VECTORS operation can have legal types is when
2422   // two 64-bit vectors are concatenated to a 128-bit vector.
2423   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
2424          "unexpected CONCAT_VECTORS");
2425   DebugLoc dl = Op.getDebugLoc();
2426   SDValue Val = DAG.getUNDEF(MVT::v2f64);
2427   SDValue Op0 = Op.getOperand(0);
2428   SDValue Op1 = Op.getOperand(1);
2429   if (Op0.getOpcode() != ISD::UNDEF)
2430     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2431                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
2432                       DAG.getIntPtrConstant(0));
2433   if (Op1.getOpcode() != ISD::UNDEF)
2434     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2435                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
2436                       DAG.getIntPtrConstant(1));
2437   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
2438 }
2439
2440 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2441   switch (Op.getOpcode()) {
2442   default: llvm_unreachable("Don't know how to custom lower this!");
2443   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2444   case ISD::GlobalAddress:
2445     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2446       LowerGlobalAddressELF(Op, DAG);
2447   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2448   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2449   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2450   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2451   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
2452   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2453   case ISD::SINT_TO_FP:
2454   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2455   case ISD::FP_TO_SINT:
2456   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2457   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2458   case ISD::RETURNADDR:    break;
2459   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2460   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2461   case ISD::INTRINSIC_VOID:
2462   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2463   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2464   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2465   case ISD::SHL:
2466   case ISD::SRL:
2467   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2468   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2469   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2470   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2471   case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
2472   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2473   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
2474   }
2475   return SDValue();
2476 }
2477
2478 /// ReplaceNodeResults - Replace the results of node with an illegal result
2479 /// type with new values built out of custom code.
2480 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2481                                            SmallVectorImpl<SDValue>&Results,
2482                                            SelectionDAG &DAG) {
2483   switch (N->getOpcode()) {
2484   default:
2485     llvm_unreachable("Don't know how to custom expand this!");
2486     return;
2487   case ISD::BIT_CONVERT:
2488     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2489     return;
2490   case ISD::SRL:
2491   case ISD::SRA: {
2492     SDValue Res = LowerShift(N, DAG, Subtarget);
2493     if (Res.getNode())
2494       Results.push_back(Res);
2495     return;
2496   }
2497   }
2498 }
2499
2500 //===----------------------------------------------------------------------===//
2501 //                           ARM Scheduler Hooks
2502 //===----------------------------------------------------------------------===//
2503
2504 MachineBasicBlock *
2505 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2506                                                MachineBasicBlock *BB) const {
2507   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2508   DebugLoc dl = MI->getDebugLoc();
2509   switch (MI->getOpcode()) {
2510   default:
2511     llvm_unreachable("Unexpected instr type to insert");
2512   case ARM::tMOVCCr: {
2513     // To "insert" a SELECT_CC instruction, we actually have to insert the
2514     // diamond control-flow pattern.  The incoming instruction knows the
2515     // destination vreg to set, the condition code register to branch on, the
2516     // true/false values to select between, and a branch opcode to use.
2517     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2518     MachineFunction::iterator It = BB;
2519     ++It;
2520
2521     //  thisMBB:
2522     //  ...
2523     //   TrueVal = ...
2524     //   cmpTY ccX, r1, r2
2525     //   bCC copy1MBB
2526     //   fallthrough --> copy0MBB
2527     MachineBasicBlock *thisMBB  = BB;
2528     MachineFunction *F = BB->getParent();
2529     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2530     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2531     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2532       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2533     F->insert(It, copy0MBB);
2534     F->insert(It, sinkMBB);
2535     // Update machine-CFG edges by first adding all successors of the current
2536     // block to the new block which will contain the Phi node for the select.
2537     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2538         e = BB->succ_end(); i != e; ++i)
2539       sinkMBB->addSuccessor(*i);
2540     // Next, remove all successors of the current block, and add the true
2541     // and fallthrough blocks as its successors.
2542     while(!BB->succ_empty())
2543       BB->removeSuccessor(BB->succ_begin());
2544     BB->addSuccessor(copy0MBB);
2545     BB->addSuccessor(sinkMBB);
2546
2547     //  copy0MBB:
2548     //   %FalseValue = ...
2549     //   # fallthrough to sinkMBB
2550     BB = copy0MBB;
2551
2552     // Update machine-CFG edges
2553     BB->addSuccessor(sinkMBB);
2554
2555     //  sinkMBB:
2556     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2557     //  ...
2558     BB = sinkMBB;
2559     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2560       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2561       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2562
2563     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2564     return BB;
2565   }
2566
2567   case ARM::tANDsp:
2568   case ARM::tADDspr_:
2569   case ARM::tSUBspi_:
2570   case ARM::t2SUBrSPi_:
2571   case ARM::t2SUBrSPi12_:
2572   case ARM::t2SUBrSPs_: {
2573     MachineFunction *MF = BB->getParent();
2574     unsigned DstReg = MI->getOperand(0).getReg();
2575     unsigned SrcReg = MI->getOperand(1).getReg();
2576     bool DstIsDead = MI->getOperand(0).isDead();
2577     bool SrcIsKill = MI->getOperand(1).isKill();
2578
2579     if (SrcReg != ARM::SP) {
2580       // Copy the source to SP from virtual register.
2581       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(SrcReg);
2582       unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2583         ? ARM::tMOVtgpr2gpr : ARM::tMOVgpr2gpr;
2584       BuildMI(BB, dl, TII->get(CopyOpc), ARM::SP)
2585         .addReg(SrcReg, getKillRegState(SrcIsKill));
2586     }
2587
2588     unsigned OpOpc = 0;
2589     bool NeedPred = false, NeedCC = false, NeedOp3 = false;
2590     switch (MI->getOpcode()) {
2591     default:
2592       llvm_unreachable("Unexpected pseudo instruction!");
2593     case ARM::tANDsp:
2594       OpOpc = ARM::tAND;
2595       NeedPred = true;
2596       break;
2597     case ARM::tADDspr_:
2598       OpOpc = ARM::tADDspr;
2599       break;
2600     case ARM::tSUBspi_:
2601       OpOpc = ARM::tSUBspi;
2602       break;
2603     case ARM::t2SUBrSPi_:
2604       OpOpc = ARM::t2SUBrSPi;
2605       NeedPred = true; NeedCC = true;
2606       break;
2607     case ARM::t2SUBrSPi12_:
2608       OpOpc = ARM::t2SUBrSPi12;
2609       NeedPred = true;
2610       break;
2611     case ARM::t2SUBrSPs_:
2612       OpOpc = ARM::t2SUBrSPs;
2613       NeedPred = true; NeedCC = true; NeedOp3 = true;
2614       break;
2615     }
2616     MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(OpOpc), ARM::SP);
2617     if (OpOpc == ARM::tAND)
2618       AddDefaultT1CC(MIB);
2619     MIB.addReg(ARM::SP);
2620     MIB.addOperand(MI->getOperand(2));
2621     if (NeedOp3)
2622       MIB.addOperand(MI->getOperand(3));
2623     if (NeedPred)
2624       AddDefaultPred(MIB);
2625     if (NeedCC)
2626       AddDefaultCC(MIB);
2627
2628     // Copy the result from SP to virtual register.
2629     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(DstReg);
2630     unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2631       ? ARM::tMOVgpr2tgpr : ARM::tMOVgpr2gpr;
2632     BuildMI(BB, dl, TII->get(CopyOpc))
2633       .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstIsDead))
2634       .addReg(ARM::SP);
2635     MF->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2636     return BB;
2637   }
2638   }
2639 }
2640
2641 //===----------------------------------------------------------------------===//
2642 //                           ARM Optimization Hooks
2643 //===----------------------------------------------------------------------===//
2644
2645 static
2646 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
2647                             TargetLowering::DAGCombinerInfo &DCI) {
2648   SelectionDAG &DAG = DCI.DAG;
2649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2650   MVT VT = N->getValueType(0);
2651   unsigned Opc = N->getOpcode();
2652   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
2653   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
2654   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
2655   ISD::CondCode CC = ISD::SETCC_INVALID;
2656
2657   if (isSlctCC) {
2658     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
2659   } else {
2660     SDValue CCOp = Slct.getOperand(0);
2661     if (CCOp.getOpcode() == ISD::SETCC)
2662       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
2663   }
2664
2665   bool DoXform = false;
2666   bool InvCC = false;
2667   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
2668           "Bad input!");
2669
2670   if (LHS.getOpcode() == ISD::Constant &&
2671       cast<ConstantSDNode>(LHS)->isNullValue()) {
2672     DoXform = true;
2673   } else if (CC != ISD::SETCC_INVALID &&
2674              RHS.getOpcode() == ISD::Constant &&
2675              cast<ConstantSDNode>(RHS)->isNullValue()) {
2676     std::swap(LHS, RHS);
2677     SDValue Op0 = Slct.getOperand(0);
2678     MVT OpVT = isSlctCC ? Op0.getValueType() :
2679                           Op0.getOperand(0).getValueType();
2680     bool isInt = OpVT.isInteger();
2681     CC = ISD::getSetCCInverse(CC, isInt);
2682
2683     if (!TLI.isCondCodeLegal(CC, OpVT))
2684       return SDValue();         // Inverse operator isn't legal.
2685
2686     DoXform = true;
2687     InvCC = true;
2688   }
2689
2690   if (DoXform) {
2691     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
2692     if (isSlctCC)
2693       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
2694                              Slct.getOperand(0), Slct.getOperand(1), CC);
2695     SDValue CCOp = Slct.getOperand(0);
2696     if (InvCC)
2697       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
2698                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
2699     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
2700                        CCOp, OtherOp, Result);
2701   }
2702   return SDValue();
2703 }
2704
2705 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
2706 static SDValue PerformADDCombine(SDNode *N,
2707                                  TargetLowering::DAGCombinerInfo &DCI) {
2708   // added by evan in r37685 with no testcase.
2709   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2710
2711   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
2712   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
2713     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
2714     if (Result.getNode()) return Result;
2715   }
2716   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2717     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2718     if (Result.getNode()) return Result;
2719   }
2720
2721   return SDValue();
2722 }
2723
2724 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
2725 static SDValue PerformSUBCombine(SDNode *N,
2726                                  TargetLowering::DAGCombinerInfo &DCI) {
2727   // added by evan in r37685 with no testcase.
2728   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2729
2730   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
2731   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2732     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2733     if (Result.getNode()) return Result;
2734   }
2735
2736   return SDValue();
2737 }
2738
2739
2740 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
2741 static SDValue PerformFMRRDCombine(SDNode *N,
2742                                    TargetLowering::DAGCombinerInfo &DCI) {
2743   // fmrrd(fmdrr x, y) -> x,y
2744   SDValue InDouble = N->getOperand(0);
2745   if (InDouble.getOpcode() == ARMISD::FMDRR)
2746     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
2747   return SDValue();
2748 }
2749
2750 /// getVShiftImm - Check if this is a valid build_vector for the immediate
2751 /// operand of a vector shift operation, where all the elements of the
2752 /// build_vector must have the same constant integer value.
2753 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
2754   // Ignore bit_converts.
2755   while (Op.getOpcode() == ISD::BIT_CONVERT)
2756     Op = Op.getOperand(0);
2757   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
2758   APInt SplatBits, SplatUndef;
2759   unsigned SplatBitSize;
2760   bool HasAnyUndefs;
2761   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2762                                       HasAnyUndefs, ElementBits) ||
2763       SplatBitSize > ElementBits)
2764     return false;
2765   Cnt = SplatBits.getSExtValue();
2766   return true;
2767 }
2768
2769 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
2770 /// operand of a vector shift left operation.  That value must be in the range:
2771 ///   0 <= Value < ElementBits for a left shift; or
2772 ///   0 <= Value <= ElementBits for a long left shift.
2773 static bool isVShiftLImm(SDValue Op, MVT VT, bool isLong, int64_t &Cnt) {
2774   assert(VT.isVector() && "vector shift count is not a vector type");
2775   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2776   if (! getVShiftImm(Op, ElementBits, Cnt))
2777     return false;
2778   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
2779 }
2780
2781 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
2782 /// operand of a vector shift right operation.  For a shift opcode, the value
2783 /// is positive, but for an intrinsic the value count must be negative. The
2784 /// absolute value must be in the range:
2785 ///   1 <= |Value| <= ElementBits for a right shift; or
2786 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
2787 static bool isVShiftRImm(SDValue Op, MVT VT, bool isNarrow, bool isIntrinsic,
2788                          int64_t &Cnt) {
2789   assert(VT.isVector() && "vector shift count is not a vector type");
2790   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
2791   if (! getVShiftImm(Op, ElementBits, Cnt))
2792     return false;
2793   if (isIntrinsic)
2794     Cnt = -Cnt;
2795   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
2796 }
2797
2798 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
2799 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
2800   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2801   switch (IntNo) {
2802   default:
2803     // Don't do anything for most intrinsics.
2804     break;
2805
2806   // Vector shifts: check for immediate versions and lower them.
2807   // Note: This is done during DAG combining instead of DAG legalizing because
2808   // the build_vectors for 64-bit vector element shift counts are generally
2809   // not legal, and it is hard to see their values after they get legalized to
2810   // loads from a constant pool.
2811   case Intrinsic::arm_neon_vshifts:
2812   case Intrinsic::arm_neon_vshiftu:
2813   case Intrinsic::arm_neon_vshiftls:
2814   case Intrinsic::arm_neon_vshiftlu:
2815   case Intrinsic::arm_neon_vshiftn:
2816   case Intrinsic::arm_neon_vrshifts:
2817   case Intrinsic::arm_neon_vrshiftu:
2818   case Intrinsic::arm_neon_vrshiftn:
2819   case Intrinsic::arm_neon_vqshifts:
2820   case Intrinsic::arm_neon_vqshiftu:
2821   case Intrinsic::arm_neon_vqshiftsu:
2822   case Intrinsic::arm_neon_vqshiftns:
2823   case Intrinsic::arm_neon_vqshiftnu:
2824   case Intrinsic::arm_neon_vqshiftnsu:
2825   case Intrinsic::arm_neon_vqrshiftns:
2826   case Intrinsic::arm_neon_vqrshiftnu:
2827   case Intrinsic::arm_neon_vqrshiftnsu: {
2828     MVT VT = N->getOperand(1).getValueType();
2829     int64_t Cnt;
2830     unsigned VShiftOpc = 0;
2831
2832     switch (IntNo) {
2833     case Intrinsic::arm_neon_vshifts:
2834     case Intrinsic::arm_neon_vshiftu:
2835       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
2836         VShiftOpc = ARMISD::VSHL;
2837         break;
2838       }
2839       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
2840         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
2841                      ARMISD::VSHRs : ARMISD::VSHRu);
2842         break;
2843       }
2844       return SDValue();
2845
2846     case Intrinsic::arm_neon_vshiftls:
2847     case Intrinsic::arm_neon_vshiftlu:
2848       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
2849         break;
2850       llvm_unreachable("invalid shift count for vshll intrinsic");
2851
2852     case Intrinsic::arm_neon_vrshifts:
2853     case Intrinsic::arm_neon_vrshiftu:
2854       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
2855         break;
2856       return SDValue();
2857
2858     case Intrinsic::arm_neon_vqshifts:
2859     case Intrinsic::arm_neon_vqshiftu:
2860       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2861         break;
2862       return SDValue();
2863
2864     case Intrinsic::arm_neon_vqshiftsu:
2865       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
2866         break;
2867       llvm_unreachable("invalid shift count for vqshlu intrinsic");
2868
2869     case Intrinsic::arm_neon_vshiftn:
2870     case Intrinsic::arm_neon_vrshiftn:
2871     case Intrinsic::arm_neon_vqshiftns:
2872     case Intrinsic::arm_neon_vqshiftnu:
2873     case Intrinsic::arm_neon_vqshiftnsu:
2874     case Intrinsic::arm_neon_vqrshiftns:
2875     case Intrinsic::arm_neon_vqrshiftnu:
2876     case Intrinsic::arm_neon_vqrshiftnsu:
2877       // Narrowing shifts require an immediate right shift.
2878       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
2879         break;
2880       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
2881
2882     default:
2883       llvm_unreachable("unhandled vector shift");
2884     }
2885
2886     switch (IntNo) {
2887     case Intrinsic::arm_neon_vshifts:
2888     case Intrinsic::arm_neon_vshiftu:
2889       // Opcode already set above.
2890       break;
2891     case Intrinsic::arm_neon_vshiftls:
2892     case Intrinsic::arm_neon_vshiftlu:
2893       if (Cnt == VT.getVectorElementType().getSizeInBits())
2894         VShiftOpc = ARMISD::VSHLLi;
2895       else
2896         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
2897                      ARMISD::VSHLLs : ARMISD::VSHLLu);
2898       break;
2899     case Intrinsic::arm_neon_vshiftn:
2900       VShiftOpc = ARMISD::VSHRN; break;
2901     case Intrinsic::arm_neon_vrshifts:
2902       VShiftOpc = ARMISD::VRSHRs; break;
2903     case Intrinsic::arm_neon_vrshiftu:
2904       VShiftOpc = ARMISD::VRSHRu; break;
2905     case Intrinsic::arm_neon_vrshiftn:
2906       VShiftOpc = ARMISD::VRSHRN; break;
2907     case Intrinsic::arm_neon_vqshifts:
2908       VShiftOpc = ARMISD::VQSHLs; break;
2909     case Intrinsic::arm_neon_vqshiftu:
2910       VShiftOpc = ARMISD::VQSHLu; break;
2911     case Intrinsic::arm_neon_vqshiftsu:
2912       VShiftOpc = ARMISD::VQSHLsu; break;
2913     case Intrinsic::arm_neon_vqshiftns:
2914       VShiftOpc = ARMISD::VQSHRNs; break;
2915     case Intrinsic::arm_neon_vqshiftnu:
2916       VShiftOpc = ARMISD::VQSHRNu; break;
2917     case Intrinsic::arm_neon_vqshiftnsu:
2918       VShiftOpc = ARMISD::VQSHRNsu; break;
2919     case Intrinsic::arm_neon_vqrshiftns:
2920       VShiftOpc = ARMISD::VQRSHRNs; break;
2921     case Intrinsic::arm_neon_vqrshiftnu:
2922       VShiftOpc = ARMISD::VQRSHRNu; break;
2923     case Intrinsic::arm_neon_vqrshiftnsu:
2924       VShiftOpc = ARMISD::VQRSHRNsu; break;
2925     }
2926
2927     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2928                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
2929   }
2930
2931   case Intrinsic::arm_neon_vshiftins: {
2932     MVT VT = N->getOperand(1).getValueType();
2933     int64_t Cnt;
2934     unsigned VShiftOpc = 0;
2935
2936     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
2937       VShiftOpc = ARMISD::VSLI;
2938     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
2939       VShiftOpc = ARMISD::VSRI;
2940     else {
2941       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
2942     }
2943
2944     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
2945                        N->getOperand(1), N->getOperand(2),
2946                        DAG.getConstant(Cnt, MVT::i32));
2947   }
2948
2949   case Intrinsic::arm_neon_vqrshifts:
2950   case Intrinsic::arm_neon_vqrshiftu:
2951     // No immediate versions of these to check for.
2952     break;
2953   }
2954
2955   return SDValue();
2956 }
2957
2958 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
2959 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
2960 /// combining instead of DAG legalizing because the build_vectors for 64-bit
2961 /// vector element shift counts are generally not legal, and it is hard to see
2962 /// their values after they get legalized to loads from a constant pool.
2963 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
2964                                    const ARMSubtarget *ST) {
2965   MVT VT = N->getValueType(0);
2966
2967   // Nothing to be done for scalar shifts.
2968   if (! VT.isVector())
2969     return SDValue();
2970
2971   assert(ST->hasNEON() && "unexpected vector shift");
2972   int64_t Cnt;
2973
2974   switch (N->getOpcode()) {
2975   default: llvm_unreachable("unexpected shift opcode");
2976
2977   case ISD::SHL:
2978     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
2979       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
2980                          DAG.getConstant(Cnt, MVT::i32));
2981     break;
2982
2983   case ISD::SRA:
2984   case ISD::SRL:
2985     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
2986       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
2987                             ARMISD::VSHRs : ARMISD::VSHRu);
2988       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
2989                          DAG.getConstant(Cnt, MVT::i32));
2990     }
2991   }
2992   return SDValue();
2993 }
2994
2995 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
2996 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
2997 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
2998                                     const ARMSubtarget *ST) {
2999   SDValue N0 = N->getOperand(0);
3000
3001   // Check for sign- and zero-extensions of vector extract operations of 8-
3002   // and 16-bit vector elements.  NEON supports these directly.  They are
3003   // handled during DAG combining because type legalization will promote them
3004   // to 32-bit types and it is messy to recognize the operations after that.
3005   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3006     SDValue Vec = N0.getOperand(0);
3007     SDValue Lane = N0.getOperand(1);
3008     MVT VT = N->getValueType(0);
3009     MVT EltVT = N0.getValueType();
3010     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3011
3012     if (VT == MVT::i32 &&
3013         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
3014         TLI.isTypeLegal(Vec.getValueType())) {
3015
3016       unsigned Opc = 0;
3017       switch (N->getOpcode()) {
3018       default: llvm_unreachable("unexpected opcode");
3019       case ISD::SIGN_EXTEND:
3020         Opc = ARMISD::VGETLANEs;
3021         break;
3022       case ISD::ZERO_EXTEND:
3023       case ISD::ANY_EXTEND:
3024         Opc = ARMISD::VGETLANEu;
3025         break;
3026       }
3027       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
3028     }
3029   }
3030
3031   return SDValue();
3032 }
3033
3034 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
3035                                              DAGCombinerInfo &DCI) const {
3036   switch (N->getOpcode()) {
3037   default: break;
3038   case ISD::ADD:      return PerformADDCombine(N, DCI);
3039   case ISD::SUB:      return PerformSUBCombine(N, DCI);
3040   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
3041   case ISD::INTRINSIC_WO_CHAIN:
3042     return PerformIntrinsicCombine(N, DCI.DAG);
3043   case ISD::SHL:
3044   case ISD::SRA:
3045   case ISD::SRL:
3046     return PerformShiftCombine(N, DCI.DAG, Subtarget);
3047   case ISD::SIGN_EXTEND:
3048   case ISD::ZERO_EXTEND:
3049   case ISD::ANY_EXTEND:
3050     return PerformExtendCombine(N, DCI.DAG, Subtarget);
3051   }
3052   return SDValue();
3053 }
3054
3055 /// isLegalAddressImmediate - Return true if the integer value can be used
3056 /// as the offset of the target addressing mode for load / store of the
3057 /// given type.
3058 static bool isLegalAddressImmediate(int64_t V, MVT VT,
3059                                     const ARMSubtarget *Subtarget) {
3060   if (V == 0)
3061     return true;
3062
3063   if (!VT.isSimple())
3064     return false;
3065
3066   if (Subtarget->isThumb()) { // FIXME for thumb2
3067     if (V < 0)
3068       return false;
3069
3070     unsigned Scale = 1;
3071     switch (VT.getSimpleVT()) {
3072     default: return false;
3073     case MVT::i1:
3074     case MVT::i8:
3075       // Scale == 1;
3076       break;
3077     case MVT::i16:
3078       // Scale == 2;
3079       Scale = 2;
3080       break;
3081     case MVT::i32:
3082       // Scale == 4;
3083       Scale = 4;
3084       break;
3085     }
3086
3087     if ((V & (Scale - 1)) != 0)
3088       return false;
3089     V /= Scale;
3090     return V == (V & ((1LL << 5) - 1));
3091   }
3092
3093   if (V < 0)
3094     V = - V;
3095   switch (VT.getSimpleVT()) {
3096   default: return false;
3097   case MVT::i1:
3098   case MVT::i8:
3099   case MVT::i32:
3100     // +- imm12
3101     return V == (V & ((1LL << 12) - 1));
3102   case MVT::i16:
3103     // +- imm8
3104     return V == (V & ((1LL << 8) - 1));
3105   case MVT::f32:
3106   case MVT::f64:
3107     if (!Subtarget->hasVFP2())
3108       return false;
3109     if ((V & 3) != 0)
3110       return false;
3111     V >>= 2;
3112     return V == (V & ((1LL << 8) - 1));
3113   }
3114 }
3115
3116 /// isLegalAddressingMode - Return true if the addressing mode represented
3117 /// by AM is legal for this target, for a load/store of the specified type.
3118 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3119                                               const Type *Ty) const {
3120   MVT VT = getValueType(Ty, true);
3121   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
3122     return false;
3123
3124   // Can never fold addr of global into load/store.
3125   if (AM.BaseGV)
3126     return false;
3127
3128   switch (AM.Scale) {
3129   case 0:  // no scale reg, must be "r+i" or "r", or "i".
3130     break;
3131   case 1:
3132     if (Subtarget->isThumb())  // FIXME for thumb2
3133       return false;
3134     // FALL THROUGH.
3135   default:
3136     // ARM doesn't support any R+R*scale+imm addr modes.
3137     if (AM.BaseOffs)
3138       return false;
3139
3140     if (!VT.isSimple())
3141       return false;
3142
3143     int Scale = AM.Scale;
3144     switch (VT.getSimpleVT()) {
3145     default: return false;
3146     case MVT::i1:
3147     case MVT::i8:
3148     case MVT::i32:
3149     case MVT::i64:
3150       // This assumes i64 is legalized to a pair of i32. If not (i.e.
3151       // ldrd / strd are used, then its address mode is same as i16.
3152       // r + r
3153       if (Scale < 0) Scale = -Scale;
3154       if (Scale == 1)
3155         return true;
3156       // r + r << imm
3157       return isPowerOf2_32(Scale & ~1);
3158     case MVT::i16:
3159       // r + r
3160       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3161         return true;
3162       return false;
3163
3164     case MVT::isVoid:
3165       // Note, we allow "void" uses (basically, uses that aren't loads or
3166       // stores), because arm allows folding a scale into many arithmetic
3167       // operations.  This should be made more precise and revisited later.
3168
3169       // Allow r << imm, but the imm has to be a multiple of two.
3170       if (AM.Scale & 1) return false;
3171       return isPowerOf2_32(AM.Scale);
3172     }
3173     break;
3174   }
3175   return true;
3176 }
3177
3178 static bool getARMIndexedAddressParts(SDNode *Ptr, MVT VT,
3179                                       bool isSEXTLoad, SDValue &Base,
3180                                       SDValue &Offset, bool &isInc,
3181                                       SelectionDAG &DAG) {
3182   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3183     return false;
3184
3185   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
3186     // AddressingMode 3
3187     Base = Ptr->getOperand(0);
3188     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3189       int RHSC = (int)RHS->getZExtValue();
3190       if (RHSC < 0 && RHSC > -256) {
3191         assert(Ptr->getOpcode() == ISD::ADD);
3192         isInc = false;
3193         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3194         return true;
3195       }
3196     }
3197     isInc = (Ptr->getOpcode() == ISD::ADD);
3198     Offset = Ptr->getOperand(1);
3199     return true;
3200   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
3201     // AddressingMode 2
3202     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3203       int RHSC = (int)RHS->getZExtValue();
3204       if (RHSC < 0 && RHSC > -0x1000) {
3205         assert(Ptr->getOpcode() == ISD::ADD);
3206         isInc = false;
3207         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3208         Base = Ptr->getOperand(0);
3209         return true;
3210       }
3211     }
3212
3213     if (Ptr->getOpcode() == ISD::ADD) {
3214       isInc = true;
3215       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
3216       if (ShOpcVal != ARM_AM::no_shift) {
3217         Base = Ptr->getOperand(1);
3218         Offset = Ptr->getOperand(0);
3219       } else {
3220         Base = Ptr->getOperand(0);
3221         Offset = Ptr->getOperand(1);
3222       }
3223       return true;
3224     }
3225
3226     isInc = (Ptr->getOpcode() == ISD::ADD);
3227     Base = Ptr->getOperand(0);
3228     Offset = Ptr->getOperand(1);
3229     return true;
3230   }
3231
3232   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
3233   return false;
3234 }
3235
3236 static bool getT2IndexedAddressParts(SDNode *Ptr, MVT VT,
3237                                      bool isSEXTLoad, SDValue &Base,
3238                                      SDValue &Offset, bool &isInc,
3239                                      SelectionDAG &DAG) {
3240   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3241     return false;
3242
3243   Base = Ptr->getOperand(0);
3244   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3245     int RHSC = (int)RHS->getZExtValue();
3246     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
3247       assert(Ptr->getOpcode() == ISD::ADD);
3248       isInc = false;
3249       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3250       return true;
3251     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3252       isInc = Ptr->getOpcode() == ISD::ADD;
3253       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3254       return true;
3255     }
3256   }
3257
3258   return false;
3259 }
3260
3261 /// getPreIndexedAddressParts - returns true by value, base pointer and
3262 /// offset pointer and addressing mode by reference if the node's address
3263 /// can be legally represented as pre-indexed load / store address.
3264 bool
3265 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3266                                              SDValue &Offset,
3267                                              ISD::MemIndexedMode &AM,
3268                                              SelectionDAG &DAG) const {
3269   if (Subtarget->isThumb1Only())
3270     return false;
3271
3272   MVT VT;
3273   SDValue Ptr;
3274   bool isSEXTLoad = false;
3275   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3276     Ptr = LD->getBasePtr();
3277     VT  = LD->getMemoryVT();
3278     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3279   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3280     Ptr = ST->getBasePtr();
3281     VT  = ST->getMemoryVT();
3282   } else
3283     return false;
3284
3285   bool isInc;
3286   bool isLegal = false;
3287   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3288     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3289                                        Offset, isInc, DAG);
3290   else 
3291     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3292                                         Offset, isInc, DAG);
3293   if (!isLegal)
3294     return false;
3295
3296   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3297   return true;
3298 }
3299
3300 /// getPostIndexedAddressParts - returns true by value, base pointer and
3301 /// offset pointer and addressing mode by reference if this node can be
3302 /// combined with a load / store to form a post-indexed load / store.
3303 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3304                                                    SDValue &Base,
3305                                                    SDValue &Offset,
3306                                                    ISD::MemIndexedMode &AM,
3307                                                    SelectionDAG &DAG) const {
3308   if (Subtarget->isThumb1Only())
3309     return false;
3310
3311   MVT VT;
3312   SDValue Ptr;
3313   bool isSEXTLoad = false;
3314   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3315     VT  = LD->getMemoryVT();
3316     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3317   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3318     VT  = ST->getMemoryVT();
3319   } else
3320     return false;
3321
3322   bool isInc;
3323   bool isLegal = false;
3324   if (Subtarget->isThumb() && Subtarget->hasThumb2())
3325     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3326                                         isInc, DAG);
3327   else 
3328     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3329                                         isInc, DAG);
3330   if (!isLegal)
3331     return false;
3332
3333   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3334   return true;
3335 }
3336
3337 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3338                                                        const APInt &Mask,
3339                                                        APInt &KnownZero,
3340                                                        APInt &KnownOne,
3341                                                        const SelectionDAG &DAG,
3342                                                        unsigned Depth) const {
3343   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3344   switch (Op.getOpcode()) {
3345   default: break;
3346   case ARMISD::CMOV: {
3347     // Bits are known zero/one if known on the LHS and RHS.
3348     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3349     if (KnownZero == 0 && KnownOne == 0) return;
3350
3351     APInt KnownZeroRHS, KnownOneRHS;
3352     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3353                           KnownZeroRHS, KnownOneRHS, Depth+1);
3354     KnownZero &= KnownZeroRHS;
3355     KnownOne  &= KnownOneRHS;
3356     return;
3357   }
3358   }
3359 }
3360
3361 //===----------------------------------------------------------------------===//
3362 //                           ARM Inline Assembly Support
3363 //===----------------------------------------------------------------------===//
3364
3365 /// getConstraintType - Given a constraint letter, return the type of
3366 /// constraint it is for this target.
3367 ARMTargetLowering::ConstraintType
3368 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3369   if (Constraint.size() == 1) {
3370     switch (Constraint[0]) {
3371     default:  break;
3372     case 'l': return C_RegisterClass;
3373     case 'w': return C_RegisterClass;
3374     }
3375   }
3376   return TargetLowering::getConstraintType(Constraint);
3377 }
3378
3379 std::pair<unsigned, const TargetRegisterClass*>
3380 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3381                                                 MVT VT) const {
3382   if (Constraint.size() == 1) {
3383     // GCC RS6000 Constraint Letters
3384     switch (Constraint[0]) {
3385     case 'l':
3386       if (Subtarget->isThumb1Only())
3387         return std::make_pair(0U, ARM::tGPRRegisterClass);
3388       else
3389         return std::make_pair(0U, ARM::GPRRegisterClass);
3390     case 'r':
3391       return std::make_pair(0U, ARM::GPRRegisterClass);
3392     case 'w':
3393       if (VT == MVT::f32)
3394         return std::make_pair(0U, ARM::SPRRegisterClass);
3395       if (VT == MVT::f64)
3396         return std::make_pair(0U, ARM::DPRRegisterClass);
3397       break;
3398     }
3399   }
3400   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3401 }
3402
3403 std::vector<unsigned> ARMTargetLowering::
3404 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3405                                   MVT VT) const {
3406   if (Constraint.size() != 1)
3407     return std::vector<unsigned>();
3408
3409   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3410   default: break;
3411   case 'l':
3412     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3413                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3414                                  0);
3415   case 'r':
3416     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3417                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3418                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3419                                  ARM::R12, ARM::LR, 0);
3420   case 'w':
3421     if (VT == MVT::f32)
3422       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3423                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3424                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3425                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3426                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3427                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3428                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3429                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3430     if (VT == MVT::f64)
3431       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3432                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3433                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3434                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3435       break;
3436   }
3437
3438   return std::vector<unsigned>();
3439 }
3440
3441 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3442 /// vector.  If it is invalid, don't add anything to Ops.
3443 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3444                                                      char Constraint,
3445                                                      bool hasMemory,
3446                                                      std::vector<SDValue>&Ops,
3447                                                      SelectionDAG &DAG) const {
3448   SDValue Result(0, 0);
3449
3450   switch (Constraint) {
3451   default: break;
3452   case 'I': case 'J': case 'K': case 'L':
3453   case 'M': case 'N': case 'O':
3454     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3455     if (!C)
3456       return;
3457
3458     int64_t CVal64 = C->getSExtValue();
3459     int CVal = (int) CVal64;
3460     // None of these constraints allow values larger than 32 bits.  Check
3461     // that the value fits in an int.
3462     if (CVal != CVal64)
3463       return;
3464
3465     switch (Constraint) {
3466       case 'I':
3467         if (Subtarget->isThumb1Only()) {
3468           // This must be a constant between 0 and 255, for ADD
3469           // immediates.
3470           if (CVal >= 0 && CVal <= 255)
3471             break;
3472         } else if (Subtarget->isThumb2()) {
3473           // A constant that can be used as an immediate value in a
3474           // data-processing instruction.
3475           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3476             break;
3477         } else {
3478           // A constant that can be used as an immediate value in a
3479           // data-processing instruction.
3480           if (ARM_AM::getSOImmVal(CVal) != -1)
3481             break;
3482         }
3483         return;
3484
3485       case 'J':
3486         if (Subtarget->isThumb()) {  // FIXME thumb2
3487           // This must be a constant between -255 and -1, for negated ADD
3488           // immediates. This can be used in GCC with an "n" modifier that
3489           // prints the negated value, for use with SUB instructions. It is
3490           // not useful otherwise but is implemented for compatibility.
3491           if (CVal >= -255 && CVal <= -1)
3492             break;
3493         } else {
3494           // This must be a constant between -4095 and 4095. It is not clear
3495           // what this constraint is intended for. Implemented for
3496           // compatibility with GCC.
3497           if (CVal >= -4095 && CVal <= 4095)
3498             break;
3499         }
3500         return;
3501
3502       case 'K':
3503         if (Subtarget->isThumb1Only()) {
3504           // A 32-bit value where only one byte has a nonzero value. Exclude
3505           // zero to match GCC. This constraint is used by GCC internally for
3506           // constants that can be loaded with a move/shift combination.
3507           // It is not useful otherwise but is implemented for compatibility.
3508           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3509             break;
3510         } else if (Subtarget->isThumb2()) {
3511           // A constant whose bitwise inverse can be used as an immediate
3512           // value in a data-processing instruction. This can be used in GCC
3513           // with a "B" modifier that prints the inverted value, for use with
3514           // BIC and MVN instructions. It is not useful otherwise but is
3515           // implemented for compatibility.
3516           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3517             break;
3518         } else {
3519           // A constant whose bitwise inverse can be used as an immediate
3520           // value in a data-processing instruction. This can be used in GCC
3521           // with a "B" modifier that prints the inverted value, for use with
3522           // BIC and MVN instructions. It is not useful otherwise but is
3523           // implemented for compatibility.
3524           if (ARM_AM::getSOImmVal(~CVal) != -1)
3525             break;
3526         }
3527         return;
3528
3529       case 'L':
3530         if (Subtarget->isThumb1Only()) {
3531           // This must be a constant between -7 and 7,
3532           // for 3-operand ADD/SUB immediate instructions.
3533           if (CVal >= -7 && CVal < 7)
3534             break;
3535         } else if (Subtarget->isThumb2()) {
3536           // A constant whose negation can be used as an immediate value in a
3537           // data-processing instruction. This can be used in GCC with an "n"
3538           // modifier that prints the negated value, for use with SUB
3539           // instructions. It is not useful otherwise but is implemented for
3540           // compatibility.
3541           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
3542             break;
3543         } else {
3544           // A constant whose negation can be used as an immediate value in a
3545           // data-processing instruction. This can be used in GCC with an "n"
3546           // modifier that prints the negated value, for use with SUB
3547           // instructions. It is not useful otherwise but is implemented for
3548           // compatibility.
3549           if (ARM_AM::getSOImmVal(-CVal) != -1)
3550             break;
3551         }
3552         return;
3553
3554       case 'M':
3555         if (Subtarget->isThumb()) { // FIXME thumb2
3556           // This must be a multiple of 4 between 0 and 1020, for
3557           // ADD sp + immediate.
3558           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
3559             break;
3560         } else {
3561           // A power of two or a constant between 0 and 32.  This is used in
3562           // GCC for the shift amount on shifted register operands, but it is
3563           // useful in general for any shift amounts.
3564           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
3565             break;
3566         }
3567         return;
3568
3569       case 'N':
3570         if (Subtarget->isThumb()) {  // FIXME thumb2
3571           // This must be a constant between 0 and 31, for shift amounts.
3572           if (CVal >= 0 && CVal <= 31)
3573             break;
3574         }
3575         return;
3576
3577       case 'O':
3578         if (Subtarget->isThumb()) {  // FIXME thumb2
3579           // This must be a multiple of 4 between -508 and 508, for
3580           // ADD/SUB sp = sp + immediate.
3581           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
3582             break;
3583         }
3584         return;
3585     }
3586     Result = DAG.getTargetConstant(CVal, Op.getValueType());
3587     break;
3588   }
3589
3590   if (Result.getNode()) {
3591     Ops.push_back(Result);
3592     return;
3593   }
3594   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
3595                                                       Ops, DAG);
3596 }