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