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