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