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