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