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