Next round of tail call changes. Register used in a tail
[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   // Temporarily disable tail calls so things don't break.
1003   if (!EnableARMTailCalls)
1004     isTailCall = false;
1005   if (isTailCall) {
1006     // Check if it's really possible to do a tail call.
1007     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1008                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1009                                                    Outs, Ins, DAG);
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   // Tail call byval lowering might overwrite argument registers so in case of
1113   // tail call optimization the copies to registers are lowered later.
1114   if (!isTailCall)
1115     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1116       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1117                                RegsToPass[i].second, InFlag);
1118       InFlag = Chain.getValue(1);
1119     }
1120
1121   // For tail calls lower the arguments to the 'real' stack slot.
1122   if (isTailCall) {
1123     // Force all the incoming stack arguments to be loaded from the stack
1124     // before any new outgoing arguments are stored to the stack, because the
1125     // outgoing stack slots may alias the incoming argument stack slots, and
1126     // the alias isn't otherwise explicit. This is slightly more conservative
1127     // than necessary, because it means that each store effectively depends
1128     // on every argument instead of just those arguments it would clobber.
1129
1130     // Do not flag preceeding copytoreg stuff together with the following stuff.
1131     InFlag = SDValue();
1132     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1133       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1134                                RegsToPass[i].second, InFlag);
1135       InFlag = Chain.getValue(1);
1136     }
1137     InFlag =SDValue();
1138   }
1139
1140   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1141   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1142   // node so that legalize doesn't hack it.
1143   bool isDirect = false;
1144   bool isARMFunc = false;
1145   bool isLocalARMFunc = false;
1146   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1147
1148   if (EnableARMLongCalls) {
1149     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1150             && "long-calls with non-static relocation model!");
1151     // Handle a global address or an external symbol. If it's not one of
1152     // those, the target's already in a register, so we don't need to do
1153     // anything extra.
1154     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1155       const GlobalValue *GV = G->getGlobal();
1156       // Create a constant pool entry for the callee address
1157       unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1158       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1159                                                            ARMPCLabelIndex,
1160                                                            ARMCP::CPValue, 0);
1161       // Get the address of the callee into a register
1162       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1163       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1164       Callee = DAG.getLoad(getPointerTy(), dl,
1165                            DAG.getEntryNode(), CPAddr,
1166                            PseudoSourceValue::getConstantPool(), 0,
1167                            false, false, 0);
1168     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1169       const char *Sym = S->getSymbol();
1170
1171       // Create a constant pool entry for the callee address
1172       unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1173       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1174                                                        Sym, ARMPCLabelIndex, 0);
1175       // Get the address of the callee into a register
1176       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1177       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1178       Callee = DAG.getLoad(getPointerTy(), dl,
1179                            DAG.getEntryNode(), CPAddr,
1180                            PseudoSourceValue::getConstantPool(), 0,
1181                            false, false, 0);
1182     }
1183   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1184     const GlobalValue *GV = G->getGlobal();
1185     isDirect = true;
1186     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1187     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1188                    getTargetMachine().getRelocationModel() != Reloc::Static;
1189     isARMFunc = !Subtarget->isThumb() || isStub;
1190     // ARM call to a local ARM function is predicable.
1191     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
1192     // tBX takes a register source operand.
1193     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1194       unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1195       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV,
1196                                                            ARMPCLabelIndex,
1197                                                            ARMCP::CPValue, 4);
1198       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1199       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1200       Callee = DAG.getLoad(getPointerTy(), dl,
1201                            DAG.getEntryNode(), CPAddr,
1202                            PseudoSourceValue::getConstantPool(), 0,
1203                            false, false, 0);
1204       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1205       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1206                            getPointerTy(), Callee, PICLabel);
1207     } else
1208       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
1209   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1210     isDirect = true;
1211     bool isStub = Subtarget->isTargetDarwin() &&
1212                   getTargetMachine().getRelocationModel() != Reloc::Static;
1213     isARMFunc = !Subtarget->isThumb() || isStub;
1214     // tBX takes a register source operand.
1215     const char *Sym = S->getSymbol();
1216     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1217       unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1218       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1219                                                        Sym, ARMPCLabelIndex, 4);
1220       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1221       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1222       Callee = DAG.getLoad(getPointerTy(), dl,
1223                            DAG.getEntryNode(), CPAddr,
1224                            PseudoSourceValue::getConstantPool(), 0,
1225                            false, false, 0);
1226       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1227       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1228                            getPointerTy(), Callee, PICLabel);
1229     } else
1230       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1231   }
1232
1233   // FIXME: handle tail calls differently.
1234   unsigned CallOpc;
1235   if (Subtarget->isThumb()) {
1236     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1237       CallOpc = ARMISD::CALL_NOLINK;
1238     else
1239       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1240   } else {
1241     CallOpc = (isDirect || Subtarget->hasV5TOps())
1242       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1243       : ARMISD::CALL_NOLINK;
1244   }
1245   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb1Only()) {
1246     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
1247     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
1248     InFlag = Chain.getValue(1);
1249   }
1250
1251   std::vector<SDValue> Ops;
1252   Ops.push_back(Chain);
1253   Ops.push_back(Callee);
1254
1255   // Add argument registers to the end of the list so that they are known live
1256   // into the call.
1257   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1258     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1259                                   RegsToPass[i].second.getValueType()));
1260
1261   if (InFlag.getNode())
1262     Ops.push_back(InFlag);
1263
1264   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1265   if (isTailCall)
1266     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1267
1268   // Returns a chain and a flag for retval copy to use.
1269   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1270   InFlag = Chain.getValue(1);
1271
1272   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1273                              DAG.getIntPtrConstant(0, true), InFlag);
1274   if (!Ins.empty())
1275     InFlag = Chain.getValue(1);
1276
1277   // Handle result values, copying them out of physregs into vregs that we
1278   // return.
1279   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1280                          dl, DAG, InVals);
1281 }
1282
1283 /// MatchingStackOffset - Return true if the given stack call argument is
1284 /// already available in the same position (relatively) of the caller's
1285 /// incoming argument stack.
1286 static
1287 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1288                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1289                          const ARMInstrInfo *TII) {
1290   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1291   int FI = INT_MAX;
1292   if (Arg.getOpcode() == ISD::CopyFromReg) {
1293     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1294     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
1295       return false;
1296     MachineInstr *Def = MRI->getVRegDef(VR);
1297     if (!Def)
1298       return false;
1299     if (!Flags.isByVal()) {
1300       if (!TII->isLoadFromStackSlot(Def, FI))
1301         return false;
1302     } else {
1303 //      unsigned Opcode = Def->getOpcode();
1304 //      if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
1305 //          Def->getOperand(1).isFI()) {
1306 //        FI = Def->getOperand(1).getIndex();
1307 //        Bytes = Flags.getByValSize();
1308 //      } else
1309         return false;
1310     }
1311   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1312     if (Flags.isByVal())
1313       // ByVal argument is passed in as a pointer but it's now being
1314       // dereferenced. e.g.
1315       // define @foo(%struct.X* %A) {
1316       //   tail call @bar(%struct.X* byval %A)
1317       // }
1318       return false;
1319     SDValue Ptr = Ld->getBasePtr();
1320     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1321     if (!FINode)
1322       return false;
1323     FI = FINode->getIndex();
1324   } else
1325     return false;
1326
1327   assert(FI != INT_MAX);
1328   if (!MFI->isFixedObjectIndex(FI))
1329     return false;
1330   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1331 }
1332
1333 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1334 /// for tail call optimization. Targets which want to do tail call
1335 /// optimization should implement this function.
1336 bool
1337 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1338                                                      CallingConv::ID CalleeCC,
1339                                                      bool isVarArg,
1340                                                      bool isCalleeStructRet,
1341                                                      bool isCallerStructRet,
1342                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1343                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1344                                                      SelectionDAG& DAG) const {
1345
1346   const Function *CallerF = DAG.getMachineFunction().getFunction();
1347   CallingConv::ID CallerCC = CallerF->getCallingConv();
1348   bool CCMatch = CallerCC == CalleeCC;
1349
1350   // Look for obvious safe cases to perform tail call optimization that do not
1351   // require ABI changes. This is what gcc calls sibcall.
1352
1353   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
1354   // emit a special epilogue.
1355   // Not sure yet if this is true on ARM.
1356 //??  if (RegInfo->needsStackRealignment(MF))
1357 //??    return false;
1358
1359   // Do not sibcall optimize vararg calls unless the call site is not passing any
1360   // arguments.
1361   if (isVarArg && !Outs.empty())
1362     return false;
1363
1364   // Also avoid sibcall optimization if either caller or callee uses struct
1365   // return semantics.
1366   if (isCalleeStructRet || isCallerStructRet)
1367     return false;
1368
1369   // If the calling conventions do not match, then we'd better make sure the
1370   // results are returned in the same way as what the caller expects.
1371   if (!CCMatch) {
1372     SmallVector<CCValAssign, 16> RVLocs1;
1373     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
1374                     RVLocs1, *DAG.getContext());
1375     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1376
1377     SmallVector<CCValAssign, 16> RVLocs2;
1378     CCState CCInfo2(CallerCC, false, getTargetMachine(),
1379                     RVLocs2, *DAG.getContext());
1380     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1381
1382     if (RVLocs1.size() != RVLocs2.size())
1383       return false;
1384     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1385       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1386         return false;
1387       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1388         return false;
1389       if (RVLocs1[i].isRegLoc()) {
1390         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1391           return false;
1392       } else {
1393         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1394           return false;
1395       }
1396     }
1397   }
1398
1399   // If the callee takes no arguments then go on to check the results of the
1400   // call.
1401   if (!Outs.empty()) {
1402     // Check if stack adjustment is needed. For now, do not do this if any
1403     // argument is passed on the stack.
1404     SmallVector<CCValAssign, 16> ArgLocs;
1405     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
1406                    ArgLocs, *DAG.getContext());
1407     CCInfo.AnalyzeCallOperands(Outs,
1408                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1409     if (CCInfo.getNextStackOffset()) {
1410       MachineFunction &MF = DAG.getMachineFunction();
1411
1412       // Check if the arguments are already laid out in the right way as
1413       // the caller's fixed stack objects.
1414       MachineFrameInfo *MFI = MF.getFrameInfo();
1415       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1416       const ARMInstrInfo *TII =
1417         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1418       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1419            i != e;
1420            ++i, ++realArgIdx) {
1421         CCValAssign &VA = ArgLocs[i];
1422         EVT RegVT = VA.getLocVT();
1423         SDValue Arg = Outs[realArgIdx].Val;
1424         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1425         if (VA.getLocInfo() == CCValAssign::Indirect)
1426           return false;
1427         if (VA.needsCustom()) {
1428           // f64 and vector types are split into multiple registers or
1429           // register/stack-slot combinations.  The types will not match
1430           // the registers; give up on memory f64 refs until we figure
1431           // out what to do about this.
1432           if (!VA.isRegLoc())
1433             return false;
1434           if (!ArgLocs[++i].isRegLoc())
1435             return false; 
1436           if (RegVT == MVT::v2f64) {
1437             if (!ArgLocs[++i].isRegLoc())
1438               return false;
1439             if (!ArgLocs[++i].isRegLoc())
1440               return false;
1441           }
1442         } else if (!VA.isRegLoc()) {
1443           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1444                                    MFI, MRI, TII))
1445             return false;
1446         }
1447       }
1448     }
1449   }
1450
1451   return true;
1452 }
1453
1454 SDValue
1455 ARMTargetLowering::LowerReturn(SDValue Chain,
1456                                CallingConv::ID CallConv, bool isVarArg,
1457                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1458                                DebugLoc dl, SelectionDAG &DAG) const {
1459
1460   // CCValAssign - represent the assignment of the return value to a location.
1461   SmallVector<CCValAssign, 16> RVLocs;
1462
1463   // CCState - Info about the registers and stack slots.
1464   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1465                  *DAG.getContext());
1466
1467   // Analyze outgoing return values.
1468   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1469                                                isVarArg));
1470
1471   // If this is the first return lowered for this function, add
1472   // the regs to the liveout set for the function.
1473   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1474     for (unsigned i = 0; i != RVLocs.size(); ++i)
1475       if (RVLocs[i].isRegLoc())
1476         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1477   }
1478
1479   SDValue Flag;
1480
1481   // Copy the result values into the output registers.
1482   for (unsigned i = 0, realRVLocIdx = 0;
1483        i != RVLocs.size();
1484        ++i, ++realRVLocIdx) {
1485     CCValAssign &VA = RVLocs[i];
1486     assert(VA.isRegLoc() && "Can only return in registers!");
1487
1488     SDValue Arg = Outs[realRVLocIdx].Val;
1489
1490     switch (VA.getLocInfo()) {
1491     default: llvm_unreachable("Unknown loc info!");
1492     case CCValAssign::Full: break;
1493     case CCValAssign::BCvt:
1494       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
1495       break;
1496     }
1497
1498     if (VA.needsCustom()) {
1499       if (VA.getLocVT() == MVT::v2f64) {
1500         // Extract the first half and return it in two registers.
1501         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1502                                    DAG.getConstant(0, MVT::i32));
1503         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1504                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1505
1506         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1507         Flag = Chain.getValue(1);
1508         VA = RVLocs[++i]; // skip ahead to next loc
1509         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1510                                  HalfGPRs.getValue(1), Flag);
1511         Flag = Chain.getValue(1);
1512         VA = RVLocs[++i]; // skip ahead to next loc
1513
1514         // Extract the 2nd half and fall through to handle it as an f64 value.
1515         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1516                           DAG.getConstant(1, MVT::i32));
1517       }
1518       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1519       // available.
1520       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1521                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1522       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1523       Flag = Chain.getValue(1);
1524       VA = RVLocs[++i]; // skip ahead to next loc
1525       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1526                                Flag);
1527     } else
1528       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1529
1530     // Guarantee that all emitted copies are
1531     // stuck together, avoiding something bad.
1532     Flag = Chain.getValue(1);
1533   }
1534
1535   SDValue result;
1536   if (Flag.getNode())
1537     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1538   else // Return Void
1539     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1540
1541   return result;
1542 }
1543
1544 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1545 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1546 // one of the above mentioned nodes. It has to be wrapped because otherwise
1547 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1548 // be used to form addressing mode. These wrapped nodes will be selected
1549 // into MOVi.
1550 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1551   EVT PtrVT = Op.getValueType();
1552   // FIXME there is no actual debug info here
1553   DebugLoc dl = Op.getDebugLoc();
1554   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1555   SDValue Res;
1556   if (CP->isMachineConstantPoolEntry())
1557     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1558                                     CP->getAlignment());
1559   else
1560     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1561                                     CP->getAlignment());
1562   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1563 }
1564
1565 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
1566                                              SelectionDAG &DAG) const {
1567   MachineFunction &MF = DAG.getMachineFunction();
1568   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1569   unsigned ARMPCLabelIndex = 0;
1570   DebugLoc DL = Op.getDebugLoc();
1571   EVT PtrVT = getPointerTy();
1572   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1573   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1574   SDValue CPAddr;
1575   if (RelocM == Reloc::Static) {
1576     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
1577   } else {
1578     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1579     ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1580     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(BA, ARMPCLabelIndex,
1581                                                          ARMCP::CPBlockAddress,
1582                                                          PCAdj);
1583     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1584   }
1585   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
1586   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
1587                                PseudoSourceValue::getConstantPool(), 0,
1588                                false, false, 0);
1589   if (RelocM == Reloc::Static)
1590     return Result;
1591   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1592   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
1593 }
1594
1595 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1596 SDValue
1597 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1598                                                  SelectionDAG &DAG) const {
1599   DebugLoc dl = GA->getDebugLoc();
1600   EVT PtrVT = getPointerTy();
1601   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1602   MachineFunction &MF = DAG.getMachineFunction();
1603   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1604   unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1605   ARMConstantPoolValue *CPV =
1606     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1607                              ARMCP::CPValue, PCAdj, "tlsgd", true);
1608   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1609   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1610   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
1611                          PseudoSourceValue::getConstantPool(), 0,
1612                          false, false, 0);
1613   SDValue Chain = Argument.getValue(1);
1614
1615   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1616   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1617
1618   // call __tls_get_addr.
1619   ArgListTy Args;
1620   ArgListEntry Entry;
1621   Entry.Node = Argument;
1622   Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1623   Args.push_back(Entry);
1624   // FIXME: is there useful debug info available here?
1625   std::pair<SDValue, SDValue> CallResult =
1626     LowerCallTo(Chain, (const Type *) Type::getInt32Ty(*DAG.getContext()),
1627                 false, false, false, false,
1628                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1629                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1630   return CallResult.first;
1631 }
1632
1633 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1634 // "local exec" model.
1635 SDValue
1636 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1637                                         SelectionDAG &DAG) const {
1638   const GlobalValue *GV = GA->getGlobal();
1639   DebugLoc dl = GA->getDebugLoc();
1640   SDValue Offset;
1641   SDValue Chain = DAG.getEntryNode();
1642   EVT PtrVT = getPointerTy();
1643   // Get the Thread Pointer
1644   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1645
1646   if (GV->isDeclaration()) {
1647     MachineFunction &MF = DAG.getMachineFunction();
1648     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1649     unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1650     // Initial exec model.
1651     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1652     ARMConstantPoolValue *CPV =
1653       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex,
1654                                ARMCP::CPValue, PCAdj, "gottpoff", true);
1655     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1656     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1657     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
1658                          PseudoSourceValue::getConstantPool(), 0,
1659                          false, false, 0);
1660     Chain = Offset.getValue(1);
1661
1662     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1663     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1664
1665     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
1666                          PseudoSourceValue::getConstantPool(), 0,
1667                          false, false, 0);
1668   } else {
1669     // local exec model
1670     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, "tpoff");
1671     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1672     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1673     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
1674                          PseudoSourceValue::getConstantPool(), 0,
1675                          false, false, 0);
1676   }
1677
1678   // The address of the thread local variable is the add of the thread
1679   // pointer with the offset of the variable.
1680   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1681 }
1682
1683 SDValue
1684 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
1685   // TODO: implement the "local dynamic" model
1686   assert(Subtarget->isTargetELF() &&
1687          "TLS not implemented for non-ELF targets");
1688   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1689   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1690   // otherwise use the "Local Exec" TLS Model
1691   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1692     return LowerToTLSGeneralDynamicModel(GA, DAG);
1693   else
1694     return LowerToTLSExecModels(GA, DAG);
1695 }
1696
1697 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1698                                                  SelectionDAG &DAG) const {
1699   EVT PtrVT = getPointerTy();
1700   DebugLoc dl = Op.getDebugLoc();
1701   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1702   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1703   if (RelocM == Reloc::PIC_) {
1704     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1705     ARMConstantPoolValue *CPV =
1706       new ARMConstantPoolValue(GV, UseGOTOFF ? "GOTOFF" : "GOT");
1707     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1708     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1709     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1710                                  CPAddr,
1711                                  PseudoSourceValue::getConstantPool(), 0,
1712                                  false, false, 0);
1713     SDValue Chain = Result.getValue(1);
1714     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1715     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
1716     if (!UseGOTOFF)
1717       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
1718                            PseudoSourceValue::getGOT(), 0,
1719                            false, false, 0);
1720     return Result;
1721   } else {
1722     // If we have T2 ops, we can materialize the address directly via movt/movw
1723     // pair. This is always cheaper.
1724     if (Subtarget->useMovt()) {
1725       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
1726                          DAG.getTargetGlobalAddress(GV, PtrVT));
1727     } else {
1728       SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1729       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1730       return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
1731                          PseudoSourceValue::getConstantPool(), 0,
1732                          false, false, 0);
1733     }
1734   }
1735 }
1736
1737 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
1738                                                     SelectionDAG &DAG) const {
1739   MachineFunction &MF = DAG.getMachineFunction();
1740   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1741   unsigned ARMPCLabelIndex = 0;
1742   EVT PtrVT = getPointerTy();
1743   DebugLoc dl = Op.getDebugLoc();
1744   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1745   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1746   SDValue CPAddr;
1747   if (RelocM == Reloc::Static)
1748     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1749   else {
1750     ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1751     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
1752     ARMConstantPoolValue *CPV =
1753       new ARMConstantPoolValue(GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj);
1754     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1755   }
1756   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1757
1758   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
1759                                PseudoSourceValue::getConstantPool(), 0,
1760                                false, false, 0);
1761   SDValue Chain = Result.getValue(1);
1762
1763   if (RelocM == Reloc::PIC_) {
1764     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1765     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1766   }
1767
1768   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
1769     Result = DAG.getLoad(PtrVT, dl, Chain, Result,
1770                          PseudoSourceValue::getGOT(), 0,
1771                          false, false, 0);
1772
1773   return Result;
1774 }
1775
1776 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1777                                                     SelectionDAG &DAG) const {
1778   assert(Subtarget->isTargetELF() &&
1779          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1780   MachineFunction &MF = DAG.getMachineFunction();
1781   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1782   unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1783   EVT PtrVT = getPointerTy();
1784   DebugLoc dl = Op.getDebugLoc();
1785   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1786   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1787                                                        "_GLOBAL_OFFSET_TABLE_",
1788                                                        ARMPCLabelIndex, PCAdj);
1789   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1790   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1791   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
1792                                PseudoSourceValue::getConstantPool(), 0,
1793                                false, false, 0);
1794   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1795   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1796 }
1797
1798 SDValue
1799 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
1800   DebugLoc dl = Op.getDebugLoc();
1801   SDValue Val = DAG.getConstant(0, MVT::i32);
1802   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(0),
1803                      Op.getOperand(1), Val);
1804 }
1805
1806 SDValue
1807 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
1808   DebugLoc dl = Op.getDebugLoc();
1809   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
1810                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
1811 }
1812
1813 SDValue
1814 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
1815                                            const ARMSubtarget *Subtarget)
1816                                              const {
1817   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1818   DebugLoc dl = Op.getDebugLoc();
1819   switch (IntNo) {
1820   default: return SDValue();    // Don't custom lower most intrinsics.
1821   case Intrinsic::arm_thread_pointer: {
1822     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1823     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1824   }
1825   case Intrinsic::eh_sjlj_lsda: {
1826     MachineFunction &MF = DAG.getMachineFunction();
1827     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1828     unsigned ARMPCLabelIndex = AFI->createConstPoolEntryUId();
1829     EVT PtrVT = getPointerTy();
1830     DebugLoc dl = Op.getDebugLoc();
1831     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1832     SDValue CPAddr;
1833     unsigned PCAdj = (RelocM != Reloc::PIC_)
1834       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1835     ARMConstantPoolValue *CPV =
1836       new ARMConstantPoolValue(MF.getFunction(), ARMPCLabelIndex,
1837                                ARMCP::CPLSDA, PCAdj);
1838     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1839     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1840     SDValue Result =
1841       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
1842                   PseudoSourceValue::getConstantPool(), 0,
1843                   false, false, 0);
1844     SDValue Chain = Result.getValue(1);
1845
1846     if (RelocM == Reloc::PIC_) {
1847       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1848       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1849     }
1850     return Result;
1851   }
1852   }
1853 }
1854
1855 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
1856                           const ARMSubtarget *Subtarget) {
1857   DebugLoc dl = Op.getDebugLoc();
1858   SDValue Op5 = Op.getOperand(5);
1859   SDValue Res;
1860   unsigned isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue();
1861   if (isDeviceBarrier) {
1862     if (Subtarget->hasV7Ops())
1863       Res = DAG.getNode(ARMISD::SYNCBARRIER, dl, MVT::Other, Op.getOperand(0));
1864     else
1865       Res = DAG.getNode(ARMISD::SYNCBARRIER, dl, MVT::Other, Op.getOperand(0),
1866                         DAG.getConstant(0, MVT::i32));
1867   } else {
1868     if (Subtarget->hasV7Ops())
1869       Res = DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
1870     else
1871       Res = DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
1872                         DAG.getConstant(0, MVT::i32));
1873   }
1874   return Res;
1875 }
1876
1877 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
1878   MachineFunction &MF = DAG.getMachineFunction();
1879   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
1880
1881   // vastart just stores the address of the VarArgsFrameIndex slot into the
1882   // memory location argument.
1883   DebugLoc dl = Op.getDebugLoc();
1884   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1885   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1886   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1887   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
1888                       false, false, 0);
1889 }
1890
1891 SDValue
1892 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1893                                            SelectionDAG &DAG) const {
1894   SDNode *Node = Op.getNode();
1895   DebugLoc dl = Node->getDebugLoc();
1896   EVT VT = Node->getValueType(0);
1897   SDValue Chain = Op.getOperand(0);
1898   SDValue Size  = Op.getOperand(1);
1899   SDValue Align = Op.getOperand(2);
1900
1901   // Chain the dynamic stack allocation so that it doesn't modify the stack
1902   // pointer when other instructions are using the stack.
1903   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1904
1905   unsigned AlignVal = cast<ConstantSDNode>(Align)->getZExtValue();
1906   unsigned StackAlign = getTargetMachine().getFrameInfo()->getStackAlignment();
1907   if (AlignVal > StackAlign)
1908     // Do this now since selection pass cannot introduce new target
1909     // independent node.
1910     Align = DAG.getConstant(-(uint64_t)AlignVal, VT);
1911
1912   // In Thumb1 mode, there isn't a "sub r, sp, r" instruction, we will end up
1913   // using a "add r, sp, r" instead. Negate the size now so we don't have to
1914   // do even more horrible hack later.
1915   MachineFunction &MF = DAG.getMachineFunction();
1916   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1917   if (AFI->isThumb1OnlyFunction()) {
1918     bool Negate = true;
1919     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Size);
1920     if (C) {
1921       uint32_t Val = C->getZExtValue();
1922       if (Val <= 508 && ((Val & 3) == 0))
1923         Negate = false;
1924     }
1925     if (Negate)
1926       Size = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, VT), Size);
1927   }
1928
1929   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1930   SDValue Ops1[] = { Chain, Size, Align };
1931   SDValue Res = DAG.getNode(ARMISD::DYN_ALLOC, dl, VTList, Ops1, 3);
1932   Chain = Res.getValue(1);
1933   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1934                              DAG.getIntPtrConstant(0, true), SDValue());
1935   SDValue Ops2[] = { Res, Chain };
1936   return DAG.getMergeValues(Ops2, 2, dl);
1937 }
1938
1939 SDValue
1940 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1941                                         SDValue &Root, SelectionDAG &DAG,
1942                                         DebugLoc dl) const {
1943   MachineFunction &MF = DAG.getMachineFunction();
1944   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1945
1946   TargetRegisterClass *RC;
1947   if (AFI->isThumb1OnlyFunction())
1948     RC = ARM::tGPRRegisterClass;
1949   else
1950     RC = ARM::GPRRegisterClass;
1951
1952   // Transform the arguments stored in physical registers into virtual ones.
1953   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 
1954   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1955
1956   SDValue ArgValue2;
1957   if (NextVA.isMemLoc()) {
1958     MachineFrameInfo *MFI = MF.getFrameInfo();
1959     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true, false);
1960
1961     // Create load node to retrieve arguments from the stack.
1962     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1963     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
1964                             PseudoSourceValue::getFixedStack(FI), 0,
1965                             false, false, 0);
1966   } else {
1967     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1968     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1969   }
1970
1971   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
1972 }
1973
1974 SDValue
1975 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1976                                         CallingConv::ID CallConv, bool isVarArg,
1977                                         const SmallVectorImpl<ISD::InputArg>
1978                                           &Ins,
1979                                         DebugLoc dl, SelectionDAG &DAG,
1980                                         SmallVectorImpl<SDValue> &InVals)
1981                                           const {
1982
1983   MachineFunction &MF = DAG.getMachineFunction();
1984   MachineFrameInfo *MFI = MF.getFrameInfo();
1985
1986   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1987
1988   // Assign locations to all of the incoming arguments.
1989   SmallVector<CCValAssign, 16> ArgLocs;
1990   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1991                  *DAG.getContext());
1992   CCInfo.AnalyzeFormalArguments(Ins,
1993                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1994                                                   isVarArg));
1995
1996   SmallVector<SDValue, 16> ArgValues;
1997
1998   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1999     CCValAssign &VA = ArgLocs[i];
2000
2001     // Arguments stored in registers.
2002     if (VA.isRegLoc()) {
2003       EVT RegVT = VA.getLocVT();
2004
2005       SDValue ArgValue;
2006       if (VA.needsCustom()) {
2007         // f64 and vector types are split up into multiple registers or
2008         // combinations of registers and stack slots.
2009         if (VA.getLocVT() == MVT::v2f64) {
2010           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2011                                                    Chain, DAG, dl);
2012           VA = ArgLocs[++i]; // skip ahead to next loc
2013           SDValue ArgValue2;
2014           if (VA.isMemLoc()) {
2015             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(),
2016                                             true, false);
2017             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2018             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2019                                     PseudoSourceValue::getFixedStack(FI), 0,
2020                                     false, false, 0);
2021           } else {
2022             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2023                                              Chain, DAG, dl);
2024           }
2025           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2026           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2027                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2028           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2029                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2030         } else
2031           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2032
2033       } else {
2034         TargetRegisterClass *RC;
2035
2036         if (RegVT == MVT::f32)
2037           RC = ARM::SPRRegisterClass;
2038         else if (RegVT == MVT::f64)
2039           RC = ARM::DPRRegisterClass;
2040         else if (RegVT == MVT::v2f64)
2041           RC = ARM::QPRRegisterClass;
2042         else if (RegVT == MVT::i32)
2043           RC = (AFI->isThumb1OnlyFunction() ?
2044                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2045         else
2046           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2047
2048         // Transform the arguments in physical registers into virtual ones.
2049         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2050         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2051       }
2052
2053       // If this is an 8 or 16-bit value, it is really passed promoted
2054       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2055       // truncate to the right size.
2056       switch (VA.getLocInfo()) {
2057       default: llvm_unreachable("Unknown loc info!");
2058       case CCValAssign::Full: break;
2059       case CCValAssign::BCvt:
2060         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
2061         break;
2062       case CCValAssign::SExt:
2063         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2064                                DAG.getValueType(VA.getValVT()));
2065         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2066         break;
2067       case CCValAssign::ZExt:
2068         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2069                                DAG.getValueType(VA.getValVT()));
2070         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2071         break;
2072       }
2073
2074       InVals.push_back(ArgValue);
2075
2076     } else { // VA.isRegLoc()
2077
2078       // sanity check
2079       assert(VA.isMemLoc());
2080       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2081
2082       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
2083       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2084                                       true, false);
2085
2086       // Create load nodes to retrieve arguments from the stack.
2087       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2088       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2089                                    PseudoSourceValue::getFixedStack(FI), 0,
2090                                    false, false, 0));
2091     }
2092   }
2093
2094   // varargs
2095   if (isVarArg) {
2096     static const unsigned GPRArgRegs[] = {
2097       ARM::R0, ARM::R1, ARM::R2, ARM::R3
2098     };
2099
2100     unsigned NumGPRs = CCInfo.getFirstUnallocated
2101       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2102
2103     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
2104     unsigned VARegSize = (4 - NumGPRs) * 4;
2105     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2106     unsigned ArgOffset = CCInfo.getNextStackOffset();
2107     if (VARegSaveSize) {
2108       // If this function is vararg, store any remaining integer argument regs
2109       // to their spots on the stack so that they may be loaded by deferencing
2110       // the result of va_next.
2111       AFI->setVarArgsRegSaveSize(VARegSaveSize);
2112       AFI->setVarArgsFrameIndex(
2113         MFI->CreateFixedObject(VARegSaveSize,
2114                                ArgOffset + VARegSaveSize - VARegSize,
2115                                true, false));
2116       SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2117                                       getPointerTy());
2118
2119       SmallVector<SDValue, 4> MemOps;
2120       for (; NumGPRs < 4; ++NumGPRs) {
2121         TargetRegisterClass *RC;
2122         if (AFI->isThumb1OnlyFunction())
2123           RC = ARM::tGPRRegisterClass;
2124         else
2125           RC = ARM::GPRRegisterClass;
2126
2127         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
2128         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2129         SDValue Store =
2130           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2131                PseudoSourceValue::getFixedStack(AFI->getVarArgsFrameIndex()),
2132                0, false, false, 0);
2133         MemOps.push_back(Store);
2134         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2135                           DAG.getConstant(4, getPointerTy()));
2136       }
2137       if (!MemOps.empty())
2138         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2139                             &MemOps[0], MemOps.size());
2140     } else
2141       // This will point to the next argument passed via stack.
2142       AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset,
2143                                                        true, false));
2144   }
2145
2146   return Chain;
2147 }
2148
2149 /// isFloatingPointZero - Return true if this is +0.0.
2150 static bool isFloatingPointZero(SDValue Op) {
2151   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2152     return CFP->getValueAPF().isPosZero();
2153   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2154     // Maybe this has already been legalized into the constant pool?
2155     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2156       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2157       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2158         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2159           return CFP->getValueAPF().isPosZero();
2160     }
2161   }
2162   return false;
2163 }
2164
2165 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2166 /// the given operands.
2167 SDValue
2168 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2169                              SDValue &ARMCC, SelectionDAG &DAG,
2170                              DebugLoc dl) const {
2171   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2172     unsigned C = RHSC->getZExtValue();
2173     if (!isLegalICmpImmediate(C)) {
2174       // Constant does not fit, try adjusting it by one?
2175       switch (CC) {
2176       default: break;
2177       case ISD::SETLT:
2178       case ISD::SETGE:
2179         if (isLegalICmpImmediate(C-1)) {
2180           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2181           RHS = DAG.getConstant(C-1, MVT::i32);
2182         }
2183         break;
2184       case ISD::SETULT:
2185       case ISD::SETUGE:
2186         if (C > 0 && isLegalICmpImmediate(C-1)) {
2187           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2188           RHS = DAG.getConstant(C-1, MVT::i32);
2189         }
2190         break;
2191       case ISD::SETLE:
2192       case ISD::SETGT:
2193         if (isLegalICmpImmediate(C+1)) {
2194           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2195           RHS = DAG.getConstant(C+1, MVT::i32);
2196         }
2197         break;
2198       case ISD::SETULE:
2199       case ISD::SETUGT:
2200         if (C < 0xffffffff && isLegalICmpImmediate(C+1)) {
2201           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2202           RHS = DAG.getConstant(C+1, MVT::i32);
2203         }
2204         break;
2205       }
2206     }
2207   }
2208
2209   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2210   ARMISD::NodeType CompareType;
2211   switch (CondCode) {
2212   default:
2213     CompareType = ARMISD::CMP;
2214     break;
2215   case ARMCC::EQ:
2216   case ARMCC::NE:
2217     // Uses only Z Flag
2218     CompareType = ARMISD::CMPZ;
2219     break;
2220   }
2221   ARMCC = DAG.getConstant(CondCode, MVT::i32);
2222   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
2223 }
2224
2225 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2226 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2227                          DebugLoc dl) {
2228   SDValue Cmp;
2229   if (!isFloatingPointZero(RHS))
2230     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
2231   else
2232     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
2233   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
2234 }
2235
2236 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2237   EVT VT = Op.getValueType();
2238   SDValue LHS = Op.getOperand(0);
2239   SDValue RHS = Op.getOperand(1);
2240   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2241   SDValue TrueVal = Op.getOperand(2);
2242   SDValue FalseVal = Op.getOperand(3);
2243   DebugLoc dl = Op.getDebugLoc();
2244
2245   if (LHS.getValueType() == MVT::i32) {
2246     SDValue ARMCC;
2247     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2248     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, dl);
2249     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
2250   }
2251
2252   ARMCC::CondCodes CondCode, CondCode2;
2253   FPCCToARMCC(CC, CondCode, CondCode2);
2254
2255   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
2256   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2257   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2258   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2259                                  ARMCC, CCR, Cmp);
2260   if (CondCode2 != ARMCC::AL) {
2261     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
2262     // FIXME: Needs another CMP because flag can have but one use.
2263     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2264     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2265                          Result, TrueVal, ARMCC2, CCR, Cmp2);
2266   }
2267   return Result;
2268 }
2269
2270 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2271   SDValue  Chain = Op.getOperand(0);
2272   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2273   SDValue    LHS = Op.getOperand(2);
2274   SDValue    RHS = Op.getOperand(3);
2275   SDValue   Dest = Op.getOperand(4);
2276   DebugLoc dl = Op.getDebugLoc();
2277
2278   if (LHS.getValueType() == MVT::i32) {
2279     SDValue ARMCC;
2280     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2281     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, dl);
2282     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2283                        Chain, Dest, ARMCC, CCR,Cmp);
2284   }
2285
2286   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2287   ARMCC::CondCodes CondCode, CondCode2;
2288   FPCCToARMCC(CC, CondCode, CondCode2);
2289
2290   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2291   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
2292   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2293   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
2294   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
2295   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2296   if (CondCode2 != ARMCC::AL) {
2297     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
2298     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
2299     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
2300   }
2301   return Res;
2302 }
2303
2304 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
2305   SDValue Chain = Op.getOperand(0);
2306   SDValue Table = Op.getOperand(1);
2307   SDValue Index = Op.getOperand(2);
2308   DebugLoc dl = Op.getDebugLoc();
2309
2310   EVT PTy = getPointerTy();
2311   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
2312   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2313   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
2314   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
2315   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
2316   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
2317   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2318   if (Subtarget->isThumb2()) {
2319     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
2320     // which does another jump to the destination. This also makes it easier
2321     // to translate it to TBB / TBH later.
2322     // FIXME: This might not work if the function is extremely large.
2323     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
2324                        Addr, Op.getOperand(2), JTI, UId);
2325   }
2326   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2327     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
2328                        PseudoSourceValue::getJumpTable(), 0,
2329                        false, false, 0);
2330     Chain = Addr.getValue(1);
2331     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
2332     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2333   } else {
2334     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
2335                        PseudoSourceValue::getJumpTable(), 0, false, false, 0);
2336     Chain = Addr.getValue(1);
2337     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
2338   }
2339 }
2340
2341 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2342   DebugLoc dl = Op.getDebugLoc();
2343   unsigned Opc;
2344
2345   switch (Op.getOpcode()) {
2346   default:
2347     assert(0 && "Invalid opcode!");
2348   case ISD::FP_TO_SINT:
2349     Opc = ARMISD::FTOSI;
2350     break;
2351   case ISD::FP_TO_UINT:
2352     Opc = ARMISD::FTOUI;
2353     break;
2354   }
2355   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
2356   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
2357 }
2358
2359 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2360   EVT VT = Op.getValueType();
2361   DebugLoc dl = Op.getDebugLoc();
2362   unsigned Opc;
2363
2364   switch (Op.getOpcode()) {
2365   default:
2366     assert(0 && "Invalid opcode!");
2367   case ISD::SINT_TO_FP:
2368     Opc = ARMISD::SITOF;
2369     break;
2370   case ISD::UINT_TO_FP:
2371     Opc = ARMISD::UITOF;
2372     break;
2373   }
2374
2375   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
2376   return DAG.getNode(Opc, dl, VT, Op);
2377 }
2378
2379 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
2380   // Implement fcopysign with a fabs and a conditional fneg.
2381   SDValue Tmp0 = Op.getOperand(0);
2382   SDValue Tmp1 = Op.getOperand(1);
2383   DebugLoc dl = Op.getDebugLoc();
2384   EVT VT = Op.getValueType();
2385   EVT SrcVT = Tmp1.getValueType();
2386   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
2387   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
2388   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
2389   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2390   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
2391 }
2392
2393 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
2394   MachineFunction &MF = DAG.getMachineFunction();
2395   MachineFrameInfo *MFI = MF.getFrameInfo();
2396   MFI->setReturnAddressIsTaken(true);
2397
2398   EVT VT = Op.getValueType();
2399   DebugLoc dl = Op.getDebugLoc();
2400   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2401   if (Depth) {
2402     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
2403     SDValue Offset = DAG.getConstant(4, MVT::i32);
2404     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
2405                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
2406                        NULL, 0, false, false, 0);
2407   }
2408
2409   // Return LR, which contains the return address. Mark it an implicit live-in.
2410   unsigned Reg = MF.addLiveIn(ARM::LR, ARM::GPRRegisterClass); 
2411   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
2412 }
2413
2414 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2415   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2416   MFI->setFrameAddressIsTaken(true);
2417
2418   EVT VT = Op.getValueType();
2419   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
2420   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2421   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
2422     ? ARM::R7 : ARM::R11;
2423   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2424   while (Depth--)
2425     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
2426                             false, false, 0);
2427   return FrameAddr;
2428 }
2429
2430 /// ExpandBIT_CONVERT - If the target supports VFP, this function is called to
2431 /// expand a bit convert where either the source or destination type is i64 to
2432 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
2433 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
2434 /// vectors), since the legalizer won't know what to do with that.
2435 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
2436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2437   DebugLoc dl = N->getDebugLoc();
2438   SDValue Op = N->getOperand(0);
2439
2440   // This function is only supposed to be called for i64 types, either as the
2441   // source or destination of the bit convert.
2442   EVT SrcVT = Op.getValueType();
2443   EVT DstVT = N->getValueType(0);
2444   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
2445          "ExpandBIT_CONVERT called for non-i64 type");
2446
2447   // Turn i64->f64 into VMOVDRR.
2448   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
2449     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2450                              DAG.getConstant(0, MVT::i32));
2451     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2452                              DAG.getConstant(1, MVT::i32));
2453     return DAG.getNode(ISD::BIT_CONVERT, dl, DstVT,
2454                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
2455   }
2456
2457   // Turn f64->i64 into VMOVRRD.
2458   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
2459     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
2460                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
2461     // Merge the pieces into a single i64 value.
2462     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
2463   }
2464
2465   return SDValue();
2466 }
2467
2468 /// getZeroVector - Returns a vector of specified type with all zero elements.
2469 ///
2470 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2471   assert(VT.isVector() && "Expected a vector type");
2472
2473   // Zero vectors are used to represent vector negation and in those cases
2474   // will be implemented with the NEON VNEG instruction.  However, VNEG does
2475   // not support i64 elements, so sometimes the zero vectors will need to be
2476   // explicitly constructed.  For those cases, and potentially other uses in
2477   // the future, always build zero vectors as <16 x i8> or <8 x i8> bitcasted
2478   // to their dest type.  This ensures they get CSE'd.
2479   SDValue Vec;
2480   SDValue Cst = DAG.getTargetConstant(0, MVT::i8);
2481   SmallVector<SDValue, 8> Ops;
2482   MVT TVT;
2483
2484   if (VT.getSizeInBits() == 64) {
2485     Ops.assign(8, Cst); TVT = MVT::v8i8;
2486   } else {
2487     Ops.assign(16, Cst); TVT = MVT::v16i8;
2488   }
2489   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2490
2491   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2492 }
2493
2494 /// getOnesVector - Returns a vector of specified type with all bits set.
2495 ///
2496 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2497   assert(VT.isVector() && "Expected a vector type");
2498
2499   // Always build ones vectors as <16 x i8> or <8 x i8> bitcasted to their
2500   // dest type. This ensures they get CSE'd.
2501   SDValue Vec;
2502   SDValue Cst = DAG.getTargetConstant(0xFF, MVT::i8);
2503   SmallVector<SDValue, 8> Ops;
2504   MVT TVT;
2505
2506   if (VT.getSizeInBits() == 64) {
2507     Ops.assign(8, Cst); TVT = MVT::v8i8;
2508   } else {
2509     Ops.assign(16, Cst); TVT = MVT::v16i8;
2510   }
2511   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, TVT, &Ops[0], Ops.size());
2512
2513   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2514 }
2515
2516 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
2517 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
2518 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
2519                                                 SelectionDAG &DAG) const {
2520   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2521   EVT VT = Op.getValueType();
2522   unsigned VTBits = VT.getSizeInBits();
2523   DebugLoc dl = Op.getDebugLoc();
2524   SDValue ShOpLo = Op.getOperand(0);
2525   SDValue ShOpHi = Op.getOperand(1);
2526   SDValue ShAmt  = Op.getOperand(2);
2527   SDValue ARMCC;
2528   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
2529
2530   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
2531
2532   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2533                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
2534   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
2535   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2536                                    DAG.getConstant(VTBits, MVT::i32));
2537   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
2538   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2539   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
2540
2541   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2542   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
2543                           ARMCC, DAG, dl);
2544   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
2545   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC,
2546                            CCR, Cmp);
2547
2548   SDValue Ops[2] = { Lo, Hi };
2549   return DAG.getMergeValues(Ops, 2, dl);
2550 }
2551
2552 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
2553 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
2554 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
2555                                                SelectionDAG &DAG) const {
2556   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
2557   EVT VT = Op.getValueType();
2558   unsigned VTBits = VT.getSizeInBits();
2559   DebugLoc dl = Op.getDebugLoc();
2560   SDValue ShOpLo = Op.getOperand(0);
2561   SDValue ShOpHi = Op.getOperand(1);
2562   SDValue ShAmt  = Op.getOperand(2);
2563   SDValue ARMCC;
2564
2565   assert(Op.getOpcode() == ISD::SHL_PARTS);
2566   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
2567                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
2568   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
2569   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
2570                                    DAG.getConstant(VTBits, MVT::i32));
2571   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
2572   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
2573
2574   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2575   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2576   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
2577                           ARMCC, DAG, dl);
2578   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
2579   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMCC,
2580                            CCR, Cmp);
2581
2582   SDValue Ops[2] = { Lo, Hi };
2583   return DAG.getMergeValues(Ops, 2, dl);
2584 }
2585
2586 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
2587                          const ARMSubtarget *ST) {
2588   EVT VT = N->getValueType(0);
2589   DebugLoc dl = N->getDebugLoc();
2590
2591   if (!ST->hasV6T2Ops())
2592     return SDValue();
2593
2594   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
2595   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
2596 }
2597
2598 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
2599                           const ARMSubtarget *ST) {
2600   EVT VT = N->getValueType(0);
2601   DebugLoc dl = N->getDebugLoc();
2602
2603   // Lower vector shifts on NEON to use VSHL.
2604   if (VT.isVector()) {
2605     assert(ST->hasNEON() && "unexpected vector shift");
2606
2607     // Left shifts translate directly to the vshiftu intrinsic.
2608     if (N->getOpcode() == ISD::SHL)
2609       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2610                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2611                          N->getOperand(0), N->getOperand(1));
2612
2613     assert((N->getOpcode() == ISD::SRA ||
2614             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2615
2616     // NEON uses the same intrinsics for both left and right shifts.  For
2617     // right shifts, the shift amounts are negative, so negate the vector of
2618     // shift amounts.
2619     EVT ShiftVT = N->getOperand(1).getValueType();
2620     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2621                                        getZeroVector(ShiftVT, DAG, dl),
2622                                        N->getOperand(1));
2623     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2624                                Intrinsic::arm_neon_vshifts :
2625                                Intrinsic::arm_neon_vshiftu);
2626     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2627                        DAG.getConstant(vshiftInt, MVT::i32),
2628                        N->getOperand(0), NegatedCount);
2629   }
2630
2631   // We can get here for a node like i32 = ISD::SHL i32, i64
2632   if (VT != MVT::i64)
2633     return SDValue();
2634
2635   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2636          "Unknown shift to lower!");
2637
2638   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2639   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2640       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2641     return SDValue();
2642
2643   // If we are in thumb mode, we don't have RRX.
2644   if (ST->isThumb1Only()) return SDValue();
2645
2646   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2647   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2648                            DAG.getConstant(0, MVT::i32));
2649   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2650                            DAG.getConstant(1, MVT::i32));
2651
2652   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2653   // captures the result into a carry flag.
2654   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2655   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2656
2657   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2658   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2659
2660   // Merge the pieces into a single i64 value.
2661  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2662 }
2663
2664 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2665   SDValue TmpOp0, TmpOp1;
2666   bool Invert = false;
2667   bool Swap = false;
2668   unsigned Opc = 0;
2669
2670   SDValue Op0 = Op.getOperand(0);
2671   SDValue Op1 = Op.getOperand(1);
2672   SDValue CC = Op.getOperand(2);
2673   EVT VT = Op.getValueType();
2674   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2675   DebugLoc dl = Op.getDebugLoc();
2676
2677   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2678     switch (SetCCOpcode) {
2679     default: llvm_unreachable("Illegal FP comparison"); break;
2680     case ISD::SETUNE:
2681     case ISD::SETNE:  Invert = true; // Fallthrough
2682     case ISD::SETOEQ:
2683     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2684     case ISD::SETOLT:
2685     case ISD::SETLT: Swap = true; // Fallthrough
2686     case ISD::SETOGT:
2687     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2688     case ISD::SETOLE:
2689     case ISD::SETLE:  Swap = true; // Fallthrough
2690     case ISD::SETOGE:
2691     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2692     case ISD::SETUGE: Swap = true; // Fallthrough
2693     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2694     case ISD::SETUGT: Swap = true; // Fallthrough
2695     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2696     case ISD::SETUEQ: Invert = true; // Fallthrough
2697     case ISD::SETONE:
2698       // Expand this to (OLT | OGT).
2699       TmpOp0 = Op0;
2700       TmpOp1 = Op1;
2701       Opc = ISD::OR;
2702       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2703       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2704       break;
2705     case ISD::SETUO: Invert = true; // Fallthrough
2706     case ISD::SETO:
2707       // Expand this to (OLT | OGE).
2708       TmpOp0 = Op0;
2709       TmpOp1 = Op1;
2710       Opc = ISD::OR;
2711       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2712       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2713       break;
2714     }
2715   } else {
2716     // Integer comparisons.
2717     switch (SetCCOpcode) {
2718     default: llvm_unreachable("Illegal integer comparison"); break;
2719     case ISD::SETNE:  Invert = true;
2720     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2721     case ISD::SETLT:  Swap = true;
2722     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2723     case ISD::SETLE:  Swap = true;
2724     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2725     case ISD::SETULT: Swap = true;
2726     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2727     case ISD::SETULE: Swap = true;
2728     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2729     }
2730
2731     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2732     if (Opc == ARMISD::VCEQ) {
2733
2734       SDValue AndOp;
2735       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2736         AndOp = Op0;
2737       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2738         AndOp = Op1;
2739
2740       // Ignore bitconvert.
2741       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2742         AndOp = AndOp.getOperand(0);
2743
2744       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2745         Opc = ARMISD::VTST;
2746         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2747         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2748         Invert = !Invert;
2749       }
2750     }
2751   }
2752
2753   if (Swap)
2754     std::swap(Op0, Op1);
2755
2756   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2757
2758   if (Invert)
2759     Result = DAG.getNOT(dl, Result, VT);
2760
2761   return Result;
2762 }
2763
2764 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
2765 /// valid vector constant for a NEON instruction with a "modified immediate"
2766 /// operand (e.g., VMOV).  If so, return either the constant being
2767 /// splatted or the encoded value, depending on the DoEncode parameter.  The
2768 /// format of the encoded value is: bit12=Op, bits11-8=Cmode,
2769 /// bits7-0=Immediate.
2770 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2771                                  unsigned SplatBitSize, SelectionDAG &DAG,
2772                                  bool isVMOV, bool DoEncode) {
2773   unsigned Op, Cmode, Imm;
2774   EVT VT;
2775
2776   // SplatBitSize is set to the smallest size that splats the vector, so a
2777   // zero vector will always have SplatBitSize == 8.  However, NEON modified
2778   // immediate instructions others than VMOV do not support the 8-bit encoding
2779   // of a zero vector, and the default encoding of zero is supposed to be the
2780   // 32-bit version.
2781   if (SplatBits == 0)
2782     SplatBitSize = 32;
2783
2784   Op = 0;
2785   switch (SplatBitSize) {
2786   case 8:
2787     // Any 1-byte value is OK.  Op=0, Cmode=1110.
2788     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2789     Cmode = 0xe;
2790     Imm = SplatBits;
2791     VT = MVT::i8;
2792     break;
2793
2794   case 16:
2795     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2796     VT = MVT::i16;
2797     if ((SplatBits & ~0xff) == 0) {
2798       // Value = 0x00nn: Op=x, Cmode=100x.
2799       Cmode = 0x8;
2800       Imm = SplatBits;
2801       break;
2802     }
2803     if ((SplatBits & ~0xff00) == 0) {
2804       // Value = 0xnn00: Op=x, Cmode=101x.
2805       Cmode = 0xa;
2806       Imm = SplatBits >> 8;
2807       break;
2808     }
2809     return SDValue();
2810
2811   case 32:
2812     // NEON's 32-bit VMOV supports splat values where:
2813     // * only one byte is nonzero, or
2814     // * the least significant byte is 0xff and the second byte is nonzero, or
2815     // * the least significant 2 bytes are 0xff and the third is nonzero.
2816     VT = MVT::i32;
2817     if ((SplatBits & ~0xff) == 0) {
2818       // Value = 0x000000nn: Op=x, Cmode=000x.
2819       Cmode = 0;
2820       Imm = SplatBits;
2821       break;
2822     }
2823     if ((SplatBits & ~0xff00) == 0) {
2824       // Value = 0x0000nn00: Op=x, Cmode=001x.
2825       Cmode = 0x2;
2826       Imm = SplatBits >> 8;
2827       break;
2828     }
2829     if ((SplatBits & ~0xff0000) == 0) {
2830       // Value = 0x00nn0000: Op=x, Cmode=010x.
2831       Cmode = 0x4;
2832       Imm = SplatBits >> 16;
2833       break;
2834     }
2835     if ((SplatBits & ~0xff000000) == 0) {
2836       // Value = 0xnn000000: Op=x, Cmode=011x.
2837       Cmode = 0x6;
2838       Imm = SplatBits >> 24;
2839       break;
2840     }
2841
2842     if ((SplatBits & ~0xffff) == 0 &&
2843         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
2844       // Value = 0x0000nnff: Op=x, Cmode=1100.
2845       Cmode = 0xc;
2846       Imm = SplatBits >> 8;
2847       SplatBits |= 0xff;
2848       break;
2849     }
2850
2851     if ((SplatBits & ~0xffffff) == 0 &&
2852         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
2853       // Value = 0x00nnffff: Op=x, Cmode=1101.
2854       Cmode = 0xd;
2855       Imm = SplatBits >> 16;
2856       SplatBits |= 0xffff;
2857       break;
2858     }
2859
2860     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2861     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2862     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2863     // and fall through here to test for a valid 64-bit splat.  But, then the
2864     // caller would also need to check and handle the change in size.
2865     return SDValue();
2866
2867   case 64: {
2868     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2869     if (!isVMOV)
2870       return SDValue();
2871     uint64_t BitMask = 0xff;
2872     uint64_t Val = 0;
2873     unsigned ImmMask = 1;
2874     Imm = 0;
2875     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2876       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
2877         Val |= BitMask;
2878         Imm |= ImmMask;
2879       } else if ((SplatBits & BitMask) != 0) {
2880         return SDValue();
2881       }
2882       BitMask <<= 8;
2883       ImmMask <<= 1;
2884     }
2885     // Op=1, Cmode=1110.
2886     Op = 1;
2887     Cmode = 0xe;
2888     SplatBits = Val;
2889     VT = MVT::i64;
2890     break;
2891   }
2892
2893   default:
2894     llvm_unreachable("unexpected size for EncodeNEONModImm");
2895     return SDValue();
2896   }
2897
2898   if (DoEncode)
2899     return DAG.getTargetConstant((Op << 12) | (Cmode << 8) | Imm, MVT::i32);
2900   return DAG.getTargetConstant(SplatBits, VT);
2901 }
2902
2903
2904 /// getNEONModImm - If this is a valid vector constant for a NEON instruction
2905 /// with a "modified immediate" operand (e.g., VMOV) of the specified element
2906 /// size, return the encoded value for that immediate.  The ByteSize field
2907 /// indicates the number of bytes of each element [1248].
2908 SDValue ARM::getNEONModImm(SDNode *N, unsigned ByteSize, bool isVMOV,
2909                            SelectionDAG &DAG) {
2910   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2911   APInt SplatBits, SplatUndef;
2912   unsigned SplatBitSize;
2913   bool HasAnyUndefs;
2914   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2915                                       HasAnyUndefs, ByteSize * 8))
2916     return SDValue();
2917
2918   if (SplatBitSize > ByteSize * 8)
2919     return SDValue();
2920
2921   return isNEONModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2922                            SplatBitSize, DAG, isVMOV, true);
2923 }
2924
2925 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
2926                        bool &ReverseVEXT, unsigned &Imm) {
2927   unsigned NumElts = VT.getVectorNumElements();
2928   ReverseVEXT = false;
2929   Imm = M[0];
2930
2931   // If this is a VEXT shuffle, the immediate value is the index of the first
2932   // element.  The other shuffle indices must be the successive elements after
2933   // the first one.
2934   unsigned ExpectedElt = Imm;
2935   for (unsigned i = 1; i < NumElts; ++i) {
2936     // Increment the expected index.  If it wraps around, it may still be
2937     // a VEXT but the source vectors must be swapped.
2938     ExpectedElt += 1;
2939     if (ExpectedElt == NumElts * 2) {
2940       ExpectedElt = 0;
2941       ReverseVEXT = true;
2942     }
2943
2944     if (ExpectedElt != static_cast<unsigned>(M[i]))
2945       return false;
2946   }
2947
2948   // Adjust the index value if the source operands will be swapped.
2949   if (ReverseVEXT)
2950     Imm -= NumElts;
2951
2952   return true;
2953 }
2954
2955 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2956 /// instruction with the specified blocksize.  (The order of the elements
2957 /// within each block of the vector is reversed.)
2958 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
2959                        unsigned BlockSize) {
2960   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2961          "Only possible block sizes for VREV are: 16, 32, 64");
2962
2963   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2964   if (EltSz == 64)
2965     return false;
2966
2967   unsigned NumElts = VT.getVectorNumElements();
2968   unsigned BlockElts = M[0] + 1;
2969
2970   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2971     return false;
2972
2973   for (unsigned i = 0; i < NumElts; ++i) {
2974     if ((unsigned) M[i] !=
2975         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2976       return false;
2977   }
2978
2979   return true;
2980 }
2981
2982 static bool isVTRNMask(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   for (unsigned i = 0; i < NumElts; i += 2) {
2991     if ((unsigned) M[i] != i + WhichResult ||
2992         (unsigned) M[i+1] != i + NumElts + WhichResult)
2993       return false;
2994   }
2995   return true;
2996 }
2997
2998 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
2999 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3000 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3001 static bool isVTRN_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3002                                 unsigned &WhichResult) {
3003   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3004   if (EltSz == 64)
3005     return false;
3006
3007   unsigned NumElts = VT.getVectorNumElements();
3008   WhichResult = (M[0] == 0 ? 0 : 1);
3009   for (unsigned i = 0; i < NumElts; i += 2) {
3010     if ((unsigned) M[i] != i + WhichResult ||
3011         (unsigned) M[i+1] != i + WhichResult)
3012       return false;
3013   }
3014   return true;
3015 }
3016
3017 static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
3018                        unsigned &WhichResult) {
3019   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3020   if (EltSz == 64)
3021     return false;
3022
3023   unsigned NumElts = VT.getVectorNumElements();
3024   WhichResult = (M[0] == 0 ? 0 : 1);
3025   for (unsigned i = 0; i != NumElts; ++i) {
3026     if ((unsigned) M[i] != 2 * i + WhichResult)
3027       return false;
3028   }
3029
3030   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3031   if (VT.is64BitVector() && EltSz == 32)
3032     return false;
3033
3034   return true;
3035 }
3036
3037 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3038 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3039 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3040 static bool isVUZP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3041                                 unsigned &WhichResult) {
3042   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3043   if (EltSz == 64)
3044     return false;
3045
3046   unsigned Half = VT.getVectorNumElements() / 2;
3047   WhichResult = (M[0] == 0 ? 0 : 1);
3048   for (unsigned j = 0; j != 2; ++j) {
3049     unsigned Idx = WhichResult;
3050     for (unsigned i = 0; i != Half; ++i) {
3051       if ((unsigned) M[i + j * Half] != Idx)
3052         return false;
3053       Idx += 2;
3054     }
3055   }
3056
3057   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3058   if (VT.is64BitVector() && EltSz == 32)
3059     return false;
3060
3061   return true;
3062 }
3063
3064 static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
3065                        unsigned &WhichResult) {
3066   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3067   if (EltSz == 64)
3068     return false;
3069
3070   unsigned NumElts = VT.getVectorNumElements();
3071   WhichResult = (M[0] == 0 ? 0 : 1);
3072   unsigned Idx = WhichResult * NumElts / 2;
3073   for (unsigned i = 0; i != NumElts; i += 2) {
3074     if ((unsigned) M[i] != Idx ||
3075         (unsigned) M[i+1] != Idx + NumElts)
3076       return false;
3077     Idx += 1;
3078   }
3079
3080   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3081   if (VT.is64BitVector() && EltSz == 32)
3082     return false;
3083
3084   return true;
3085 }
3086
3087 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3088 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3089 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3090 static bool isVZIP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
3091                                 unsigned &WhichResult) {
3092   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3093   if (EltSz == 64)
3094     return false;
3095
3096   unsigned NumElts = VT.getVectorNumElements();
3097   WhichResult = (M[0] == 0 ? 0 : 1);
3098   unsigned Idx = WhichResult * NumElts / 2;
3099   for (unsigned i = 0; i != NumElts; i += 2) {
3100     if ((unsigned) M[i] != Idx ||
3101         (unsigned) M[i+1] != Idx)
3102       return false;
3103     Idx += 1;
3104   }
3105
3106   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3107   if (VT.is64BitVector() && EltSz == 32)
3108     return false;
3109
3110   return true;
3111 }
3112
3113
3114 static SDValue BuildSplat(SDValue Val, EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3115   // Canonicalize all-zeros and all-ones vectors.
3116   ConstantSDNode *ConstVal = cast<ConstantSDNode>(Val.getNode());
3117   if (ConstVal->isNullValue())
3118     return getZeroVector(VT, DAG, dl);
3119   if (ConstVal->isAllOnesValue())
3120     return getOnesVector(VT, DAG, dl);
3121
3122   EVT CanonicalVT;
3123   if (VT.is64BitVector()) {
3124     switch (Val.getValueType().getSizeInBits()) {
3125     case 8:  CanonicalVT = MVT::v8i8; break;
3126     case 16: CanonicalVT = MVT::v4i16; break;
3127     case 32: CanonicalVT = MVT::v2i32; break;
3128     case 64: CanonicalVT = MVT::v1i64; break;
3129     default: llvm_unreachable("unexpected splat element type"); break;
3130     }
3131   } else {
3132     assert(VT.is128BitVector() && "unknown splat vector size");
3133     switch (Val.getValueType().getSizeInBits()) {
3134     case 8:  CanonicalVT = MVT::v16i8; break;
3135     case 16: CanonicalVT = MVT::v8i16; break;
3136     case 32: CanonicalVT = MVT::v4i32; break;
3137     case 64: CanonicalVT = MVT::v2i64; break;
3138     default: llvm_unreachable("unexpected splat element type"); break;
3139     }
3140   }
3141
3142   // Build a canonical splat for this value.
3143   SmallVector<SDValue, 8> Ops;
3144   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
3145   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
3146                             Ops.size());
3147   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
3148 }
3149
3150 // If this is a case we can't handle, return null and let the default
3151 // expansion code take care of it.
3152 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3153   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3154   DebugLoc dl = Op.getDebugLoc();
3155   EVT VT = Op.getValueType();
3156
3157   APInt SplatBits, SplatUndef;
3158   unsigned SplatBitSize;
3159   bool HasAnyUndefs;
3160   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3161     if (SplatBitSize <= 64) {
3162       // Check if an immediate VMOV works.
3163       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
3164                                       SplatUndef.getZExtValue(),
3165                                       SplatBitSize, DAG, true, false);
3166       if (Val.getNode())
3167         return BuildSplat(Val, VT, DAG, dl);
3168     }
3169   }
3170
3171   // Scan through the operands to see if only one value is used.
3172   unsigned NumElts = VT.getVectorNumElements();
3173   bool isOnlyLowElement = true;
3174   bool usesOnlyOneValue = true;
3175   bool isConstant = true;
3176   SDValue Value;
3177   for (unsigned i = 0; i < NumElts; ++i) {
3178     SDValue V = Op.getOperand(i);
3179     if (V.getOpcode() == ISD::UNDEF)
3180       continue;
3181     if (i > 0)
3182       isOnlyLowElement = false;
3183     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
3184       isConstant = false;
3185
3186     if (!Value.getNode())
3187       Value = V;
3188     else if (V != Value)
3189       usesOnlyOneValue = false;
3190   }
3191
3192   if (!Value.getNode())
3193     return DAG.getUNDEF(VT);
3194
3195   if (isOnlyLowElement)
3196     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
3197
3198   // If all elements are constants, fall back to the default expansion, which
3199   // will generate a load from the constant pool.
3200   if (isConstant)
3201     return SDValue();
3202
3203   // Use VDUP for non-constant splats.
3204   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3205   if (usesOnlyOneValue && EltSize <= 32)
3206     return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
3207
3208   // Vectors with 32- or 64-bit elements can be built by directly assigning
3209   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
3210   // will be legalized.
3211   if (EltSize >= 32) {
3212     // Do the expansion with floating-point types, since that is what the VFP
3213     // registers are defined to use, and since i64 is not legal.
3214     EVT EltVT = EVT::getFloatingPointVT(EltSize);
3215     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
3216     SmallVector<SDValue, 8> Ops;
3217     for (unsigned i = 0; i < NumElts; ++i)
3218       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, dl, EltVT, Op.getOperand(i)));
3219     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
3220     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Val);
3221   }
3222
3223   return SDValue();
3224 }
3225
3226 /// isShuffleMaskLegal - Targets can use this to indicate that they only
3227 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
3228 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
3229 /// are assumed to be legal.
3230 bool
3231 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
3232                                       EVT VT) const {
3233   if (VT.getVectorNumElements() == 4 &&
3234       (VT.is128BitVector() || VT.is64BitVector())) {
3235     unsigned PFIndexes[4];
3236     for (unsigned i = 0; i != 4; ++i) {
3237       if (M[i] < 0)
3238         PFIndexes[i] = 8;
3239       else
3240         PFIndexes[i] = M[i];
3241     }
3242
3243     // Compute the index in the perfect shuffle table.
3244     unsigned PFTableIndex =
3245       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3246     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3247     unsigned Cost = (PFEntry >> 30);
3248
3249     if (Cost <= 4)
3250       return true;
3251   }
3252
3253   bool ReverseVEXT;
3254   unsigned Imm, WhichResult;
3255
3256   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3257   return (EltSize >= 32 ||
3258           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
3259           isVREVMask(M, VT, 64) ||
3260           isVREVMask(M, VT, 32) ||
3261           isVREVMask(M, VT, 16) ||
3262           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
3263           isVTRNMask(M, VT, WhichResult) ||
3264           isVUZPMask(M, VT, WhichResult) ||
3265           isVZIPMask(M, VT, WhichResult) ||
3266           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
3267           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
3268           isVZIP_v_undef_Mask(M, VT, WhichResult));
3269 }
3270
3271 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
3272 /// the specified operations to build the shuffle.
3273 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
3274                                       SDValue RHS, SelectionDAG &DAG,
3275                                       DebugLoc dl) {
3276   unsigned OpNum = (PFEntry >> 26) & 0x0F;
3277   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
3278   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
3279
3280   enum {
3281     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
3282     OP_VREV,
3283     OP_VDUP0,
3284     OP_VDUP1,
3285     OP_VDUP2,
3286     OP_VDUP3,
3287     OP_VEXT1,
3288     OP_VEXT2,
3289     OP_VEXT3,
3290     OP_VUZPL, // VUZP, left result
3291     OP_VUZPR, // VUZP, right result
3292     OP_VZIPL, // VZIP, left result
3293     OP_VZIPR, // VZIP, right result
3294     OP_VTRNL, // VTRN, left result
3295     OP_VTRNR  // VTRN, right result
3296   };
3297
3298   if (OpNum == OP_COPY) {
3299     if (LHSID == (1*9+2)*9+3) return LHS;
3300     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
3301     return RHS;
3302   }
3303
3304   SDValue OpLHS, OpRHS;
3305   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
3306   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
3307   EVT VT = OpLHS.getValueType();
3308
3309   switch (OpNum) {
3310   default: llvm_unreachable("Unknown shuffle opcode!");
3311   case OP_VREV:
3312     return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
3313   case OP_VDUP0:
3314   case OP_VDUP1:
3315   case OP_VDUP2:
3316   case OP_VDUP3:
3317     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
3318                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
3319   case OP_VEXT1:
3320   case OP_VEXT2:
3321   case OP_VEXT3:
3322     return DAG.getNode(ARMISD::VEXT, dl, VT,
3323                        OpLHS, OpRHS,
3324                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
3325   case OP_VUZPL:
3326   case OP_VUZPR:
3327     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
3328                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
3329   case OP_VZIPL:
3330   case OP_VZIPR:
3331     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
3332                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
3333   case OP_VTRNL:
3334   case OP_VTRNR:
3335     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
3336                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
3337   }
3338 }
3339
3340 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3341   SDValue V1 = Op.getOperand(0);
3342   SDValue V2 = Op.getOperand(1);
3343   DebugLoc dl = Op.getDebugLoc();
3344   EVT VT = Op.getValueType();
3345   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
3346   SmallVector<int, 8> ShuffleMask;
3347
3348   // Convert shuffles that are directly supported on NEON to target-specific
3349   // DAG nodes, instead of keeping them as shuffles and matching them again
3350   // during code selection.  This is more efficient and avoids the possibility
3351   // of inconsistencies between legalization and selection.
3352   // FIXME: floating-point vectors should be canonicalized to integer vectors
3353   // of the same time so that they get CSEd properly.
3354   SVN->getMask(ShuffleMask);
3355
3356   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3357   if (EltSize <= 32) {
3358     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
3359       int Lane = SVN->getSplatIndex();
3360       // If this is undef splat, generate it via "just" vdup, if possible.
3361       if (Lane == -1) Lane = 0;
3362
3363       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3364         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
3365       }
3366       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
3367                          DAG.getConstant(Lane, MVT::i32));
3368     }
3369
3370     bool ReverseVEXT;
3371     unsigned Imm;
3372     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
3373       if (ReverseVEXT)
3374         std::swap(V1, V2);
3375       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
3376                          DAG.getConstant(Imm, MVT::i32));
3377     }
3378
3379     if (isVREVMask(ShuffleMask, VT, 64))
3380       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
3381     if (isVREVMask(ShuffleMask, VT, 32))
3382       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
3383     if (isVREVMask(ShuffleMask, VT, 16))
3384       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
3385
3386     // Check for Neon shuffles that modify both input vectors in place.
3387     // If both results are used, i.e., if there are two shuffles with the same
3388     // source operands and with masks corresponding to both results of one of
3389     // these operations, DAG memoization will ensure that a single node is
3390     // used for both shuffles.
3391     unsigned WhichResult;
3392     if (isVTRNMask(ShuffleMask, VT, WhichResult))
3393       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
3394                          V1, V2).getValue(WhichResult);
3395     if (isVUZPMask(ShuffleMask, VT, WhichResult))
3396       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
3397                          V1, V2).getValue(WhichResult);
3398     if (isVZIPMask(ShuffleMask, VT, WhichResult))
3399       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
3400                          V1, V2).getValue(WhichResult);
3401
3402     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
3403       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
3404                          V1, V1).getValue(WhichResult);
3405     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
3406       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
3407                          V1, V1).getValue(WhichResult);
3408     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
3409       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
3410                          V1, V1).getValue(WhichResult);
3411   }
3412
3413   // If the shuffle is not directly supported and it has 4 elements, use
3414   // the PerfectShuffle-generated table to synthesize it from other shuffles.
3415   unsigned NumElts = VT.getVectorNumElements();
3416   if (NumElts == 4) {
3417     unsigned PFIndexes[4];
3418     for (unsigned i = 0; i != 4; ++i) {
3419       if (ShuffleMask[i] < 0)
3420         PFIndexes[i] = 8;
3421       else
3422         PFIndexes[i] = ShuffleMask[i];
3423     }
3424
3425     // Compute the index in the perfect shuffle table.
3426     unsigned PFTableIndex =
3427       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3428     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3429     unsigned Cost = (PFEntry >> 30);
3430
3431     if (Cost <= 4)
3432       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
3433   }
3434
3435   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
3436   if (EltSize >= 32) {
3437     // Do the expansion with floating-point types, since that is what the VFP
3438     // registers are defined to use, and since i64 is not legal.
3439     EVT EltVT = EVT::getFloatingPointVT(EltSize);
3440     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
3441     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, VecVT, V1);
3442     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, VecVT, V2);
3443     SmallVector<SDValue, 8> Ops;
3444     for (unsigned i = 0; i < NumElts; ++i) {
3445       if (ShuffleMask[i] < 0)
3446         Ops.push_back(DAG.getUNDEF(EltVT));
3447       else
3448         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3449                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
3450                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
3451                                                   MVT::i32)));
3452     }
3453     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
3454     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Val);
3455   }
3456
3457   return SDValue();
3458 }
3459
3460 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
3461   EVT VT = Op.getValueType();
3462   DebugLoc dl = Op.getDebugLoc();
3463   SDValue Vec = Op.getOperand(0);
3464   SDValue Lane = Op.getOperand(1);
3465   assert(VT == MVT::i32 &&
3466          Vec.getValueType().getVectorElementType().getSizeInBits() < 32 &&
3467          "unexpected type for custom-lowering vector extract");
3468   return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
3469 }
3470
3471 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3472   // The only time a CONCAT_VECTORS operation can have legal types is when
3473   // two 64-bit vectors are concatenated to a 128-bit vector.
3474   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
3475          "unexpected CONCAT_VECTORS");
3476   DebugLoc dl = Op.getDebugLoc();
3477   SDValue Val = DAG.getUNDEF(MVT::v2f64);
3478   SDValue Op0 = Op.getOperand(0);
3479   SDValue Op1 = Op.getOperand(1);
3480   if (Op0.getOpcode() != ISD::UNDEF)
3481     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
3482                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
3483                       DAG.getIntPtrConstant(0));
3484   if (Op1.getOpcode() != ISD::UNDEF)
3485     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
3486                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
3487                       DAG.getIntPtrConstant(1));
3488   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
3489 }
3490
3491 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3492   switch (Op.getOpcode()) {
3493   default: llvm_unreachable("Don't know how to custom lower this!");
3494   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
3495   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
3496   case ISD::GlobalAddress:
3497     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
3498       LowerGlobalAddressELF(Op, DAG);
3499   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
3500   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
3501   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
3502   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
3503   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
3504   case ISD::VASTART:       return LowerVASTART(Op, DAG);
3505   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
3506   case ISD::SINT_TO_FP:
3507   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
3508   case ISD::FP_TO_SINT:
3509   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
3510   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
3511   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
3512   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
3513   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
3514   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
3515   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
3516   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
3517                                                                Subtarget);
3518   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
3519   case ISD::SHL:
3520   case ISD::SRL:
3521   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
3522   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
3523   case ISD::SRL_PARTS:
3524   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
3525   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
3526   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
3527   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
3528   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
3529   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3530   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
3531   }
3532   return SDValue();
3533 }
3534
3535 /// ReplaceNodeResults - Replace the results of node with an illegal result
3536 /// type with new values built out of custom code.
3537 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
3538                                            SmallVectorImpl<SDValue>&Results,
3539                                            SelectionDAG &DAG) const {
3540   SDValue Res;
3541   switch (N->getOpcode()) {
3542   default:
3543     llvm_unreachable("Don't know how to custom expand this!");
3544     break;
3545   case ISD::BIT_CONVERT:
3546     Res = ExpandBIT_CONVERT(N, DAG);
3547     break;
3548   case ISD::SRL:
3549   case ISD::SRA:
3550     Res = LowerShift(N, DAG, Subtarget);
3551     break;
3552   }
3553   if (Res.getNode())
3554     Results.push_back(Res);
3555 }
3556
3557 //===----------------------------------------------------------------------===//
3558 //                           ARM Scheduler Hooks
3559 //===----------------------------------------------------------------------===//
3560
3561 MachineBasicBlock *
3562 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
3563                                      MachineBasicBlock *BB,
3564                                      unsigned Size) const {
3565   unsigned dest    = MI->getOperand(0).getReg();
3566   unsigned ptr     = MI->getOperand(1).getReg();
3567   unsigned oldval  = MI->getOperand(2).getReg();
3568   unsigned newval  = MI->getOperand(3).getReg();
3569   unsigned scratch = BB->getParent()->getRegInfo()
3570     .createVirtualRegister(ARM::GPRRegisterClass);
3571   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3572   DebugLoc dl = MI->getDebugLoc();
3573   bool isThumb2 = Subtarget->isThumb2();
3574
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::t2LDREXB : 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   MachineFunction *MF = BB->getParent();
3593   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3594   MachineFunction::iterator It = BB;
3595   ++It; // insert the new blocks after the current block
3596
3597   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
3598   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
3599   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
3600   MF->insert(It, loop1MBB);
3601   MF->insert(It, loop2MBB);
3602   MF->insert(It, exitMBB);
3603   exitMBB->transferSuccessors(BB);
3604
3605   //  thisMBB:
3606   //   ...
3607   //   fallthrough --> loop1MBB
3608   BB->addSuccessor(loop1MBB);
3609
3610   // loop1MBB:
3611   //   ldrex dest, [ptr]
3612   //   cmp dest, oldval
3613   //   bne exitMBB
3614   BB = loop1MBB;
3615   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
3616   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
3617                  .addReg(dest).addReg(oldval));
3618   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
3619     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
3620   BB->addSuccessor(loop2MBB);
3621   BB->addSuccessor(exitMBB);
3622
3623   // loop2MBB:
3624   //   strex scratch, newval, [ptr]
3625   //   cmp scratch, #0
3626   //   bne loop1MBB
3627   BB = loop2MBB;
3628   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval)
3629                  .addReg(ptr));
3630   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
3631                  .addReg(scratch).addImm(0));
3632   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
3633     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
3634   BB->addSuccessor(loop1MBB);
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::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
3648                                     unsigned Size, unsigned BinOpcode) const {
3649   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
3650   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3651
3652   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3653   MachineFunction *MF = BB->getParent();
3654   MachineFunction::iterator It = BB;
3655   ++It;
3656
3657   unsigned dest = MI->getOperand(0).getReg();
3658   unsigned ptr = MI->getOperand(1).getReg();
3659   unsigned incr = MI->getOperand(2).getReg();
3660   DebugLoc dl = MI->getDebugLoc();
3661
3662   bool isThumb2 = Subtarget->isThumb2();
3663   unsigned ldrOpc, strOpc;
3664   switch (Size) {
3665   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
3666   case 1:
3667     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
3668     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
3669     break;
3670   case 2:
3671     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
3672     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
3673     break;
3674   case 4:
3675     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
3676     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
3677     break;
3678   }
3679
3680   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
3681   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
3682   MF->insert(It, loopMBB);
3683   MF->insert(It, exitMBB);
3684   exitMBB->transferSuccessors(BB);
3685
3686   MachineRegisterInfo &RegInfo = MF->getRegInfo();
3687   unsigned scratch = RegInfo.createVirtualRegister(ARM::GPRRegisterClass);
3688   unsigned scratch2 = (!BinOpcode) ? incr :
3689     RegInfo.createVirtualRegister(ARM::GPRRegisterClass);
3690
3691   //  thisMBB:
3692   //   ...
3693   //   fallthrough --> loopMBB
3694   BB->addSuccessor(loopMBB);
3695
3696   //  loopMBB:
3697   //   ldrex dest, ptr
3698   //   <binop> scratch2, dest, incr
3699   //   strex scratch, scratch2, ptr
3700   //   cmp scratch, #0
3701   //   bne- loopMBB
3702   //   fallthrough --> exitMBB
3703   BB = loopMBB;
3704   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr));
3705   if (BinOpcode) {
3706     // operand order needs to go the other way for NAND
3707     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
3708       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
3709                      addReg(incr).addReg(dest)).addReg(0);
3710     else
3711       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
3712                      addReg(dest).addReg(incr)).addReg(0);
3713   }
3714
3715   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2)
3716                  .addReg(ptr));
3717   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
3718                  .addReg(scratch).addImm(0));
3719   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
3720     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
3721
3722   BB->addSuccessor(loopMBB);
3723   BB->addSuccessor(exitMBB);
3724
3725   //  exitMBB:
3726   //   ...
3727   BB = exitMBB;
3728
3729   MF->DeleteMachineInstr(MI);   // The instruction is gone now.
3730
3731   return BB;
3732 }
3733
3734 MachineBasicBlock *
3735 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
3736                                                MachineBasicBlock *BB) const {
3737   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3738   DebugLoc dl = MI->getDebugLoc();
3739   bool isThumb2 = Subtarget->isThumb2();
3740   switch (MI->getOpcode()) {
3741   default:
3742     MI->dump();
3743     llvm_unreachable("Unexpected instr type to insert");
3744
3745   case ARM::ATOMIC_LOAD_ADD_I8:
3746      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
3747   case ARM::ATOMIC_LOAD_ADD_I16:
3748      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
3749   case ARM::ATOMIC_LOAD_ADD_I32:
3750      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
3751
3752   case ARM::ATOMIC_LOAD_AND_I8:
3753      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
3754   case ARM::ATOMIC_LOAD_AND_I16:
3755      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
3756   case ARM::ATOMIC_LOAD_AND_I32:
3757      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
3758
3759   case ARM::ATOMIC_LOAD_OR_I8:
3760      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
3761   case ARM::ATOMIC_LOAD_OR_I16:
3762      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
3763   case ARM::ATOMIC_LOAD_OR_I32:
3764      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
3765
3766   case ARM::ATOMIC_LOAD_XOR_I8:
3767      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
3768   case ARM::ATOMIC_LOAD_XOR_I16:
3769      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
3770   case ARM::ATOMIC_LOAD_XOR_I32:
3771      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
3772
3773   case ARM::ATOMIC_LOAD_NAND_I8:
3774      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
3775   case ARM::ATOMIC_LOAD_NAND_I16:
3776      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
3777   case ARM::ATOMIC_LOAD_NAND_I32:
3778      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
3779
3780   case ARM::ATOMIC_LOAD_SUB_I8:
3781      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
3782   case ARM::ATOMIC_LOAD_SUB_I16:
3783      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
3784   case ARM::ATOMIC_LOAD_SUB_I32:
3785      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
3786
3787   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
3788   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
3789   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
3790
3791   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
3792   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
3793   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
3794
3795   case ARM::tMOVCCr_pseudo: {
3796     // To "insert" a SELECT_CC instruction, we actually have to insert the
3797     // diamond control-flow pattern.  The incoming instruction knows the
3798     // destination vreg to set, the condition code register to branch on, the
3799     // true/false values to select between, and a branch opcode to use.
3800     const BasicBlock *LLVM_BB = BB->getBasicBlock();
3801     MachineFunction::iterator It = BB;
3802     ++It;
3803
3804     //  thisMBB:
3805     //  ...
3806     //   TrueVal = ...
3807     //   cmpTY ccX, r1, r2
3808     //   bCC copy1MBB
3809     //   fallthrough --> copy0MBB
3810     MachineBasicBlock *thisMBB  = BB;
3811     MachineFunction *F = BB->getParent();
3812     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3813     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
3814     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
3815       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
3816     F->insert(It, copy0MBB);
3817     F->insert(It, sinkMBB);
3818     // Update machine-CFG edges by first adding all successors of the current
3819     // block to the new block which will contain the Phi node for the select.
3820     for (MachineBasicBlock::succ_iterator I = BB->succ_begin(), 
3821            E = BB->succ_end(); I != E; ++I)
3822       sinkMBB->addSuccessor(*I);
3823     // Next, remove all successors of the current block, and add the true
3824     // and fallthrough blocks as its successors.
3825     while (!BB->succ_empty())
3826       BB->removeSuccessor(BB->succ_begin());
3827     BB->addSuccessor(copy0MBB);
3828     BB->addSuccessor(sinkMBB);
3829
3830     //  copy0MBB:
3831     //   %FalseValue = ...
3832     //   # fallthrough to sinkMBB
3833     BB = copy0MBB;
3834
3835     // Update machine-CFG edges
3836     BB->addSuccessor(sinkMBB);
3837
3838     //  sinkMBB:
3839     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
3840     //  ...
3841     BB = sinkMBB;
3842     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
3843       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
3844       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
3845
3846     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
3847     return BB;
3848   }
3849
3850   case ARM::tANDsp:
3851   case ARM::tADDspr_:
3852   case ARM::tSUBspi_:
3853   case ARM::t2SUBrSPi_:
3854   case ARM::t2SUBrSPi12_:
3855   case ARM::t2SUBrSPs_: {
3856     MachineFunction *MF = BB->getParent();
3857     unsigned DstReg = MI->getOperand(0).getReg();
3858     unsigned SrcReg = MI->getOperand(1).getReg();
3859     bool DstIsDead = MI->getOperand(0).isDead();
3860     bool SrcIsKill = MI->getOperand(1).isKill();
3861
3862     if (SrcReg != ARM::SP) {
3863       // Copy the source to SP from virtual register.
3864       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(SrcReg);
3865       unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
3866         ? ARM::tMOVtgpr2gpr : ARM::tMOVgpr2gpr;
3867       BuildMI(BB, dl, TII->get(CopyOpc), ARM::SP)
3868         .addReg(SrcReg, getKillRegState(SrcIsKill));
3869     }
3870
3871     unsigned OpOpc = 0;
3872     bool NeedPred = false, NeedCC = false, NeedOp3 = false;
3873     switch (MI->getOpcode()) {
3874     default:
3875       llvm_unreachable("Unexpected pseudo instruction!");
3876     case ARM::tANDsp:
3877       OpOpc = ARM::tAND;
3878       NeedPred = true;
3879       break;
3880     case ARM::tADDspr_:
3881       OpOpc = ARM::tADDspr;
3882       break;
3883     case ARM::tSUBspi_:
3884       OpOpc = ARM::tSUBspi;
3885       break;
3886     case ARM::t2SUBrSPi_:
3887       OpOpc = ARM::t2SUBrSPi;
3888       NeedPred = true; NeedCC = true;
3889       break;
3890     case ARM::t2SUBrSPi12_:
3891       OpOpc = ARM::t2SUBrSPi12;
3892       NeedPred = true;
3893       break;
3894     case ARM::t2SUBrSPs_:
3895       OpOpc = ARM::t2SUBrSPs;
3896       NeedPred = true; NeedCC = true; NeedOp3 = true;
3897       break;
3898     }
3899     MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(OpOpc), ARM::SP);
3900     if (OpOpc == ARM::tAND)
3901       AddDefaultT1CC(MIB);
3902     MIB.addReg(ARM::SP);
3903     MIB.addOperand(MI->getOperand(2));
3904     if (NeedOp3)
3905       MIB.addOperand(MI->getOperand(3));
3906     if (NeedPred)
3907       AddDefaultPred(MIB);
3908     if (NeedCC)
3909       AddDefaultCC(MIB);
3910
3911     // Copy the result from SP to virtual register.
3912     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(DstReg);
3913     unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
3914       ? ARM::tMOVgpr2tgpr : ARM::tMOVgpr2gpr;
3915     BuildMI(BB, dl, TII->get(CopyOpc))
3916       .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstIsDead))
3917       .addReg(ARM::SP);
3918     MF->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
3919     return BB;
3920   }
3921   }
3922 }
3923
3924 //===----------------------------------------------------------------------===//
3925 //                           ARM Optimization Hooks
3926 //===----------------------------------------------------------------------===//
3927
3928 static
3929 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
3930                             TargetLowering::DAGCombinerInfo &DCI) {
3931   SelectionDAG &DAG = DCI.DAG;
3932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3933   EVT VT = N->getValueType(0);
3934   unsigned Opc = N->getOpcode();
3935   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
3936   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
3937   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
3938   ISD::CondCode CC = ISD::SETCC_INVALID;
3939
3940   if (isSlctCC) {
3941     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
3942   } else {
3943     SDValue CCOp = Slct.getOperand(0);
3944     if (CCOp.getOpcode() == ISD::SETCC)
3945       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
3946   }
3947
3948   bool DoXform = false;
3949   bool InvCC = false;
3950   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
3951           "Bad input!");
3952
3953   if (LHS.getOpcode() == ISD::Constant &&
3954       cast<ConstantSDNode>(LHS)->isNullValue()) {
3955     DoXform = true;
3956   } else if (CC != ISD::SETCC_INVALID &&
3957              RHS.getOpcode() == ISD::Constant &&
3958              cast<ConstantSDNode>(RHS)->isNullValue()) {
3959     std::swap(LHS, RHS);
3960     SDValue Op0 = Slct.getOperand(0);
3961     EVT OpVT = isSlctCC ? Op0.getValueType() :
3962                           Op0.getOperand(0).getValueType();
3963     bool isInt = OpVT.isInteger();
3964     CC = ISD::getSetCCInverse(CC, isInt);
3965
3966     if (!TLI.isCondCodeLegal(CC, OpVT))
3967       return SDValue();         // Inverse operator isn't legal.
3968
3969     DoXform = true;
3970     InvCC = true;
3971   }
3972
3973   if (DoXform) {
3974     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
3975     if (isSlctCC)
3976       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
3977                              Slct.getOperand(0), Slct.getOperand(1), CC);
3978     SDValue CCOp = Slct.getOperand(0);
3979     if (InvCC)
3980       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
3981                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
3982     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3983                        CCOp, OtherOp, Result);
3984   }
3985   return SDValue();
3986 }
3987
3988 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
3989 static SDValue PerformADDCombine(SDNode *N,
3990                                  TargetLowering::DAGCombinerInfo &DCI) {
3991   // added by evan in r37685 with no testcase.
3992   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3993
3994   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
3995   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
3996     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
3997     if (Result.getNode()) return Result;
3998   }
3999   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
4000     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
4001     if (Result.getNode()) return Result;
4002   }
4003
4004   return SDValue();
4005 }
4006
4007 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
4008 static SDValue PerformSUBCombine(SDNode *N,
4009                                  TargetLowering::DAGCombinerInfo &DCI) {
4010   // added by evan in r37685 with no testcase.
4011   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
4012
4013   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
4014   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
4015     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
4016     if (Result.getNode()) return Result;
4017   }
4018
4019   return SDValue();
4020 }
4021
4022 static SDValue PerformMULCombine(SDNode *N,
4023                                  TargetLowering::DAGCombinerInfo &DCI,
4024                                  const ARMSubtarget *Subtarget) {
4025   SelectionDAG &DAG = DCI.DAG;
4026
4027   if (Subtarget->isThumb1Only())
4028     return SDValue();
4029
4030   if (DAG.getMachineFunction().
4031       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
4032     return SDValue();
4033
4034   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
4035     return SDValue();
4036
4037   EVT VT = N->getValueType(0);
4038   if (VT != MVT::i32)
4039     return SDValue();
4040
4041   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
4042   if (!C)
4043     return SDValue();
4044
4045   uint64_t MulAmt = C->getZExtValue();
4046   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
4047   ShiftAmt = ShiftAmt & (32 - 1);
4048   SDValue V = N->getOperand(0);
4049   DebugLoc DL = N->getDebugLoc();
4050
4051   SDValue Res;
4052   MulAmt >>= ShiftAmt;
4053   if (isPowerOf2_32(MulAmt - 1)) {
4054     // (mul x, 2^N + 1) => (add (shl x, N), x)
4055     Res = DAG.getNode(ISD::ADD, DL, VT,
4056                       V, DAG.getNode(ISD::SHL, DL, VT,
4057                                      V, DAG.getConstant(Log2_32(MulAmt-1),
4058                                                         MVT::i32)));
4059   } else if (isPowerOf2_32(MulAmt + 1)) {
4060     // (mul x, 2^N - 1) => (sub (shl x, N), x)
4061     Res = DAG.getNode(ISD::SUB, DL, VT,
4062                       DAG.getNode(ISD::SHL, DL, VT,
4063                                   V, DAG.getConstant(Log2_32(MulAmt+1),
4064                                                      MVT::i32)),
4065                                                      V);
4066   } else
4067     return SDValue();
4068
4069   if (ShiftAmt != 0)
4070     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
4071                       DAG.getConstant(ShiftAmt, MVT::i32));
4072
4073   // Do not add new nodes to DAG combiner worklist.
4074   DCI.CombineTo(N, Res, false);
4075   return SDValue();
4076 }
4077
4078 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
4079 /// ARMISD::VMOVRRD.
4080 static SDValue PerformVMOVRRDCombine(SDNode *N,
4081                                    TargetLowering::DAGCombinerInfo &DCI) {
4082   // fmrrd(fmdrr x, y) -> x,y
4083   SDValue InDouble = N->getOperand(0);
4084   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
4085     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
4086   return SDValue();
4087 }
4088
4089 /// getVShiftImm - Check if this is a valid build_vector for the immediate
4090 /// operand of a vector shift operation, where all the elements of the
4091 /// build_vector must have the same constant integer value.
4092 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
4093   // Ignore bit_converts.
4094   while (Op.getOpcode() == ISD::BIT_CONVERT)
4095     Op = Op.getOperand(0);
4096   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
4097   APInt SplatBits, SplatUndef;
4098   unsigned SplatBitSize;
4099   bool HasAnyUndefs;
4100   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
4101                                       HasAnyUndefs, ElementBits) ||
4102       SplatBitSize > ElementBits)
4103     return false;
4104   Cnt = SplatBits.getSExtValue();
4105   return true;
4106 }
4107
4108 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
4109 /// operand of a vector shift left operation.  That value must be in the range:
4110 ///   0 <= Value < ElementBits for a left shift; or
4111 ///   0 <= Value <= ElementBits for a long left shift.
4112 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
4113   assert(VT.isVector() && "vector shift count is not a vector type");
4114   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
4115   if (! getVShiftImm(Op, ElementBits, Cnt))
4116     return false;
4117   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
4118 }
4119
4120 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
4121 /// operand of a vector shift right operation.  For a shift opcode, the value
4122 /// is positive, but for an intrinsic the value count must be negative. The
4123 /// absolute value must be in the range:
4124 ///   1 <= |Value| <= ElementBits for a right shift; or
4125 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
4126 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
4127                          int64_t &Cnt) {
4128   assert(VT.isVector() && "vector shift count is not a vector type");
4129   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
4130   if (! getVShiftImm(Op, ElementBits, Cnt))
4131     return false;
4132   if (isIntrinsic)
4133     Cnt = -Cnt;
4134   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
4135 }
4136
4137 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
4138 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
4139   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4140   switch (IntNo) {
4141   default:
4142     // Don't do anything for most intrinsics.
4143     break;
4144
4145   // Vector shifts: check for immediate versions and lower them.
4146   // Note: This is done during DAG combining instead of DAG legalizing because
4147   // the build_vectors for 64-bit vector element shift counts are generally
4148   // not legal, and it is hard to see their values after they get legalized to
4149   // loads from a constant pool.
4150   case Intrinsic::arm_neon_vshifts:
4151   case Intrinsic::arm_neon_vshiftu:
4152   case Intrinsic::arm_neon_vshiftls:
4153   case Intrinsic::arm_neon_vshiftlu:
4154   case Intrinsic::arm_neon_vshiftn:
4155   case Intrinsic::arm_neon_vrshifts:
4156   case Intrinsic::arm_neon_vrshiftu:
4157   case Intrinsic::arm_neon_vrshiftn:
4158   case Intrinsic::arm_neon_vqshifts:
4159   case Intrinsic::arm_neon_vqshiftu:
4160   case Intrinsic::arm_neon_vqshiftsu:
4161   case Intrinsic::arm_neon_vqshiftns:
4162   case Intrinsic::arm_neon_vqshiftnu:
4163   case Intrinsic::arm_neon_vqshiftnsu:
4164   case Intrinsic::arm_neon_vqrshiftns:
4165   case Intrinsic::arm_neon_vqrshiftnu:
4166   case Intrinsic::arm_neon_vqrshiftnsu: {
4167     EVT VT = N->getOperand(1).getValueType();
4168     int64_t Cnt;
4169     unsigned VShiftOpc = 0;
4170
4171     switch (IntNo) {
4172     case Intrinsic::arm_neon_vshifts:
4173     case Intrinsic::arm_neon_vshiftu:
4174       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
4175         VShiftOpc = ARMISD::VSHL;
4176         break;
4177       }
4178       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
4179         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
4180                      ARMISD::VSHRs : ARMISD::VSHRu);
4181         break;
4182       }
4183       return SDValue();
4184
4185     case Intrinsic::arm_neon_vshiftls:
4186     case Intrinsic::arm_neon_vshiftlu:
4187       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
4188         break;
4189       llvm_unreachable("invalid shift count for vshll intrinsic");
4190
4191     case Intrinsic::arm_neon_vrshifts:
4192     case Intrinsic::arm_neon_vrshiftu:
4193       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
4194         break;
4195       return SDValue();
4196
4197     case Intrinsic::arm_neon_vqshifts:
4198     case Intrinsic::arm_neon_vqshiftu:
4199       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
4200         break;
4201       return SDValue();
4202
4203     case Intrinsic::arm_neon_vqshiftsu:
4204       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
4205         break;
4206       llvm_unreachable("invalid shift count for vqshlu intrinsic");
4207
4208     case Intrinsic::arm_neon_vshiftn:
4209     case Intrinsic::arm_neon_vrshiftn:
4210     case Intrinsic::arm_neon_vqshiftns:
4211     case Intrinsic::arm_neon_vqshiftnu:
4212     case Intrinsic::arm_neon_vqshiftnsu:
4213     case Intrinsic::arm_neon_vqrshiftns:
4214     case Intrinsic::arm_neon_vqrshiftnu:
4215     case Intrinsic::arm_neon_vqrshiftnsu:
4216       // Narrowing shifts require an immediate right shift.
4217       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
4218         break;
4219       llvm_unreachable("invalid shift count for narrowing vector shift "
4220                        "intrinsic");
4221
4222     default:
4223       llvm_unreachable("unhandled vector shift");
4224     }
4225
4226     switch (IntNo) {
4227     case Intrinsic::arm_neon_vshifts:
4228     case Intrinsic::arm_neon_vshiftu:
4229       // Opcode already set above.
4230       break;
4231     case Intrinsic::arm_neon_vshiftls:
4232     case Intrinsic::arm_neon_vshiftlu:
4233       if (Cnt == VT.getVectorElementType().getSizeInBits())
4234         VShiftOpc = ARMISD::VSHLLi;
4235       else
4236         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
4237                      ARMISD::VSHLLs : ARMISD::VSHLLu);
4238       break;
4239     case Intrinsic::arm_neon_vshiftn:
4240       VShiftOpc = ARMISD::VSHRN; break;
4241     case Intrinsic::arm_neon_vrshifts:
4242       VShiftOpc = ARMISD::VRSHRs; break;
4243     case Intrinsic::arm_neon_vrshiftu:
4244       VShiftOpc = ARMISD::VRSHRu; break;
4245     case Intrinsic::arm_neon_vrshiftn:
4246       VShiftOpc = ARMISD::VRSHRN; break;
4247     case Intrinsic::arm_neon_vqshifts:
4248       VShiftOpc = ARMISD::VQSHLs; break;
4249     case Intrinsic::arm_neon_vqshiftu:
4250       VShiftOpc = ARMISD::VQSHLu; break;
4251     case Intrinsic::arm_neon_vqshiftsu:
4252       VShiftOpc = ARMISD::VQSHLsu; break;
4253     case Intrinsic::arm_neon_vqshiftns:
4254       VShiftOpc = ARMISD::VQSHRNs; break;
4255     case Intrinsic::arm_neon_vqshiftnu:
4256       VShiftOpc = ARMISD::VQSHRNu; break;
4257     case Intrinsic::arm_neon_vqshiftnsu:
4258       VShiftOpc = ARMISD::VQSHRNsu; break;
4259     case Intrinsic::arm_neon_vqrshiftns:
4260       VShiftOpc = ARMISD::VQRSHRNs; break;
4261     case Intrinsic::arm_neon_vqrshiftnu:
4262       VShiftOpc = ARMISD::VQRSHRNu; break;
4263     case Intrinsic::arm_neon_vqrshiftnsu:
4264       VShiftOpc = ARMISD::VQRSHRNsu; break;
4265     }
4266
4267     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
4268                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
4269   }
4270
4271   case Intrinsic::arm_neon_vshiftins: {
4272     EVT VT = N->getOperand(1).getValueType();
4273     int64_t Cnt;
4274     unsigned VShiftOpc = 0;
4275
4276     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
4277       VShiftOpc = ARMISD::VSLI;
4278     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
4279       VShiftOpc = ARMISD::VSRI;
4280     else {
4281       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
4282     }
4283
4284     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
4285                        N->getOperand(1), N->getOperand(2),
4286                        DAG.getConstant(Cnt, MVT::i32));
4287   }
4288
4289   case Intrinsic::arm_neon_vqrshifts:
4290   case Intrinsic::arm_neon_vqrshiftu:
4291     // No immediate versions of these to check for.
4292     break;
4293   }
4294
4295   return SDValue();
4296 }
4297
4298 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
4299 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
4300 /// combining instead of DAG legalizing because the build_vectors for 64-bit
4301 /// vector element shift counts are generally not legal, and it is hard to see
4302 /// their values after they get legalized to loads from a constant pool.
4303 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
4304                                    const ARMSubtarget *ST) {
4305   EVT VT = N->getValueType(0);
4306
4307   // Nothing to be done for scalar shifts.
4308   if (! VT.isVector())
4309     return SDValue();
4310
4311   assert(ST->hasNEON() && "unexpected vector shift");
4312   int64_t Cnt;
4313
4314   switch (N->getOpcode()) {
4315   default: llvm_unreachable("unexpected shift opcode");
4316
4317   case ISD::SHL:
4318     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
4319       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
4320                          DAG.getConstant(Cnt, MVT::i32));
4321     break;
4322
4323   case ISD::SRA:
4324   case ISD::SRL:
4325     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
4326       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
4327                             ARMISD::VSHRs : ARMISD::VSHRu);
4328       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
4329                          DAG.getConstant(Cnt, MVT::i32));
4330     }
4331   }
4332   return SDValue();
4333 }
4334
4335 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
4336 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
4337 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
4338                                     const ARMSubtarget *ST) {
4339   SDValue N0 = N->getOperand(0);
4340
4341   // Check for sign- and zero-extensions of vector extract operations of 8-
4342   // and 16-bit vector elements.  NEON supports these directly.  They are
4343   // handled during DAG combining because type legalization will promote them
4344   // to 32-bit types and it is messy to recognize the operations after that.
4345   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4346     SDValue Vec = N0.getOperand(0);
4347     SDValue Lane = N0.getOperand(1);
4348     EVT VT = N->getValueType(0);
4349     EVT EltVT = N0.getValueType();
4350     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4351
4352     if (VT == MVT::i32 &&
4353         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
4354         TLI.isTypeLegal(Vec.getValueType())) {
4355
4356       unsigned Opc = 0;
4357       switch (N->getOpcode()) {
4358       default: llvm_unreachable("unexpected opcode");
4359       case ISD::SIGN_EXTEND:
4360         Opc = ARMISD::VGETLANEs;
4361         break;
4362       case ISD::ZERO_EXTEND:
4363       case ISD::ANY_EXTEND:
4364         Opc = ARMISD::VGETLANEu;
4365         break;
4366       }
4367       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
4368     }
4369   }
4370
4371   return SDValue();
4372 }
4373
4374 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
4375 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
4376 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
4377                                        const ARMSubtarget *ST) {
4378   // If the target supports NEON, try to use vmax/vmin instructions for f32
4379   // selects like "x < y ? x : y".  Unless the FiniteOnlyFPMath option is set,
4380   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
4381   // a NaN; only do the transformation when it matches that behavior.
4382
4383   // For now only do this when using NEON for FP operations; if using VFP, it
4384   // is not obvious that the benefit outweighs the cost of switching to the
4385   // NEON pipeline.
4386   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
4387       N->getValueType(0) != MVT::f32)
4388     return SDValue();
4389
4390   SDValue CondLHS = N->getOperand(0);
4391   SDValue CondRHS = N->getOperand(1);
4392   SDValue LHS = N->getOperand(2);
4393   SDValue RHS = N->getOperand(3);
4394   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
4395
4396   unsigned Opcode = 0;
4397   bool IsReversed;
4398   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
4399     IsReversed = false; // x CC y ? x : y
4400   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
4401     IsReversed = true ; // x CC y ? y : x
4402   } else {
4403     return SDValue();
4404   }
4405
4406   bool IsUnordered;
4407   switch (CC) {
4408   default: break;
4409   case ISD::SETOLT:
4410   case ISD::SETOLE:
4411   case ISD::SETLT:
4412   case ISD::SETLE:
4413   case ISD::SETULT:
4414   case ISD::SETULE:
4415     // If LHS is NaN, an ordered comparison will be false and the result will
4416     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
4417     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
4418     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
4419     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
4420       break;
4421     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
4422     // will return -0, so vmin can only be used for unsafe math or if one of
4423     // the operands is known to be nonzero.
4424     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
4425         !UnsafeFPMath &&
4426         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
4427       break;
4428     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
4429     break;
4430
4431   case ISD::SETOGT:
4432   case ISD::SETOGE:
4433   case ISD::SETGT:
4434   case ISD::SETGE:
4435   case ISD::SETUGT:
4436   case ISD::SETUGE:
4437     // If LHS is NaN, an ordered comparison will be false and the result will
4438     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
4439     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
4440     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
4441     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
4442       break;
4443     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
4444     // will return +0, so vmax can only be used for unsafe math or if one of
4445     // the operands is known to be nonzero.
4446     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
4447         !UnsafeFPMath &&
4448         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
4449       break;
4450     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
4451     break;
4452   }
4453
4454   if (!Opcode)
4455     return SDValue();
4456   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
4457 }
4458
4459 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
4460                                              DAGCombinerInfo &DCI) const {
4461   switch (N->getOpcode()) {
4462   default: break;
4463   case ISD::ADD:        return PerformADDCombine(N, DCI);
4464   case ISD::SUB:        return PerformSUBCombine(N, DCI);
4465   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
4466   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
4467   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
4468   case ISD::SHL:
4469   case ISD::SRA:
4470   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
4471   case ISD::SIGN_EXTEND:
4472   case ISD::ZERO_EXTEND:
4473   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
4474   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
4475   }
4476   return SDValue();
4477 }
4478
4479 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
4480   if (!Subtarget->hasV6Ops())
4481     // Pre-v6 does not support unaligned mem access.
4482     return false;
4483   else {
4484     // v6+ may or may not support unaligned mem access depending on the system
4485     // configuration.
4486     // FIXME: This is pretty conservative. Should we provide cmdline option to
4487     // control the behaviour?
4488     if (!Subtarget->isTargetDarwin())
4489       return false;
4490   }
4491
4492   switch (VT.getSimpleVT().SimpleTy) {
4493   default:
4494     return false;
4495   case MVT::i8:
4496   case MVT::i16:
4497   case MVT::i32:
4498     return true;
4499   // FIXME: VLD1 etc with standard alignment is legal.
4500   }
4501 }
4502
4503 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
4504   if (V < 0)
4505     return false;
4506
4507   unsigned Scale = 1;
4508   switch (VT.getSimpleVT().SimpleTy) {
4509   default: return false;
4510   case MVT::i1:
4511   case MVT::i8:
4512     // Scale == 1;
4513     break;
4514   case MVT::i16:
4515     // Scale == 2;
4516     Scale = 2;
4517     break;
4518   case MVT::i32:
4519     // Scale == 4;
4520     Scale = 4;
4521     break;
4522   }
4523
4524   if ((V & (Scale - 1)) != 0)
4525     return false;
4526   V /= Scale;
4527   return V == (V & ((1LL << 5) - 1));
4528 }
4529
4530 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
4531                                       const ARMSubtarget *Subtarget) {
4532   bool isNeg = false;
4533   if (V < 0) {
4534     isNeg = true;
4535     V = - V;
4536   }
4537
4538   switch (VT.getSimpleVT().SimpleTy) {
4539   default: return false;
4540   case MVT::i1:
4541   case MVT::i8:
4542   case MVT::i16:
4543   case MVT::i32:
4544     // + imm12 or - imm8
4545     if (isNeg)
4546       return V == (V & ((1LL << 8) - 1));
4547     return V == (V & ((1LL << 12) - 1));
4548   case MVT::f32:
4549   case MVT::f64:
4550     // Same as ARM mode. FIXME: NEON?
4551     if (!Subtarget->hasVFP2())
4552       return false;
4553     if ((V & 3) != 0)
4554       return false;
4555     V >>= 2;
4556     return V == (V & ((1LL << 8) - 1));
4557   }
4558 }
4559
4560 /// isLegalAddressImmediate - Return true if the integer value can be used
4561 /// as the offset of the target addressing mode for load / store of the
4562 /// given type.
4563 static bool isLegalAddressImmediate(int64_t V, EVT VT,
4564                                     const ARMSubtarget *Subtarget) {
4565   if (V == 0)
4566     return true;
4567
4568   if (!VT.isSimple())
4569     return false;
4570
4571   if (Subtarget->isThumb1Only())
4572     return isLegalT1AddressImmediate(V, VT);
4573   else if (Subtarget->isThumb2())
4574     return isLegalT2AddressImmediate(V, VT, Subtarget);
4575
4576   // ARM mode.
4577   if (V < 0)
4578     V = - V;
4579   switch (VT.getSimpleVT().SimpleTy) {
4580   default: return false;
4581   case MVT::i1:
4582   case MVT::i8:
4583   case MVT::i32:
4584     // +- imm12
4585     return V == (V & ((1LL << 12) - 1));
4586   case MVT::i16:
4587     // +- imm8
4588     return V == (V & ((1LL << 8) - 1));
4589   case MVT::f32:
4590   case MVT::f64:
4591     if (!Subtarget->hasVFP2()) // FIXME: NEON?
4592       return false;
4593     if ((V & 3) != 0)
4594       return false;
4595     V >>= 2;
4596     return V == (V & ((1LL << 8) - 1));
4597   }
4598 }
4599
4600 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
4601                                                       EVT VT) const {
4602   int Scale = AM.Scale;
4603   if (Scale < 0)
4604     return false;
4605
4606   switch (VT.getSimpleVT().SimpleTy) {
4607   default: return false;
4608   case MVT::i1:
4609   case MVT::i8:
4610   case MVT::i16:
4611   case MVT::i32:
4612     if (Scale == 1)
4613       return true;
4614     // r + r << imm
4615     Scale = Scale & ~1;
4616     return Scale == 2 || Scale == 4 || Scale == 8;
4617   case MVT::i64:
4618     // r + r
4619     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
4620       return true;
4621     return false;
4622   case MVT::isVoid:
4623     // Note, we allow "void" uses (basically, uses that aren't loads or
4624     // stores), because arm allows folding a scale into many arithmetic
4625     // operations.  This should be made more precise and revisited later.
4626
4627     // Allow r << imm, but the imm has to be a multiple of two.
4628     if (Scale & 1) return false;
4629     return isPowerOf2_32(Scale);
4630   }
4631 }
4632
4633 /// isLegalAddressingMode - Return true if the addressing mode represented
4634 /// by AM is legal for this target, for a load/store of the specified type.
4635 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
4636                                               const Type *Ty) const {
4637   EVT VT = getValueType(Ty, true);
4638   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
4639     return false;
4640
4641   // Can never fold addr of global into load/store.
4642   if (AM.BaseGV)
4643     return false;
4644
4645   switch (AM.Scale) {
4646   case 0:  // no scale reg, must be "r+i" or "r", or "i".
4647     break;
4648   case 1:
4649     if (Subtarget->isThumb1Only())
4650       return false;
4651     // FALL THROUGH.
4652   default:
4653     // ARM doesn't support any R+R*scale+imm addr modes.
4654     if (AM.BaseOffs)
4655       return false;
4656
4657     if (!VT.isSimple())
4658       return false;
4659
4660     if (Subtarget->isThumb2())
4661       return isLegalT2ScaledAddressingMode(AM, VT);
4662
4663     int Scale = AM.Scale;
4664     switch (VT.getSimpleVT().SimpleTy) {
4665     default: return false;
4666     case MVT::i1:
4667     case MVT::i8:
4668     case MVT::i32:
4669       if (Scale < 0) Scale = -Scale;
4670       if (Scale == 1)
4671         return true;
4672       // r + r << imm
4673       return isPowerOf2_32(Scale & ~1);
4674     case MVT::i16:
4675     case MVT::i64:
4676       // r + r
4677       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
4678         return true;
4679       return false;
4680
4681     case MVT::isVoid:
4682       // Note, we allow "void" uses (basically, uses that aren't loads or
4683       // stores), because arm allows folding a scale into many arithmetic
4684       // operations.  This should be made more precise and revisited later.
4685
4686       // Allow r << imm, but the imm has to be a multiple of two.
4687       if (Scale & 1) return false;
4688       return isPowerOf2_32(Scale);
4689     }
4690     break;
4691   }
4692   return true;
4693 }
4694
4695 /// isLegalICmpImmediate - Return true if the specified immediate is legal
4696 /// icmp immediate, that is the target has icmp instructions which can compare
4697 /// a register against the immediate without having to materialize the
4698 /// immediate into a register.
4699 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
4700   if (!Subtarget->isThumb())
4701     return ARM_AM::getSOImmVal(Imm) != -1;
4702   if (Subtarget->isThumb2())
4703     return ARM_AM::getT2SOImmVal(Imm) != -1; 
4704   return Imm >= 0 && Imm <= 255;
4705 }
4706
4707 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
4708                                       bool isSEXTLoad, SDValue &Base,
4709                                       SDValue &Offset, bool &isInc,
4710                                       SelectionDAG &DAG) {
4711   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
4712     return false;
4713
4714   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
4715     // AddressingMode 3
4716     Base = Ptr->getOperand(0);
4717     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
4718       int RHSC = (int)RHS->getZExtValue();
4719       if (RHSC < 0 && RHSC > -256) {
4720         assert(Ptr->getOpcode() == ISD::ADD);
4721         isInc = false;
4722         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
4723         return true;
4724       }
4725     }
4726     isInc = (Ptr->getOpcode() == ISD::ADD);
4727     Offset = Ptr->getOperand(1);
4728     return true;
4729   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
4730     // AddressingMode 2
4731     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
4732       int RHSC = (int)RHS->getZExtValue();
4733       if (RHSC < 0 && RHSC > -0x1000) {
4734         assert(Ptr->getOpcode() == ISD::ADD);
4735         isInc = false;
4736         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
4737         Base = Ptr->getOperand(0);
4738         return true;
4739       }
4740     }
4741
4742     if (Ptr->getOpcode() == ISD::ADD) {
4743       isInc = true;
4744       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
4745       if (ShOpcVal != ARM_AM::no_shift) {
4746         Base = Ptr->getOperand(1);
4747         Offset = Ptr->getOperand(0);
4748       } else {
4749         Base = Ptr->getOperand(0);
4750         Offset = Ptr->getOperand(1);
4751       }
4752       return true;
4753     }
4754
4755     isInc = (Ptr->getOpcode() == ISD::ADD);
4756     Base = Ptr->getOperand(0);
4757     Offset = Ptr->getOperand(1);
4758     return true;
4759   }
4760
4761   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
4762   return false;
4763 }
4764
4765 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
4766                                      bool isSEXTLoad, SDValue &Base,
4767                                      SDValue &Offset, bool &isInc,
4768                                      SelectionDAG &DAG) {
4769   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
4770     return false;
4771
4772   Base = Ptr->getOperand(0);
4773   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
4774     int RHSC = (int)RHS->getZExtValue();
4775     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
4776       assert(Ptr->getOpcode() == ISD::ADD);
4777       isInc = false;
4778       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
4779       return true;
4780     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
4781       isInc = Ptr->getOpcode() == ISD::ADD;
4782       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
4783       return true;
4784     }
4785   }
4786
4787   return false;
4788 }
4789
4790 /// getPreIndexedAddressParts - returns true by value, base pointer and
4791 /// offset pointer and addressing mode by reference if the node's address
4792 /// can be legally represented as pre-indexed load / store address.
4793 bool
4794 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
4795                                              SDValue &Offset,
4796                                              ISD::MemIndexedMode &AM,
4797                                              SelectionDAG &DAG) const {
4798   if (Subtarget->isThumb1Only())
4799     return false;
4800
4801   EVT VT;
4802   SDValue Ptr;
4803   bool isSEXTLoad = false;
4804   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4805     Ptr = LD->getBasePtr();
4806     VT  = LD->getMemoryVT();
4807     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
4808   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4809     Ptr = ST->getBasePtr();
4810     VT  = ST->getMemoryVT();
4811   } else
4812     return false;
4813
4814   bool isInc;
4815   bool isLegal = false;
4816   if (Subtarget->isThumb2())
4817     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
4818                                        Offset, isInc, DAG);
4819   else
4820     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
4821                                         Offset, isInc, DAG);
4822   if (!isLegal)
4823     return false;
4824
4825   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
4826   return true;
4827 }
4828
4829 /// getPostIndexedAddressParts - returns true by value, base pointer and
4830 /// offset pointer and addressing mode by reference if this node can be
4831 /// combined with a load / store to form a post-indexed load / store.
4832 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
4833                                                    SDValue &Base,
4834                                                    SDValue &Offset,
4835                                                    ISD::MemIndexedMode &AM,
4836                                                    SelectionDAG &DAG) const {
4837   if (Subtarget->isThumb1Only())
4838     return false;
4839
4840   EVT VT;
4841   SDValue Ptr;
4842   bool isSEXTLoad = false;
4843   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4844     VT  = LD->getMemoryVT();
4845     Ptr = LD->getBasePtr();
4846     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
4847   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4848     VT  = ST->getMemoryVT();
4849     Ptr = ST->getBasePtr();
4850   } else
4851     return false;
4852
4853   bool isInc;
4854   bool isLegal = false;
4855   if (Subtarget->isThumb2())
4856     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
4857                                        isInc, DAG);
4858   else
4859     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
4860                                         isInc, DAG);
4861   if (!isLegal)
4862     return false;
4863
4864   if (Ptr != Base) {
4865     // Swap base ptr and offset to catch more post-index load / store when
4866     // it's legal. In Thumb2 mode, offset must be an immediate.
4867     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
4868         !Subtarget->isThumb2())
4869       std::swap(Base, Offset);
4870
4871     // Post-indexed load / store update the base pointer.
4872     if (Ptr != Base)
4873       return false;
4874   }
4875
4876   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
4877   return true;
4878 }
4879
4880 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
4881                                                        const APInt &Mask,
4882                                                        APInt &KnownZero,
4883                                                        APInt &KnownOne,
4884                                                        const SelectionDAG &DAG,
4885                                                        unsigned Depth) const {
4886   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
4887   switch (Op.getOpcode()) {
4888   default: break;
4889   case ARMISD::CMOV: {
4890     // Bits are known zero/one if known on the LHS and RHS.
4891     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
4892     if (KnownZero == 0 && KnownOne == 0) return;
4893
4894     APInt KnownZeroRHS, KnownOneRHS;
4895     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
4896                           KnownZeroRHS, KnownOneRHS, Depth+1);
4897     KnownZero &= KnownZeroRHS;
4898     KnownOne  &= KnownOneRHS;
4899     return;
4900   }
4901   }
4902 }
4903
4904 //===----------------------------------------------------------------------===//
4905 //                           ARM Inline Assembly Support
4906 //===----------------------------------------------------------------------===//
4907
4908 /// getConstraintType - Given a constraint letter, return the type of
4909 /// constraint it is for this target.
4910 ARMTargetLowering::ConstraintType
4911 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
4912   if (Constraint.size() == 1) {
4913     switch (Constraint[0]) {
4914     default:  break;
4915     case 'l': return C_RegisterClass;
4916     case 'w': return C_RegisterClass;
4917     }
4918   }
4919   return TargetLowering::getConstraintType(Constraint);
4920 }
4921
4922 std::pair<unsigned, const TargetRegisterClass*>
4923 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4924                                                 EVT VT) const {
4925   if (Constraint.size() == 1) {
4926     // GCC ARM Constraint Letters
4927     switch (Constraint[0]) {
4928     case 'l':
4929       if (Subtarget->isThumb())
4930         return std::make_pair(0U, ARM::tGPRRegisterClass);
4931       else
4932         return std::make_pair(0U, ARM::GPRRegisterClass);
4933     case 'r':
4934       return std::make_pair(0U, ARM::GPRRegisterClass);
4935     case 'w':
4936       if (VT == MVT::f32)
4937         return std::make_pair(0U, ARM::SPRRegisterClass);
4938       if (VT.getSizeInBits() == 64)
4939         return std::make_pair(0U, ARM::DPRRegisterClass);
4940       if (VT.getSizeInBits() == 128)
4941         return std::make_pair(0U, ARM::QPRRegisterClass);
4942       break;
4943     }
4944   }
4945   if (StringRef("{cc}").equals_lower(Constraint))
4946     return std::make_pair(0U, ARM::CCRRegisterClass);
4947
4948   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4949 }
4950
4951 std::vector<unsigned> ARMTargetLowering::
4952 getRegClassForInlineAsmConstraint(const std::string &Constraint,
4953                                   EVT VT) const {
4954   if (Constraint.size() != 1)
4955     return std::vector<unsigned>();
4956
4957   switch (Constraint[0]) {      // GCC ARM Constraint Letters
4958   default: break;
4959   case 'l':
4960     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
4961                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
4962                                  0);
4963   case 'r':
4964     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
4965                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
4966                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
4967                                  ARM::R12, ARM::LR, 0);
4968   case 'w':
4969     if (VT == MVT::f32)
4970       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
4971                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
4972                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
4973                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
4974                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
4975                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
4976                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
4977                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
4978     if (VT.getSizeInBits() == 64)
4979       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
4980                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
4981                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
4982                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
4983     if (VT.getSizeInBits() == 128)
4984       return make_vector<unsigned>(ARM::Q0, ARM::Q1, ARM::Q2, ARM::Q3,
4985                                    ARM::Q4, ARM::Q5, ARM::Q6, ARM::Q7, 0);
4986       break;
4987   }
4988
4989   return std::vector<unsigned>();
4990 }
4991
4992 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4993 /// vector.  If it is invalid, don't add anything to Ops.
4994 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4995                                                      char Constraint,
4996                                                      bool hasMemory,
4997                                                      std::vector<SDValue>&Ops,
4998                                                      SelectionDAG &DAG) const {
4999   SDValue Result(0, 0);
5000
5001   switch (Constraint) {
5002   default: break;
5003   case 'I': case 'J': case 'K': case 'L':
5004   case 'M': case 'N': case 'O':
5005     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5006     if (!C)
5007       return;
5008
5009     int64_t CVal64 = C->getSExtValue();
5010     int CVal = (int) CVal64;
5011     // None of these constraints allow values larger than 32 bits.  Check
5012     // that the value fits in an int.
5013     if (CVal != CVal64)
5014       return;
5015
5016     switch (Constraint) {
5017       case 'I':
5018         if (Subtarget->isThumb1Only()) {
5019           // This must be a constant between 0 and 255, for ADD
5020           // immediates.
5021           if (CVal >= 0 && CVal <= 255)
5022             break;
5023         } else if (Subtarget->isThumb2()) {
5024           // A constant that can be used as an immediate value in a
5025           // data-processing instruction.
5026           if (ARM_AM::getT2SOImmVal(CVal) != -1)
5027             break;
5028         } else {
5029           // A constant that can be used as an immediate value in a
5030           // data-processing instruction.
5031           if (ARM_AM::getSOImmVal(CVal) != -1)
5032             break;
5033         }
5034         return;
5035
5036       case 'J':
5037         if (Subtarget->isThumb()) {  // FIXME thumb2
5038           // This must be a constant between -255 and -1, for negated ADD
5039           // immediates. This can be used in GCC with an "n" modifier that
5040           // prints the negated value, for use with SUB instructions. It is
5041           // not useful otherwise but is implemented for compatibility.
5042           if (CVal >= -255 && CVal <= -1)
5043             break;
5044         } else {
5045           // This must be a constant between -4095 and 4095. It is not clear
5046           // what this constraint is intended for. Implemented for
5047           // compatibility with GCC.
5048           if (CVal >= -4095 && CVal <= 4095)
5049             break;
5050         }
5051         return;
5052
5053       case 'K':
5054         if (Subtarget->isThumb1Only()) {
5055           // A 32-bit value where only one byte has a nonzero value. Exclude
5056           // zero to match GCC. This constraint is used by GCC internally for
5057           // constants that can be loaded with a move/shift combination.
5058           // It is not useful otherwise but is implemented for compatibility.
5059           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
5060             break;
5061         } else if (Subtarget->isThumb2()) {
5062           // A constant whose bitwise inverse can be used as an immediate
5063           // value in a data-processing instruction. This can be used in GCC
5064           // with a "B" modifier that prints the inverted value, for use with
5065           // BIC and MVN instructions. It is not useful otherwise but is
5066           // implemented for compatibility.
5067           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
5068             break;
5069         } else {
5070           // A constant whose bitwise inverse can be used as an immediate
5071           // value in a data-processing instruction. This can be used in GCC
5072           // with a "B" modifier that prints the inverted value, for use with
5073           // BIC and MVN instructions. It is not useful otherwise but is
5074           // implemented for compatibility.
5075           if (ARM_AM::getSOImmVal(~CVal) != -1)
5076             break;
5077         }
5078         return;
5079
5080       case 'L':
5081         if (Subtarget->isThumb1Only()) {
5082           // This must be a constant between -7 and 7,
5083           // for 3-operand ADD/SUB immediate instructions.
5084           if (CVal >= -7 && CVal < 7)
5085             break;
5086         } else if (Subtarget->isThumb2()) {
5087           // A constant whose negation can be used as an immediate value in a
5088           // data-processing instruction. This can be used in GCC with an "n"
5089           // modifier that prints the negated value, for use with SUB
5090           // instructions. It is not useful otherwise but is implemented for
5091           // compatibility.
5092           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
5093             break;
5094         } else {
5095           // A constant whose negation can be used as an immediate value in a
5096           // data-processing instruction. This can be used in GCC with an "n"
5097           // modifier that prints the negated value, for use with SUB
5098           // instructions. It is not useful otherwise but is implemented for
5099           // compatibility.
5100           if (ARM_AM::getSOImmVal(-CVal) != -1)
5101             break;
5102         }
5103         return;
5104
5105       case 'M':
5106         if (Subtarget->isThumb()) { // FIXME thumb2
5107           // This must be a multiple of 4 between 0 and 1020, for
5108           // ADD sp + immediate.
5109           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
5110             break;
5111         } else {
5112           // A power of two or a constant between 0 and 32.  This is used in
5113           // GCC for the shift amount on shifted register operands, but it is
5114           // useful in general for any shift amounts.
5115           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
5116             break;
5117         }
5118         return;
5119
5120       case 'N':
5121         if (Subtarget->isThumb()) {  // FIXME thumb2
5122           // This must be a constant between 0 and 31, for shift amounts.
5123           if (CVal >= 0 && CVal <= 31)
5124             break;
5125         }
5126         return;
5127
5128       case 'O':
5129         if (Subtarget->isThumb()) {  // FIXME thumb2
5130           // This must be a multiple of 4 between -508 and 508, for
5131           // ADD/SUB sp = sp + immediate.
5132           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
5133             break;
5134         }
5135         return;
5136     }
5137     Result = DAG.getTargetConstant(CVal, Op.getValueType());
5138     break;
5139   }
5140
5141   if (Result.getNode()) {
5142     Ops.push_back(Result);
5143     return;
5144   }
5145   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
5146                                                       Ops, DAG);
5147 }
5148
5149 bool
5150 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5151   // The ARM target isn't yet aware of offsets.
5152   return false;
5153 }
5154
5155 int ARM::getVFPf32Imm(const APFloat &FPImm) {
5156   APInt Imm = FPImm.bitcastToAPInt();
5157   uint32_t Sign = Imm.lshr(31).getZExtValue() & 1;
5158   int32_t Exp = (Imm.lshr(23).getSExtValue() & 0xff) - 127;  // -126 to 127
5159   int64_t Mantissa = Imm.getZExtValue() & 0x7fffff;  // 23 bits
5160
5161   // We can handle 4 bits of mantissa.
5162   // mantissa = (16+UInt(e:f:g:h))/16.
5163   if (Mantissa & 0x7ffff)
5164     return -1;
5165   Mantissa >>= 19;
5166   if ((Mantissa & 0xf) != Mantissa)
5167     return -1;
5168
5169   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
5170   if (Exp < -3 || Exp > 4)
5171     return -1;
5172   Exp = ((Exp+3) & 0x7) ^ 4;
5173
5174   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
5175 }
5176
5177 int ARM::getVFPf64Imm(const APFloat &FPImm) {
5178   APInt Imm = FPImm.bitcastToAPInt();
5179   uint64_t Sign = Imm.lshr(63).getZExtValue() & 1;
5180   int64_t Exp = (Imm.lshr(52).getSExtValue() & 0x7ff) - 1023;   // -1022 to 1023
5181   uint64_t Mantissa = Imm.getZExtValue() & 0xfffffffffffffLL;
5182
5183   // We can handle 4 bits of mantissa.
5184   // mantissa = (16+UInt(e:f:g:h))/16.
5185   if (Mantissa & 0xffffffffffffLL)
5186     return -1;
5187   Mantissa >>= 48;
5188   if ((Mantissa & 0xf) != Mantissa)
5189     return -1;
5190
5191   // We can handle 3 bits of exponent: exp == UInt(NOT(b):c:d)-3
5192   if (Exp < -3 || Exp > 4)
5193     return -1;
5194   Exp = ((Exp+3) & 0x7) ^ 4;
5195
5196   return ((int)Sign << 7) | (Exp << 4) | Mantissa;
5197 }
5198
5199 /// isFPImmLegal - Returns true if the target can instruction select the
5200 /// specified FP immediate natively. If false, the legalizer will
5201 /// materialize the FP immediate as a load from a constant pool.
5202 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
5203   if (!Subtarget->hasVFP3())
5204     return false;
5205   if (VT == MVT::f32)
5206     return ARM::getVFPf32Imm(Imm) != -1;
5207   if (VT == MVT::f64)
5208     return ARM::getVFPf64Imm(Imm) != -1;
5209   return false;
5210 }