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