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