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