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