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