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