ARMISelLowering.cpp revision 2dc4f54324a65665aed78840bc9d6d5ea5d6e7d1
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 "llvm/CallingConv.h"
24#include "llvm/Constants.h"
25#include "llvm/Instruction.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/GlobalValue.h"
28#include "llvm/CodeGen/MachineBasicBlock.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/Target/TargetOptions.h"
35#include "llvm/ADT/VectorExtras.h"
36#include "llvm/Support/MathExtras.h"
37using namespace llvm;
38
39ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
40    : TargetLowering(TM), ARMPCLabelIndex(0) {
41  Subtarget = &TM.getSubtarget<ARMSubtarget>();
42
43  if (Subtarget->isTargetDarwin()) {
44    // Uses VFP for Thumb libfuncs if available.
45    if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
46      // Single-precision floating-point arithmetic.
47      setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
48      setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
49      setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
50      setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
51
52      // Double-precision floating-point arithmetic.
53      setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
54      setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
55      setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
56      setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
57
58      // Single-precision comparisons.
59      setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
60      setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
61      setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
62      setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
63      setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
64      setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
65      setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
66      setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
67
68      setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
69      setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
70      setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
71      setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
72      setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
73      setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
74      setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
75      setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
76
77      // Double-precision comparisons.
78      setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
79      setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
80      setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
81      setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
82      setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
83      setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
84      setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
85      setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
86
87      setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
88      setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
89      setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
90      setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
91      setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
92      setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
93      setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
94      setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
95
96      // Floating-point to integer conversions.
97      // i64 conversions are done via library routines even when generating VFP
98      // instructions, so use the same ones.
99      setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
100      setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
101      setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
102      setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
103
104      // Conversions between floating types.
105      setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
106      setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
107
108      // Integer to floating-point conversions.
109      // i64 conversions are done via library routines even when generating VFP
110      // instructions, so use the same ones.
111      // FIXME: There appears to be some naming inconsistency in ARM libgcc: e.g.
112      // __floatunsidf vs. __floatunssidfvfp.
113      setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
114      setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
115      setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
116      setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
117    }
118  }
119
120  addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
121  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
122    addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
123    addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
124
125    setTruncStoreAction(MVT::f64, MVT::f32, Expand);
126  }
127  computeRegisterProperties();
128
129  // ARM does not have f32 extending load.
130  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
131
132  // ARM does not have i1 sign extending load.
133  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
134
135  // ARM supports all 4 flavors of integer indexed load / store.
136  for (unsigned im = (unsigned)ISD::PRE_INC;
137       im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
138    setIndexedLoadAction(im,  MVT::i1,  Legal);
139    setIndexedLoadAction(im,  MVT::i8,  Legal);
140    setIndexedLoadAction(im,  MVT::i16, Legal);
141    setIndexedLoadAction(im,  MVT::i32, Legal);
142    setIndexedStoreAction(im, MVT::i1,  Legal);
143    setIndexedStoreAction(im, MVT::i8,  Legal);
144    setIndexedStoreAction(im, MVT::i16, Legal);
145    setIndexedStoreAction(im, MVT::i32, Legal);
146  }
147
148  // i64 operation support.
149  if (Subtarget->isThumb()) {
150    setOperationAction(ISD::MUL,     MVT::i64, Expand);
151    setOperationAction(ISD::MULHU,   MVT::i32, Expand);
152    setOperationAction(ISD::MULHS,   MVT::i32, Expand);
153    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155  } else {
156    setOperationAction(ISD::MUL,     MVT::i64, Expand);
157    setOperationAction(ISD::MULHU,   MVT::i32, Expand);
158    if (!Subtarget->hasV6Ops())
159      setOperationAction(ISD::MULHS, MVT::i32, Expand);
160  }
161  setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
162  setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
163  setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
164  setOperationAction(ISD::SRL,       MVT::i64, Custom);
165  setOperationAction(ISD::SRA,       MVT::i64, Custom);
166
167  // ARM does not have ROTL.
168  setOperationAction(ISD::ROTL,  MVT::i32, Expand);
169  setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
170  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
171  if (!Subtarget->hasV5TOps() || Subtarget->isThumb())
172    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
173
174  // Only ARMv6 has BSWAP.
175  if (!Subtarget->hasV6Ops())
176    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
177
178  // These are expanded into libcalls.
179  setOperationAction(ISD::SDIV,  MVT::i32, Expand);
180  setOperationAction(ISD::UDIV,  MVT::i32, Expand);
181  setOperationAction(ISD::SREM,  MVT::i32, Expand);
182  setOperationAction(ISD::UREM,  MVT::i32, Expand);
183  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
184  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
185
186  // Support label based line numbers.
187  setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
188  setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
189
190  setOperationAction(ISD::RET,           MVT::Other, Custom);
191  setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
192  setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
193  setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
194  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
195
196  // Use the default implementation.
197  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
198  setOperationAction(ISD::VAARG,              MVT::Other, Expand);
199  setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
200  setOperationAction(ISD::VAEND,              MVT::Other, Expand);
201  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
202  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
203  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
204  setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
205
206  if (!Subtarget->hasV6Ops()) {
207    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
208    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
209  }
210  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
211
212  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb())
213    // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
214    setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
215
216  // We want to custom lower some of our intrinsics.
217  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
218
219  setOperationAction(ISD::SETCC,     MVT::i32, Expand);
220  setOperationAction(ISD::SETCC,     MVT::f32, Expand);
221  setOperationAction(ISD::SETCC,     MVT::f64, Expand);
222  setOperationAction(ISD::SELECT,    MVT::i32, Expand);
223  setOperationAction(ISD::SELECT,    MVT::f32, Expand);
224  setOperationAction(ISD::SELECT,    MVT::f64, Expand);
225  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
226  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
227  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
228
229  setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
230  setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
231  setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
232  setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
233  setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
234
235  // We don't support sin/cos/fmod/copysign/pow
236  setOperationAction(ISD::FSIN,      MVT::f64, Expand);
237  setOperationAction(ISD::FSIN,      MVT::f32, Expand);
238  setOperationAction(ISD::FCOS,      MVT::f32, Expand);
239  setOperationAction(ISD::FCOS,      MVT::f64, Expand);
240  setOperationAction(ISD::FREM,      MVT::f64, Expand);
241  setOperationAction(ISD::FREM,      MVT::f32, Expand);
242  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
243    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
244    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
245  }
246  setOperationAction(ISD::FPOW,      MVT::f64, Expand);
247  setOperationAction(ISD::FPOW,      MVT::f32, Expand);
248
249  // int <-> fp are custom expanded into bit_convert + ARMISD ops.
250  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
251    setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
252    setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
253    setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
254    setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255  }
256
257  // We have target-specific dag combine patterns for the following nodes:
258  // ARMISD::FMRRD  - No need to call setTargetDAGCombine
259  setTargetDAGCombine(ISD::ADD);
260  setTargetDAGCombine(ISD::SUB);
261
262  setStackPointerRegisterToSaveRestore(ARM::SP);
263  setSchedulingPreference(SchedulingForRegPressure);
264  setIfCvtBlockSizeLimit(Subtarget->isThumb() ? 0 : 10);
265  setIfCvtDupBlockSizeLimit(Subtarget->isThumb() ? 0 : 2);
266
267  maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
268}
269
270const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
271  switch (Opcode) {
272  default: return 0;
273  case ARMISD::Wrapper:       return "ARMISD::Wrapper";
274  case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
275  case ARMISD::CALL:          return "ARMISD::CALL";
276  case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
277  case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
278  case ARMISD::tCALL:         return "ARMISD::tCALL";
279  case ARMISD::BRCOND:        return "ARMISD::BRCOND";
280  case ARMISD::BR_JT:         return "ARMISD::BR_JT";
281  case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
282  case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
283  case ARMISD::CMP:           return "ARMISD::CMP";
284  case ARMISD::CMPNZ:         return "ARMISD::CMPNZ";
285  case ARMISD::CMPFP:         return "ARMISD::CMPFP";
286  case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
287  case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
288  case ARMISD::CMOV:          return "ARMISD::CMOV";
289  case ARMISD::CNEG:          return "ARMISD::CNEG";
290
291  case ARMISD::FTOSI:         return "ARMISD::FTOSI";
292  case ARMISD::FTOUI:         return "ARMISD::FTOUI";
293  case ARMISD::SITOF:         return "ARMISD::SITOF";
294  case ARMISD::UITOF:         return "ARMISD::UITOF";
295
296  case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
297  case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
298  case ARMISD::RRX:           return "ARMISD::RRX";
299
300  case ARMISD::FMRRD:         return "ARMISD::FMRRD";
301  case ARMISD::FMDRR:         return "ARMISD::FMDRR";
302
303  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
304  }
305}
306
307//===----------------------------------------------------------------------===//
308// Lowering Code
309//===----------------------------------------------------------------------===//
310
311/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
312static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
313  switch (CC) {
314  default: assert(0 && "Unknown condition code!");
315  case ISD::SETNE:  return ARMCC::NE;
316  case ISD::SETEQ:  return ARMCC::EQ;
317  case ISD::SETGT:  return ARMCC::GT;
318  case ISD::SETGE:  return ARMCC::GE;
319  case ISD::SETLT:  return ARMCC::LT;
320  case ISD::SETLE:  return ARMCC::LE;
321  case ISD::SETUGT: return ARMCC::HI;
322  case ISD::SETUGE: return ARMCC::HS;
323  case ISD::SETULT: return ARMCC::LO;
324  case ISD::SETULE: return ARMCC::LS;
325  }
326}
327
328/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
329/// returns true if the operands should be inverted to form the proper
330/// comparison.
331static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
332                        ARMCC::CondCodes &CondCode2) {
333  bool Invert = false;
334  CondCode2 = ARMCC::AL;
335  switch (CC) {
336  default: assert(0 && "Unknown FP condition!");
337  case ISD::SETEQ:
338  case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
339  case ISD::SETGT:
340  case ISD::SETOGT: CondCode = ARMCC::GT; break;
341  case ISD::SETGE:
342  case ISD::SETOGE: CondCode = ARMCC::GE; break;
343  case ISD::SETOLT: CondCode = ARMCC::MI; break;
344  case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
345  case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
346  case ISD::SETO:   CondCode = ARMCC::VC; break;
347  case ISD::SETUO:  CondCode = ARMCC::VS; break;
348  case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
349  case ISD::SETUGT: CondCode = ARMCC::HI; break;
350  case ISD::SETUGE: CondCode = ARMCC::PL; break;
351  case ISD::SETLT:
352  case ISD::SETULT: CondCode = ARMCC::LT; break;
353  case ISD::SETLE:
354  case ISD::SETULE: CondCode = ARMCC::LE; break;
355  case ISD::SETNE:
356  case ISD::SETUNE: CondCode = ARMCC::NE; break;
357  }
358  return Invert;
359}
360
361static void
362HowToPassArgument(MVT ObjectVT, unsigned NumGPRs,
363                  unsigned StackOffset, unsigned &NeededGPRs,
364                  unsigned &NeededStackSize, unsigned &GPRPad,
365                  unsigned &StackPad, ISD::ArgFlagsTy Flags) {
366  NeededStackSize = 0;
367  NeededGPRs = 0;
368  StackPad = 0;
369  GPRPad = 0;
370  unsigned align = Flags.getOrigAlign();
371  GPRPad = NumGPRs % ((align + 3)/4);
372  StackPad = StackOffset % align;
373  unsigned firstGPR = NumGPRs + GPRPad;
374  switch (ObjectVT.getSimpleVT()) {
375  default: assert(0 && "Unhandled argument type!");
376  case MVT::i32:
377  case MVT::f32:
378    if (firstGPR < 4)
379      NeededGPRs = 1;
380    else
381      NeededStackSize = 4;
382    break;
383  case MVT::i64:
384  case MVT::f64:
385    if (firstGPR < 3)
386      NeededGPRs = 2;
387    else if (firstGPR == 3) {
388      NeededGPRs = 1;
389      NeededStackSize = 4;
390    } else
391      NeededStackSize = 8;
392  }
393}
394
395/// LowerCALL - Lowering a ISD::CALL node into a callseq_start <-
396/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
397/// nodes.
398SDValue ARMTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
399  CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
400  MVT RetVT = TheCall->getRetValType(0);
401  SDValue Chain    = TheCall->getChain();
402  assert((TheCall->getCallingConv() == CallingConv::C ||
403          TheCall->getCallingConv() == CallingConv::Fast) &&
404         "unknown calling convention");
405  SDValue Callee   = TheCall->getCallee();
406  unsigned NumOps   = TheCall->getNumArgs();
407  DebugLoc dl       = TheCall->getDebugLoc();
408  unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
409  unsigned NumGPRs = 0;     // GPRs used for parameter passing.
410
411  // Count how many bytes are to be pushed on the stack.
412  unsigned NumBytes = 0;
413
414  // Add up all the space actually used.
415  for (unsigned i = 0; i < NumOps; ++i) {
416    unsigned ObjSize;
417    unsigned ObjGPRs;
418    unsigned StackPad;
419    unsigned GPRPad;
420    MVT ObjectVT = TheCall->getArg(i).getValueType();
421    ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
422    HowToPassArgument(ObjectVT, NumGPRs, NumBytes, ObjGPRs, ObjSize,
423                      GPRPad, StackPad, Flags);
424    NumBytes += ObjSize + StackPad;
425    NumGPRs += ObjGPRs + GPRPad;
426  }
427
428  // Adjust the stack pointer for the new arguments...
429  // These operations are automatically eliminated by the prolog/epilog pass
430  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
431
432  SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
433
434  static const unsigned GPRArgRegs[] = {
435    ARM::R0, ARM::R1, ARM::R2, ARM::R3
436  };
437
438  NumGPRs = 0;
439  std::vector<std::pair<unsigned, SDValue> > RegsToPass;
440  std::vector<SDValue> MemOpChains;
441  for (unsigned i = 0; i != NumOps; ++i) {
442    SDValue Arg = TheCall->getArg(i);
443    ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
444    MVT ArgVT = Arg.getValueType();
445
446    unsigned ObjSize;
447    unsigned ObjGPRs;
448    unsigned GPRPad;
449    unsigned StackPad;
450    HowToPassArgument(ArgVT, NumGPRs, ArgOffset, ObjGPRs,
451                      ObjSize, GPRPad, StackPad, Flags);
452    NumGPRs += GPRPad;
453    ArgOffset += StackPad;
454    if (ObjGPRs > 0) {
455      switch (ArgVT.getSimpleVT()) {
456      default: assert(0 && "Unexpected ValueType for argument!");
457      case MVT::i32:
458        RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Arg));
459        break;
460      case MVT::f32:
461        RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs],
462                             DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Arg)));
463        break;
464      case MVT::i64: {
465        SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
466                                   DAG.getConstant(0, getPointerTy()));
467        SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
468                                   DAG.getConstant(1, getPointerTy()));
469        RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Lo));
470        if (ObjGPRs == 2)
471          RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs+1], Hi));
472        else {
473          SDValue PtrOff= DAG.getConstant(ArgOffset, StackPtr.getValueType());
474          PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
475          MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff, NULL, 0));
476        }
477        break;
478      }
479      case MVT::f64: {
480        SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
481                                    DAG.getVTList(MVT::i32, MVT::i32),
482                                    &Arg, 1);
483        RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Cvt));
484        if (ObjGPRs == 2)
485          RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs+1],
486                                              Cvt.getValue(1)));
487        else {
488          SDValue PtrOff= DAG.getConstant(ArgOffset, StackPtr.getValueType());
489          PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
490          MemOpChains.push_back(DAG.getStore(Chain, dl, Cvt.getValue(1), PtrOff,
491                                             NULL, 0));
492        }
493        break;
494      }
495      }
496    } else {
497      assert(ObjSize != 0);
498      SDValue PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
499      PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
500      MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
501    }
502
503    NumGPRs += ObjGPRs;
504    ArgOffset += ObjSize;
505  }
506
507  if (!MemOpChains.empty())
508    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
509                        &MemOpChains[0], MemOpChains.size());
510
511  // Build a sequence of copy-to-reg nodes chained together with token chain
512  // and flag operands which copy the outgoing args into the appropriate regs.
513  SDValue InFlag;
514  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
515    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
516                             RegsToPass[i].second, InFlag);
517    InFlag = Chain.getValue(1);
518  }
519
520  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
521  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
522  // node so that legalize doesn't hack it.
523  bool isDirect = false;
524  bool isARMFunc = false;
525  bool isLocalARMFunc = false;
526  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
527    GlobalValue *GV = G->getGlobal();
528    isDirect = true;
529    bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
530                  GV->hasLinkOnceLinkage());
531    bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
532                   getTargetMachine().getRelocationModel() != Reloc::Static;
533    isARMFunc = !Subtarget->isThumb() || isStub;
534    // ARM call to a local ARM function is predicable.
535    isLocalARMFunc = !Subtarget->isThumb() && !isExt;
536    // tBX takes a register source operand.
537    if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
538      ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
539                                                           ARMCP::CPStub, 4);
540      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
541      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
542      Callee = DAG.getLoad(getPointerTy(), dl,
543                           DAG.getEntryNode(), CPAddr, NULL, 0);
544      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
545      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
546                           getPointerTy(), Callee, PICLabel);
547   } else
548      Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
549  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
550    isDirect = true;
551    bool isStub = Subtarget->isTargetDarwin() &&
552                  getTargetMachine().getRelocationModel() != Reloc::Static;
553    isARMFunc = !Subtarget->isThumb() || isStub;
554    // tBX takes a register source operand.
555    const char *Sym = S->getSymbol();
556    if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
557      ARMConstantPoolValue *CPV = new ARMConstantPoolValue(Sym, ARMPCLabelIndex,
558                                                           ARMCP::CPStub, 4);
559      SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
560      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
561      Callee = DAG.getLoad(getPointerTy(), dl,
562                           DAG.getEntryNode(), CPAddr, NULL, 0);
563      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
564      Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
565                           getPointerTy(), Callee, PICLabel);
566    } else
567      Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
568  }
569
570  // FIXME: handle tail calls differently.
571  unsigned CallOpc;
572  if (Subtarget->isThumb()) {
573    if (!Subtarget->hasV5TOps() && (!isDirect || isARMFunc))
574      CallOpc = ARMISD::CALL_NOLINK;
575    else
576      CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
577  } else {
578    CallOpc = (isDirect || Subtarget->hasV5TOps())
579      ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
580      : ARMISD::CALL_NOLINK;
581  }
582  if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb()) {
583    // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
584    Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
585    InFlag = Chain.getValue(1);
586  }
587
588  std::vector<SDValue> Ops;
589  Ops.push_back(Chain);
590  Ops.push_back(Callee);
591
592  // Add argument registers to the end of the list so that they are known live
593  // into the call.
594  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
595    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
596                                  RegsToPass[i].second.getValueType()));
597
598  if (InFlag.getNode())
599    Ops.push_back(InFlag);
600  // Returns a chain and a flag for retval copy to use.
601  Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
602                      &Ops[0], Ops.size());
603  InFlag = Chain.getValue(1);
604
605  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
606                             DAG.getIntPtrConstant(0, true), InFlag);
607  if (RetVT != MVT::Other)
608    InFlag = Chain.getValue(1);
609
610  std::vector<SDValue> ResultVals;
611
612  // If the call has results, copy the values out of the ret val registers.
613  switch (RetVT.getSimpleVT()) {
614  default: assert(0 && "Unexpected ret value!");
615  case MVT::Other:
616    break;
617  case MVT::i32:
618    Chain = DAG.getCopyFromReg(Chain, dl, ARM::R0,
619                               MVT::i32, InFlag).getValue(1);
620    ResultVals.push_back(Chain.getValue(0));
621    if (TheCall->getNumRetVals() > 1 &&
622        TheCall->getRetValType(1) == MVT::i32) {
623      // Returns a i64 value.
624      Chain = DAG.getCopyFromReg(Chain, dl, ARM::R1, MVT::i32,
625                                 Chain.getValue(2)).getValue(1);
626      ResultVals.push_back(Chain.getValue(0));
627    }
628    break;
629  case MVT::f32:
630    Chain = DAG.getCopyFromReg(Chain, dl, ARM::R0,
631                               MVT::i32, InFlag).getValue(1);
632    ResultVals.push_back(DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32,
633                                     Chain.getValue(0)));
634    break;
635  case MVT::f64: {
636    SDValue Lo = DAG.getCopyFromReg(Chain, dl, ARM::R0, MVT::i32, InFlag);
637    SDValue Hi = DAG.getCopyFromReg(Lo, dl, ARM::R1, MVT::i32, Lo.getValue(2));
638    ResultVals.push_back(DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi));
639    break;
640  }
641  }
642
643  if (ResultVals.empty())
644    return Chain;
645
646  ResultVals.push_back(Chain);
647  SDValue Res = DAG.getMergeValues(&ResultVals[0], ResultVals.size(), dl);
648  return Res.getValue(Op.getResNo());
649}
650
651static SDValue LowerRET(SDValue Op, SelectionDAG &DAG) {
652  SDValue Copy;
653  SDValue Chain = Op.getOperand(0);
654  DebugLoc dl = Op.getDebugLoc();
655  switch(Op.getNumOperands()) {
656  default:
657    assert(0 && "Do not know how to return this many arguments!");
658    abort();
659  case 1: {
660    SDValue LR = DAG.getRegister(ARM::LR, MVT::i32);
661    return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
662  }
663  case 3:
664    Op = Op.getOperand(1);
665    if (Op.getValueType() == MVT::f32) {
666      Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
667    } else if (Op.getValueType() == MVT::f64) {
668      // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
669      // available.
670      Op = DAG.getNode(ARMISD::FMRRD, dl,
671                       DAG.getVTList(MVT::i32, MVT::i32), &Op,1);
672      SDValue Sign = DAG.getConstant(0, MVT::i32);
673      return DAG.getNode(ISD::RET, dl, MVT::Other, Chain, Op, Sign,
674                         Op.getValue(1), Sign);
675    }
676    Copy = DAG.getCopyToReg(Chain, dl, ARM::R0, Op, SDValue());
677    if (DAG.getMachineFunction().getRegInfo().liveout_empty())
678      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
679    break;
680  case 5:
681    Copy = DAG.getCopyToReg(Chain, dl, ARM::R1, Op.getOperand(3), SDValue());
682    Copy = DAG.getCopyToReg(Copy, dl, ARM::R0, Op.getOperand(1),
683                            Copy.getValue(1));
684    // If we haven't noted the R0+R1 are live out, do so now.
685    if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
686      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
687      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R1);
688    }
689    break;
690  case 9:  // i128 -> 4 regs
691    Copy = DAG.getCopyToReg(Chain, dl, ARM::R3, Op.getOperand(7), SDValue());
692    Copy = DAG.getCopyToReg(Copy, dl, ARM::R2, Op.getOperand(5),
693                            Copy.getValue(1));
694    Copy = DAG.getCopyToReg(Copy, dl, ARM::R1, Op.getOperand(3),
695                            Copy.getValue(1));
696    Copy = DAG.getCopyToReg(Copy, dl, ARM::R0, Op.getOperand(1),
697                            Copy.getValue(1));
698    // If we haven't noted the R0+R1 are live out, do so now.
699    if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
700      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
701      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R1);
702      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R2);
703      DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R3);
704    }
705    break;
706
707  }
708
709  //We must use RET_FLAG instead of BRIND because BRIND doesn't have a flag
710  return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Copy, Copy.getValue(1));
711}
712
713// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
714// their target countpart wrapped in the ARMISD::Wrapper node. Suppose N is
715// one of the above mentioned nodes. It has to be wrapped because otherwise
716// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
717// be used to form addressing mode. These wrapped nodes will be selected
718// into MOVi.
719static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
720  MVT PtrVT = Op.getValueType();
721  // FIXME there is no actual debug info here
722  DebugLoc dl = Op.getDebugLoc();
723  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
724  SDValue Res;
725  if (CP->isMachineConstantPoolEntry())
726    Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
727                                    CP->getAlignment());
728  else
729    Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
730                                    CP->getAlignment());
731  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
732}
733
734// Lower ISD::GlobalTLSAddress using the "general dynamic" model
735SDValue
736ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
737                                                 SelectionDAG &DAG) {
738  DebugLoc dl = GA->getDebugLoc();
739  MVT PtrVT = getPointerTy();
740  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
741  ARMConstantPoolValue *CPV =
742    new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
743                             PCAdj, "tlsgd", true);
744  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
745  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
746  Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
747  SDValue Chain = Argument.getValue(1);
748
749  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
750  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
751
752  // call __tls_get_addr.
753  ArgListTy Args;
754  ArgListEntry Entry;
755  Entry.Node = Argument;
756  Entry.Ty = (const Type *) Type::Int32Ty;
757  Args.push_back(Entry);
758  // FIXME: is there useful debug info available here?
759  std::pair<SDValue, SDValue> CallResult =
760    LowerCallTo(Chain, (const Type *) Type::Int32Ty, false, false, false, false,
761                CallingConv::C, false,
762                DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
763  return CallResult.first;
764}
765
766// Lower ISD::GlobalTLSAddress using the "initial exec" or
767// "local exec" model.
768SDValue
769ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
770                                        SelectionDAG &DAG) {
771  GlobalValue *GV = GA->getGlobal();
772  DebugLoc dl = GA->getDebugLoc();
773  SDValue Offset;
774  SDValue Chain = DAG.getEntryNode();
775  MVT PtrVT = getPointerTy();
776  // Get the Thread Pointer
777  SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
778
779  if (GV->isDeclaration()){
780    // initial exec model
781    unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
782    ARMConstantPoolValue *CPV =
783      new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
784                               PCAdj, "gottpoff", true);
785    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
786    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
787    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
788    Chain = Offset.getValue(1);
789
790    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
791    Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
792
793    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
794  } else {
795    // local exec model
796    ARMConstantPoolValue *CPV =
797      new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
798    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
799    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
800    Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
801  }
802
803  // The address of the thread local variable is the add of the thread
804  // pointer with the offset of the variable.
805  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
806}
807
808SDValue
809ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
810  // TODO: implement the "local dynamic" model
811  assert(Subtarget->isTargetELF() &&
812         "TLS not implemented for non-ELF targets");
813  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
814  // If the relocation model is PIC, use the "General Dynamic" TLS Model,
815  // otherwise use the "Local Exec" TLS Model
816  if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
817    return LowerToTLSGeneralDynamicModel(GA, DAG);
818  else
819    return LowerToTLSExecModels(GA, DAG);
820}
821
822SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
823                                                 SelectionDAG &DAG) {
824  MVT PtrVT = getPointerTy();
825  DebugLoc dl = Op.getDebugLoc();
826  GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
827  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
828  if (RelocM == Reloc::PIC_) {
829    bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
830    ARMConstantPoolValue *CPV =
831      new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
832    SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
833    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
834    SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
835                                 CPAddr, NULL, 0);
836    SDValue Chain = Result.getValue(1);
837    SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
838    Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
839    if (!UseGOTOFF)
840      Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
841    return Result;
842  } else {
843    SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
844    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
845    return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
846  }
847}
848
849/// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
850/// even in non-static mode.
851static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
852  // If symbol visibility is hidden, the extra load is not needed if
853  // the symbol is definitely defined in the current translation unit.
854  bool isDecl = GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode();
855  if (GV->hasHiddenVisibility() && (!isDecl && !GV->hasCommonLinkage()))
856    return false;
857  return RelocM != Reloc::Static && (isDecl || GV->isWeakForLinker());
858}
859
860SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
861                                                    SelectionDAG &DAG) {
862  MVT PtrVT = getPointerTy();
863  DebugLoc dl = Op.getDebugLoc();
864  GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
865  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
866  bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
867  SDValue CPAddr;
868  if (RelocM == Reloc::Static)
869    CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
870  else {
871    unsigned PCAdj = (RelocM != Reloc::PIC_)
872      ? 0 : (Subtarget->isThumb() ? 4 : 8);
873    ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
874      : ARMCP::CPValue;
875    ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
876                                                         Kind, PCAdj);
877    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
878  }
879  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
880
881  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
882  SDValue Chain = Result.getValue(1);
883
884  if (RelocM == Reloc::PIC_) {
885    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
886    Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
887  }
888  if (IsIndirect)
889    Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
890
891  return Result;
892}
893
894SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
895                                                    SelectionDAG &DAG){
896  assert(Subtarget->isTargetELF() &&
897         "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
898  MVT PtrVT = getPointerTy();
899  DebugLoc dl = Op.getDebugLoc();
900  unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
901  ARMConstantPoolValue *CPV = new ARMConstantPoolValue("_GLOBAL_OFFSET_TABLE_",
902                                                       ARMPCLabelIndex,
903                                                       ARMCP::CPValue, PCAdj);
904  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
905  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
906  SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
907  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
908  return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
909}
910
911static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
912  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
913  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
914  switch (IntNo) {
915  default: return SDValue();    // Don't custom lower most intrinsics.
916  case Intrinsic::arm_thread_pointer:
917      return DAG.getNode(ARMISD::THREAD_POINTER, DebugLoc::getUnknownLoc(),
918                         PtrVT);
919  }
920}
921
922static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
923                            unsigned VarArgsFrameIndex) {
924  // vastart just stores the address of the VarArgsFrameIndex slot into the
925  // memory location argument.
926  DebugLoc dl = Op.getDebugLoc();
927  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
928  SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
929  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
930  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
931}
932
933static SDValue LowerFORMAL_ARGUMENT(SDValue Op, SelectionDAG &DAG,
934                                    unsigned ArgNo, unsigned &NumGPRs,
935                                    unsigned &ArgOffset, DebugLoc dl) {
936  MachineFunction &MF = DAG.getMachineFunction();
937  MVT ObjectVT = Op.getValue(ArgNo).getValueType();
938  SDValue Root = Op.getOperand(0);
939  MachineRegisterInfo &RegInfo = MF.getRegInfo();
940
941  static const unsigned GPRArgRegs[] = {
942    ARM::R0, ARM::R1, ARM::R2, ARM::R3
943  };
944
945  unsigned ObjSize;
946  unsigned ObjGPRs;
947  unsigned GPRPad;
948  unsigned StackPad;
949  ISD::ArgFlagsTy Flags =
950    cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo + 3))->getArgFlags();
951  HowToPassArgument(ObjectVT, NumGPRs, ArgOffset, ObjGPRs,
952                    ObjSize, GPRPad, StackPad, Flags);
953  NumGPRs += GPRPad;
954  ArgOffset += StackPad;
955
956  SDValue ArgValue;
957  if (ObjGPRs == 1) {
958    unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
959    RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
960    ArgValue = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
961    if (ObjectVT == MVT::f32)
962      ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, ArgValue);
963  } else if (ObjGPRs == 2) {
964    unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
965    RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
966    ArgValue = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
967
968    VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
969    RegInfo.addLiveIn(GPRArgRegs[NumGPRs+1], VReg);
970    SDValue ArgValue2 = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
971
972    assert(ObjectVT != MVT::i64 && "i64 should already be lowered");
973    ArgValue = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
974  }
975  NumGPRs += ObjGPRs;
976
977  if (ObjSize) {
978    MachineFrameInfo *MFI = MF.getFrameInfo();
979    int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
980    SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
981    if (ObjGPRs == 0)
982      ArgValue = DAG.getLoad(ObjectVT, dl, Root, FIN, NULL, 0);
983    else {
984      SDValue ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
985      assert(ObjectVT != MVT::i64 && "i64 should already be lowered");
986      ArgValue = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
987    }
988
989    ArgOffset += ObjSize;   // Move on to the next argument.
990  }
991
992  return ArgValue;
993}
994
995SDValue
996ARMTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
997  std::vector<SDValue> ArgValues;
998  SDValue Root = Op.getOperand(0);
999  DebugLoc dl = Op.getDebugLoc();
1000  unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
1001  unsigned NumGPRs = 0;     // GPRs used for parameter passing.
1002
1003  unsigned NumArgs = Op.getNode()->getNumValues()-1;
1004  for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
1005    ArgValues.push_back(LowerFORMAL_ARGUMENT(Op, DAG, ArgNo,
1006                                             NumGPRs, ArgOffset, dl));
1007
1008  bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1009  if (isVarArg) {
1010    static const unsigned GPRArgRegs[] = {
1011      ARM::R0, ARM::R1, ARM::R2, ARM::R3
1012    };
1013
1014    MachineFunction &MF = DAG.getMachineFunction();
1015    MachineRegisterInfo &RegInfo = MF.getRegInfo();
1016    MachineFrameInfo *MFI = MF.getFrameInfo();
1017    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1018    unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1019    unsigned VARegSize = (4 - NumGPRs) * 4;
1020    unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1021    if (VARegSaveSize) {
1022      // If this function is vararg, store any remaining integer argument regs
1023      // to their spots on the stack so that they may be loaded by deferencing
1024      // the result of va_next.
1025      AFI->setVarArgsRegSaveSize(VARegSaveSize);
1026      VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1027                                                 VARegSaveSize - VARegSize);
1028      SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1029
1030      SmallVector<SDValue, 4> MemOps;
1031      for (; NumGPRs < 4; ++NumGPRs) {
1032        unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
1033        RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
1034        SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
1035        SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1036        MemOps.push_back(Store);
1037        FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1038                          DAG.getConstant(4, getPointerTy()));
1039      }
1040      if (!MemOps.empty())
1041        Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1042                           &MemOps[0], MemOps.size());
1043    } else
1044      // This will point to the next argument passed via stack.
1045      VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1046  }
1047
1048  ArgValues.push_back(Root);
1049
1050  // Return the new list of results.
1051  return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1052                     &ArgValues[0], ArgValues.size());
1053}
1054
1055/// isFloatingPointZero - Return true if this is +0.0.
1056static bool isFloatingPointZero(SDValue Op) {
1057  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1058    return CFP->getValueAPF().isPosZero();
1059  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1060    // Maybe this has already been legalized into the constant pool?
1061    if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1062      SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1063      if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1064        if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1065          return CFP->getValueAPF().isPosZero();
1066    }
1067  }
1068  return false;
1069}
1070
1071static bool isLegalCmpImmediate(unsigned C, bool isThumb) {
1072  return ( isThumb && (C & ~255U) == 0) ||
1073         (!isThumb && ARM_AM::getSOImmVal(C) != -1);
1074}
1075
1076/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1077/// the given operands.
1078static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1079                         SDValue &ARMCC, SelectionDAG &DAG, bool isThumb,
1080                         DebugLoc dl) {
1081  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1082    unsigned C = RHSC->getZExtValue();
1083    if (!isLegalCmpImmediate(C, isThumb)) {
1084      // Constant does not fit, try adjusting it by one?
1085      switch (CC) {
1086      default: break;
1087      case ISD::SETLT:
1088      case ISD::SETGE:
1089        if (isLegalCmpImmediate(C-1, isThumb)) {
1090          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1091          RHS = DAG.getConstant(C-1, MVT::i32);
1092        }
1093        break;
1094      case ISD::SETULT:
1095      case ISD::SETUGE:
1096        if (C > 0 && isLegalCmpImmediate(C-1, isThumb)) {
1097          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1098          RHS = DAG.getConstant(C-1, MVT::i32);
1099        }
1100        break;
1101      case ISD::SETLE:
1102      case ISD::SETGT:
1103        if (isLegalCmpImmediate(C+1, isThumb)) {
1104          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1105          RHS = DAG.getConstant(C+1, MVT::i32);
1106        }
1107        break;
1108      case ISD::SETULE:
1109      case ISD::SETUGT:
1110        if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb)) {
1111          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1112          RHS = DAG.getConstant(C+1, MVT::i32);
1113        }
1114        break;
1115      }
1116    }
1117  }
1118
1119  ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1120  ARMISD::NodeType CompareType;
1121  switch (CondCode) {
1122  default:
1123    CompareType = ARMISD::CMP;
1124    break;
1125  case ARMCC::EQ:
1126  case ARMCC::NE:
1127  case ARMCC::MI:
1128  case ARMCC::PL:
1129    // Uses only N and Z Flags
1130    CompareType = ARMISD::CMPNZ;
1131    break;
1132  }
1133  ARMCC = DAG.getConstant(CondCode, MVT::i32);
1134  return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1135}
1136
1137/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1138static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1139                         DebugLoc dl) {
1140  SDValue Cmp;
1141  if (!isFloatingPointZero(RHS))
1142    Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1143  else
1144    Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1145  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1146}
1147
1148static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1149                              const ARMSubtarget *ST) {
1150  MVT VT = Op.getValueType();
1151  SDValue LHS = Op.getOperand(0);
1152  SDValue RHS = Op.getOperand(1);
1153  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1154  SDValue TrueVal = Op.getOperand(2);
1155  SDValue FalseVal = Op.getOperand(3);
1156  DebugLoc dl = Op.getDebugLoc();
1157
1158  if (LHS.getValueType() == MVT::i32) {
1159    SDValue ARMCC;
1160    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1161    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb(), dl);
1162    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1163  }
1164
1165  ARMCC::CondCodes CondCode, CondCode2;
1166  if (FPCCToARMCC(CC, CondCode, CondCode2))
1167    std::swap(TrueVal, FalseVal);
1168
1169  SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1170  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1171  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1172  SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1173                                 ARMCC, CCR, Cmp);
1174  if (CondCode2 != ARMCC::AL) {
1175    SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1176    // FIXME: Needs another CMP because flag can have but one use.
1177    SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1178    Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1179                         Result, TrueVal, ARMCC2, CCR, Cmp2);
1180  }
1181  return Result;
1182}
1183
1184static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1185                          const ARMSubtarget *ST) {
1186  SDValue  Chain = Op.getOperand(0);
1187  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1188  SDValue    LHS = Op.getOperand(2);
1189  SDValue    RHS = Op.getOperand(3);
1190  SDValue   Dest = Op.getOperand(4);
1191  DebugLoc dl = Op.getDebugLoc();
1192
1193  if (LHS.getValueType() == MVT::i32) {
1194    SDValue ARMCC;
1195    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1196    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb(), dl);
1197    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1198                       Chain, Dest, ARMCC, CCR,Cmp);
1199  }
1200
1201  assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1202  ARMCC::CondCodes CondCode, CondCode2;
1203  if (FPCCToARMCC(CC, CondCode, CondCode2))
1204    // Swap the LHS/RHS of the comparison if needed.
1205    std::swap(LHS, RHS);
1206
1207  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1208  SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1209  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1210  SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1211  SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1212  SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1213  if (CondCode2 != ARMCC::AL) {
1214    ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1215    SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1216    Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1217  }
1218  return Res;
1219}
1220
1221SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1222  SDValue Chain = Op.getOperand(0);
1223  SDValue Table = Op.getOperand(1);
1224  SDValue Index = Op.getOperand(2);
1225  DebugLoc dl = Op.getDebugLoc();
1226
1227  MVT PTy = getPointerTy();
1228  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1229  ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1230  SDValue UId =  DAG.getConstant(AFI->createJumpTableUId(), PTy);
1231  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1232  Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1233  Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1234  SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1235  bool isPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1236  Addr = DAG.getLoad(isPIC ? (MVT)MVT::i32 : PTy, dl,
1237                     Chain, Addr, NULL, 0);
1238  Chain = Addr.getValue(1);
1239  if (isPIC)
1240    Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1241  return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1242}
1243
1244static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1245  DebugLoc dl = Op.getDebugLoc();
1246  unsigned Opc =
1247    Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1248  Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1249  return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1250}
1251
1252static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1253  MVT VT = Op.getValueType();
1254  DebugLoc dl = Op.getDebugLoc();
1255  unsigned Opc =
1256    Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1257
1258  Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1259  return DAG.getNode(Opc, dl, VT, Op);
1260}
1261
1262static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1263  // Implement fcopysign with a fabs and a conditional fneg.
1264  SDValue Tmp0 = Op.getOperand(0);
1265  SDValue Tmp1 = Op.getOperand(1);
1266  DebugLoc dl = Op.getDebugLoc();
1267  MVT VT = Op.getValueType();
1268  MVT SrcVT = Tmp1.getValueType();
1269  SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1270  SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1271  SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1272  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1273  return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1274}
1275
1276SDValue
1277ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1278                                           SDValue Chain,
1279                                           SDValue Dst, SDValue Src,
1280                                           SDValue Size, unsigned Align,
1281                                           bool AlwaysInline,
1282                                         const Value *DstSV, uint64_t DstSVOff,
1283                                         const Value *SrcSV, uint64_t SrcSVOff){
1284  // Do repeated 4-byte loads and stores. To be improved.
1285  // This requires 4-byte alignment.
1286  if ((Align & 3) != 0)
1287    return SDValue();
1288  // This requires the copy size to be a constant, preferrably
1289  // within a subtarget-specific limit.
1290  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1291  if (!ConstantSize)
1292    return SDValue();
1293  uint64_t SizeVal = ConstantSize->getZExtValue();
1294  if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1295    return SDValue();
1296
1297  unsigned BytesLeft = SizeVal & 3;
1298  unsigned NumMemOps = SizeVal >> 2;
1299  unsigned EmittedNumMemOps = 0;
1300  MVT VT = MVT::i32;
1301  unsigned VTSize = 4;
1302  unsigned i = 0;
1303  const unsigned MAX_LOADS_IN_LDM = 6;
1304  SDValue TFOps[MAX_LOADS_IN_LDM];
1305  SDValue Loads[MAX_LOADS_IN_LDM];
1306  uint64_t SrcOff = 0, DstOff = 0;
1307
1308  // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1309  // same number of stores.  The loads and stores will get combined into
1310  // ldm/stm later on.
1311  while (EmittedNumMemOps < NumMemOps) {
1312    for (i = 0;
1313         i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1314      Loads[i] = DAG.getLoad(VT, dl, Chain,
1315                             DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1316                                         DAG.getConstant(SrcOff, MVT::i32)),
1317                             SrcSV, SrcSVOff + SrcOff);
1318      TFOps[i] = Loads[i].getValue(1);
1319      SrcOff += VTSize;
1320    }
1321    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1322
1323    for (i = 0;
1324         i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1325      TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1326                           DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1327                                       DAG.getConstant(DstOff, MVT::i32)),
1328                           DstSV, DstSVOff + DstOff);
1329      DstOff += VTSize;
1330    }
1331    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1332
1333    EmittedNumMemOps += i;
1334  }
1335
1336  if (BytesLeft == 0)
1337    return Chain;
1338
1339  // Issue loads / stores for the trailing (1 - 3) bytes.
1340  unsigned BytesLeftSave = BytesLeft;
1341  i = 0;
1342  while (BytesLeft) {
1343    if (BytesLeft >= 2) {
1344      VT = MVT::i16;
1345      VTSize = 2;
1346    } else {
1347      VT = MVT::i8;
1348      VTSize = 1;
1349    }
1350
1351    Loads[i] = DAG.getLoad(VT, dl, Chain,
1352                           DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1353                                       DAG.getConstant(SrcOff, MVT::i32)),
1354                           SrcSV, SrcSVOff + SrcOff);
1355    TFOps[i] = Loads[i].getValue(1);
1356    ++i;
1357    SrcOff += VTSize;
1358    BytesLeft -= VTSize;
1359  }
1360  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1361
1362  i = 0;
1363  BytesLeft = BytesLeftSave;
1364  while (BytesLeft) {
1365    if (BytesLeft >= 2) {
1366      VT = MVT::i16;
1367      VTSize = 2;
1368    } else {
1369      VT = MVT::i8;
1370      VTSize = 1;
1371    }
1372
1373    TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1374                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1375                                        DAG.getConstant(DstOff, MVT::i32)),
1376                            DstSV, DstSVOff + DstOff);
1377    ++i;
1378    DstOff += VTSize;
1379    BytesLeft -= VTSize;
1380  }
1381  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1382}
1383
1384static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1385  SDValue Op = N->getOperand(0);
1386  DebugLoc dl = N->getDebugLoc();
1387  if (N->getValueType(0) == MVT::f64) {
1388    // Turn i64->f64 into FMDRR.
1389    SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1390                             DAG.getConstant(0, MVT::i32));
1391    SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1392                             DAG.getConstant(1, MVT::i32));
1393    return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
1394  }
1395
1396  // Turn f64->i64 into FMRRD.
1397  SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
1398                            DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
1399
1400  // Merge the pieces into a single i64 value.
1401  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
1402}
1403
1404static SDValue ExpandSRx(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST) {
1405  assert(N->getValueType(0) == MVT::i64 &&
1406         (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
1407         "Unknown shift to lower!");
1408
1409  // We only lower SRA, SRL of 1 here, all others use generic lowering.
1410  if (!isa<ConstantSDNode>(N->getOperand(1)) ||
1411      cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
1412    return SDValue();
1413
1414  // If we are in thumb mode, we don't have RRX.
1415  if (ST->isThumb()) return SDValue();
1416
1417  // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
1418  DebugLoc dl = N->getDebugLoc();
1419  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
1420                             DAG.getConstant(0, MVT::i32));
1421  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
1422                             DAG.getConstant(1, MVT::i32));
1423
1424  // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
1425  // captures the result into a carry flag.
1426  unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
1427  Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
1428
1429  // The low part is an ARMISD::RRX operand, which shifts the carry in.
1430  Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
1431
1432  // Merge the pieces into a single i64 value.
1433 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1434}
1435
1436SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
1437  switch (Op.getOpcode()) {
1438  default: assert(0 && "Don't know how to custom lower this!"); abort();
1439  case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
1440  case ISD::GlobalAddress:
1441    return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
1442      LowerGlobalAddressELF(Op, DAG);
1443  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
1444  case ISD::CALL:          return LowerCALL(Op, DAG);
1445  case ISD::RET:           return LowerRET(Op, DAG);
1446  case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
1447  case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
1448  case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
1449  case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
1450  case ISD::SINT_TO_FP:
1451  case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
1452  case ISD::FP_TO_SINT:
1453  case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
1454  case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
1455  case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
1456  case ISD::RETURNADDR:    break;
1457  case ISD::FRAMEADDR:     break;
1458  case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
1459  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1460  case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
1461  case ISD::SRL:
1462  case ISD::SRA:           return ExpandSRx(Op.getNode(), DAG,Subtarget);
1463  }
1464  return SDValue();
1465}
1466
1467/// ReplaceNodeResults - Replace the results of node with an illegal result
1468/// type with new values built out of custom code.
1469void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
1470                                           SmallVectorImpl<SDValue>&Results,
1471                                           SelectionDAG &DAG) {
1472  switch (N->getOpcode()) {
1473  default:
1474    assert(0 && "Don't know how to custom expand this!");
1475    return;
1476  case ISD::BIT_CONVERT:
1477    Results.push_back(ExpandBIT_CONVERT(N, DAG));
1478    return;
1479  case ISD::SRL:
1480  case ISD::SRA: {
1481    SDValue Res = ExpandSRx(N, DAG, Subtarget);
1482    if (Res.getNode())
1483      Results.push_back(Res);
1484    return;
1485  }
1486  }
1487}
1488
1489//===----------------------------------------------------------------------===//
1490//                           ARM Scheduler Hooks
1491//===----------------------------------------------------------------------===//
1492
1493MachineBasicBlock *
1494ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1495                                               MachineBasicBlock *BB) const {
1496  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1497  DebugLoc dl = MI->getDebugLoc();
1498  switch (MI->getOpcode()) {
1499  default: assert(false && "Unexpected instr type to insert");
1500  case ARM::tMOVCCr: {
1501    // To "insert" a SELECT_CC instruction, we actually have to insert the
1502    // diamond control-flow pattern.  The incoming instruction knows the
1503    // destination vreg to set, the condition code register to branch on, the
1504    // true/false values to select between, and a branch opcode to use.
1505    const BasicBlock *LLVM_BB = BB->getBasicBlock();
1506    MachineFunction::iterator It = BB;
1507    ++It;
1508
1509    //  thisMBB:
1510    //  ...
1511    //   TrueVal = ...
1512    //   cmpTY ccX, r1, r2
1513    //   bCC copy1MBB
1514    //   fallthrough --> copy0MBB
1515    MachineBasicBlock *thisMBB  = BB;
1516    MachineFunction *F = BB->getParent();
1517    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1518    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1519    BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
1520      .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
1521    F->insert(It, copy0MBB);
1522    F->insert(It, sinkMBB);
1523    // Update machine-CFG edges by first adding all successors of the current
1524    // block to the new block which will contain the Phi node for the select.
1525    for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
1526        e = BB->succ_end(); i != e; ++i)
1527      sinkMBB->addSuccessor(*i);
1528    // Next, remove all successors of the current block, and add the true
1529    // and fallthrough blocks as its successors.
1530    while(!BB->succ_empty())
1531      BB->removeSuccessor(BB->succ_begin());
1532    BB->addSuccessor(copy0MBB);
1533    BB->addSuccessor(sinkMBB);
1534
1535    //  copy0MBB:
1536    //   %FalseValue = ...
1537    //   # fallthrough to sinkMBB
1538    BB = copy0MBB;
1539
1540    // Update machine-CFG edges
1541    BB->addSuccessor(sinkMBB);
1542
1543    //  sinkMBB:
1544    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1545    //  ...
1546    BB = sinkMBB;
1547    BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
1548      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1549      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1550
1551    F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1552    return BB;
1553  }
1554  }
1555}
1556
1557//===----------------------------------------------------------------------===//
1558//                           ARM Optimization Hooks
1559//===----------------------------------------------------------------------===//
1560
1561static
1562SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
1563                            TargetLowering::DAGCombinerInfo &DCI) {
1564  SelectionDAG &DAG = DCI.DAG;
1565  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1566  MVT VT = N->getValueType(0);
1567  unsigned Opc = N->getOpcode();
1568  bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
1569  SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
1570  SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
1571  ISD::CondCode CC = ISD::SETCC_INVALID;
1572
1573  if (isSlctCC) {
1574    CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
1575  } else {
1576    SDValue CCOp = Slct.getOperand(0);
1577    if (CCOp.getOpcode() == ISD::SETCC)
1578      CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
1579  }
1580
1581  bool DoXform = false;
1582  bool InvCC = false;
1583  assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
1584          "Bad input!");
1585
1586  if (LHS.getOpcode() == ISD::Constant &&
1587      cast<ConstantSDNode>(LHS)->isNullValue()) {
1588    DoXform = true;
1589  } else if (CC != ISD::SETCC_INVALID &&
1590             RHS.getOpcode() == ISD::Constant &&
1591             cast<ConstantSDNode>(RHS)->isNullValue()) {
1592    std::swap(LHS, RHS);
1593    SDValue Op0 = Slct.getOperand(0);
1594    MVT OpVT = isSlctCC ? Op0.getValueType() :
1595                          Op0.getOperand(0).getValueType();
1596    bool isInt = OpVT.isInteger();
1597    CC = ISD::getSetCCInverse(CC, isInt);
1598
1599    if (!TLI.isCondCodeLegal(CC, OpVT))
1600      return SDValue();         // Inverse operator isn't legal.
1601
1602    DoXform = true;
1603    InvCC = true;
1604  }
1605
1606  if (DoXform) {
1607    SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
1608    if (isSlctCC)
1609      return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
1610                             Slct.getOperand(0), Slct.getOperand(1), CC);
1611    SDValue CCOp = Slct.getOperand(0);
1612    if (InvCC)
1613      CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
1614                          CCOp.getOperand(0), CCOp.getOperand(1), CC);
1615    return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
1616                       CCOp, OtherOp, Result);
1617  }
1618  return SDValue();
1619}
1620
1621/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
1622static SDValue PerformADDCombine(SDNode *N,
1623                                 TargetLowering::DAGCombinerInfo &DCI) {
1624  // added by evan in r37685 with no testcase.
1625  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1626
1627  // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1628  if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
1629    SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
1630    if (Result.getNode()) return Result;
1631  }
1632  if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1633    SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
1634    if (Result.getNode()) return Result;
1635  }
1636
1637  return SDValue();
1638}
1639
1640/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
1641static SDValue PerformSUBCombine(SDNode *N,
1642                                 TargetLowering::DAGCombinerInfo &DCI) {
1643  // added by evan in r37685 with no testcase.
1644  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1645
1646  // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1647  if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1648    SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
1649    if (Result.getNode()) return Result;
1650  }
1651
1652  return SDValue();
1653}
1654
1655
1656/// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
1657static SDValue PerformFMRRDCombine(SDNode *N,
1658                                   TargetLowering::DAGCombinerInfo &DCI) {
1659  // fmrrd(fmdrr x, y) -> x,y
1660  SDValue InDouble = N->getOperand(0);
1661  if (InDouble.getOpcode() == ARMISD::FMDRR)
1662    return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
1663  return SDValue();
1664}
1665
1666SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
1667                                             DAGCombinerInfo &DCI) const {
1668  switch (N->getOpcode()) {
1669  default: break;
1670  case ISD::ADD:      return PerformADDCombine(N, DCI);
1671  case ISD::SUB:      return PerformSUBCombine(N, DCI);
1672  case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
1673  }
1674
1675  return SDValue();
1676}
1677
1678/// isLegalAddressImmediate - Return true if the integer value can be used
1679/// as the offset of the target addressing mode for load / store of the
1680/// given type.
1681static bool isLegalAddressImmediate(int64_t V, MVT VT,
1682                                    const ARMSubtarget *Subtarget) {
1683  if (V == 0)
1684    return true;
1685
1686  if (!VT.isSimple())
1687    return false;
1688
1689  if (Subtarget->isThumb()) {
1690    if (V < 0)
1691      return false;
1692
1693    unsigned Scale = 1;
1694    switch (VT.getSimpleVT()) {
1695    default: return false;
1696    case MVT::i1:
1697    case MVT::i8:
1698      // Scale == 1;
1699      break;
1700    case MVT::i16:
1701      // Scale == 2;
1702      Scale = 2;
1703      break;
1704    case MVT::i32:
1705      // Scale == 4;
1706      Scale = 4;
1707      break;
1708    }
1709
1710    if ((V & (Scale - 1)) != 0)
1711      return false;
1712    V /= Scale;
1713    return V == (V & ((1LL << 5) - 1));
1714  }
1715
1716  if (V < 0)
1717    V = - V;
1718  switch (VT.getSimpleVT()) {
1719  default: return false;
1720  case MVT::i1:
1721  case MVT::i8:
1722  case MVT::i32:
1723    // +- imm12
1724    return V == (V & ((1LL << 12) - 1));
1725  case MVT::i16:
1726    // +- imm8
1727    return V == (V & ((1LL << 8) - 1));
1728  case MVT::f32:
1729  case MVT::f64:
1730    if (!Subtarget->hasVFP2())
1731      return false;
1732    if ((V & 3) != 0)
1733      return false;
1734    V >>= 2;
1735    return V == (V & ((1LL << 8) - 1));
1736  }
1737}
1738
1739/// isLegalAddressingMode - Return true if the addressing mode represented
1740/// by AM is legal for this target, for a load/store of the specified type.
1741bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1742                                              const Type *Ty) const {
1743  if (!isLegalAddressImmediate(AM.BaseOffs, getValueType(Ty, true), Subtarget))
1744    return false;
1745
1746  // Can never fold addr of global into load/store.
1747  if (AM.BaseGV)
1748    return false;
1749
1750  switch (AM.Scale) {
1751  case 0:  // no scale reg, must be "r+i" or "r", or "i".
1752    break;
1753  case 1:
1754    if (Subtarget->isThumb())
1755      return false;
1756    // FALL THROUGH.
1757  default:
1758    // ARM doesn't support any R+R*scale+imm addr modes.
1759    if (AM.BaseOffs)
1760      return false;
1761
1762    int Scale = AM.Scale;
1763    switch (getValueType(Ty).getSimpleVT()) {
1764    default: return false;
1765    case MVT::i1:
1766    case MVT::i8:
1767    case MVT::i32:
1768    case MVT::i64:
1769      // This assumes i64 is legalized to a pair of i32. If not (i.e.
1770      // ldrd / strd are used, then its address mode is same as i16.
1771      // r + r
1772      if (Scale < 0) Scale = -Scale;
1773      if (Scale == 1)
1774        return true;
1775      // r + r << imm
1776      return isPowerOf2_32(Scale & ~1);
1777    case MVT::i16:
1778      // r + r
1779      if (((unsigned)AM.HasBaseReg + Scale) <= 2)
1780        return true;
1781      return false;
1782
1783    case MVT::isVoid:
1784      // Note, we allow "void" uses (basically, uses that aren't loads or
1785      // stores), because arm allows folding a scale into many arithmetic
1786      // operations.  This should be made more precise and revisited later.
1787
1788      // Allow r << imm, but the imm has to be a multiple of two.
1789      if (AM.Scale & 1) return false;
1790      return isPowerOf2_32(AM.Scale);
1791    }
1792    break;
1793  }
1794  return true;
1795}
1796
1797static bool getIndexedAddressParts(SDNode *Ptr, MVT VT,
1798                                   bool isSEXTLoad, SDValue &Base,
1799                                   SDValue &Offset, bool &isInc,
1800                                   SelectionDAG &DAG) {
1801  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
1802    return false;
1803
1804  if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
1805    // AddressingMode 3
1806    Base = Ptr->getOperand(0);
1807    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1808      int RHSC = (int)RHS->getZExtValue();
1809      if (RHSC < 0 && RHSC > -256) {
1810        isInc = false;
1811        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1812        return true;
1813      }
1814    }
1815    isInc = (Ptr->getOpcode() == ISD::ADD);
1816    Offset = Ptr->getOperand(1);
1817    return true;
1818  } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
1819    // AddressingMode 2
1820    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1821      int RHSC = (int)RHS->getZExtValue();
1822      if (RHSC < 0 && RHSC > -0x1000) {
1823        isInc = false;
1824        Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1825        Base = Ptr->getOperand(0);
1826        return true;
1827      }
1828    }
1829
1830    if (Ptr->getOpcode() == ISD::ADD) {
1831      isInc = true;
1832      ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
1833      if (ShOpcVal != ARM_AM::no_shift) {
1834        Base = Ptr->getOperand(1);
1835        Offset = Ptr->getOperand(0);
1836      } else {
1837        Base = Ptr->getOperand(0);
1838        Offset = Ptr->getOperand(1);
1839      }
1840      return true;
1841    }
1842
1843    isInc = (Ptr->getOpcode() == ISD::ADD);
1844    Base = Ptr->getOperand(0);
1845    Offset = Ptr->getOperand(1);
1846    return true;
1847  }
1848
1849  // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
1850  return false;
1851}
1852
1853/// getPreIndexedAddressParts - returns true by value, base pointer and
1854/// offset pointer and addressing mode by reference if the node's address
1855/// can be legally represented as pre-indexed load / store address.
1856bool
1857ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1858                                             SDValue &Offset,
1859                                             ISD::MemIndexedMode &AM,
1860                                             SelectionDAG &DAG) const {
1861  if (Subtarget->isThumb())
1862    return false;
1863
1864  MVT VT;
1865  SDValue Ptr;
1866  bool isSEXTLoad = false;
1867  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1868    Ptr = LD->getBasePtr();
1869    VT  = LD->getMemoryVT();
1870    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
1871  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1872    Ptr = ST->getBasePtr();
1873    VT  = ST->getMemoryVT();
1874  } else
1875    return false;
1876
1877  bool isInc;
1878  bool isLegal = getIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, Offset,
1879                                        isInc, DAG);
1880  if (isLegal) {
1881    AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
1882    return true;
1883  }
1884  return false;
1885}
1886
1887/// getPostIndexedAddressParts - returns true by value, base pointer and
1888/// offset pointer and addressing mode by reference if this node can be
1889/// combined with a load / store to form a post-indexed load / store.
1890bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1891                                                   SDValue &Base,
1892                                                   SDValue &Offset,
1893                                                   ISD::MemIndexedMode &AM,
1894                                                   SelectionDAG &DAG) const {
1895  if (Subtarget->isThumb())
1896    return false;
1897
1898  MVT VT;
1899  SDValue Ptr;
1900  bool isSEXTLoad = false;
1901  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1902    VT  = LD->getMemoryVT();
1903    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
1904  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1905    VT  = ST->getMemoryVT();
1906  } else
1907    return false;
1908
1909  bool isInc;
1910  bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
1911                                        isInc, DAG);
1912  if (isLegal) {
1913    AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
1914    return true;
1915  }
1916  return false;
1917}
1918
1919void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1920                                                       const APInt &Mask,
1921                                                       APInt &KnownZero,
1922                                                       APInt &KnownOne,
1923                                                       const SelectionDAG &DAG,
1924                                                       unsigned Depth) const {
1925  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1926  switch (Op.getOpcode()) {
1927  default: break;
1928  case ARMISD::CMOV: {
1929    // Bits are known zero/one if known on the LHS and RHS.
1930    DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1931    if (KnownZero == 0 && KnownOne == 0) return;
1932
1933    APInt KnownZeroRHS, KnownOneRHS;
1934    DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
1935                          KnownZeroRHS, KnownOneRHS, Depth+1);
1936    KnownZero &= KnownZeroRHS;
1937    KnownOne  &= KnownOneRHS;
1938    return;
1939  }
1940  }
1941}
1942
1943//===----------------------------------------------------------------------===//
1944//                           ARM Inline Assembly Support
1945//===----------------------------------------------------------------------===//
1946
1947/// getConstraintType - Given a constraint letter, return the type of
1948/// constraint it is for this target.
1949ARMTargetLowering::ConstraintType
1950ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
1951  if (Constraint.size() == 1) {
1952    switch (Constraint[0]) {
1953    default:  break;
1954    case 'l': return C_RegisterClass;
1955    case 'w': return C_RegisterClass;
1956    }
1957  }
1958  return TargetLowering::getConstraintType(Constraint);
1959}
1960
1961std::pair<unsigned, const TargetRegisterClass*>
1962ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1963                                                MVT VT) const {
1964  if (Constraint.size() == 1) {
1965    // GCC RS6000 Constraint Letters
1966    switch (Constraint[0]) {
1967    case 'l':
1968    // FIXME: in thumb mode, 'l' is only low-regs.
1969    // FALL THROUGH.
1970    case 'r':
1971      return std::make_pair(0U, ARM::GPRRegisterClass);
1972    case 'w':
1973      if (VT == MVT::f32)
1974        return std::make_pair(0U, ARM::SPRRegisterClass);
1975      if (VT == MVT::f64)
1976        return std::make_pair(0U, ARM::DPRRegisterClass);
1977      break;
1978    }
1979  }
1980  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1981}
1982
1983std::vector<unsigned> ARMTargetLowering::
1984getRegClassForInlineAsmConstraint(const std::string &Constraint,
1985                                  MVT VT) const {
1986  if (Constraint.size() != 1)
1987    return std::vector<unsigned>();
1988
1989  switch (Constraint[0]) {      // GCC ARM Constraint Letters
1990  default: break;
1991  case 'l':
1992  case 'r':
1993    return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
1994                                 ARM::R4, ARM::R5, ARM::R6, ARM::R7,
1995                                 ARM::R8, ARM::R9, ARM::R10, ARM::R11,
1996                                 ARM::R12, ARM::LR, 0);
1997  case 'w':
1998    if (VT == MVT::f32)
1999      return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
2000                                   ARM::S4, ARM::S5, ARM::S6, ARM::S7,
2001                                   ARM::S8, ARM::S9, ARM::S10, ARM::S11,
2002                                   ARM::S12,ARM::S13,ARM::S14,ARM::S15,
2003                                   ARM::S16,ARM::S17,ARM::S18,ARM::S19,
2004                                   ARM::S20,ARM::S21,ARM::S22,ARM::S23,
2005                                   ARM::S24,ARM::S25,ARM::S26,ARM::S27,
2006                                   ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
2007    if (VT == MVT::f64)
2008      return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
2009                                   ARM::D4, ARM::D5, ARM::D6, ARM::D7,
2010                                   ARM::D8, ARM::D9, ARM::D10,ARM::D11,
2011                                   ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
2012      break;
2013  }
2014
2015  return std::vector<unsigned>();
2016}
2017