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