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