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