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