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