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