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