Increase ISD::ParamFlags to 64 bits. Increase the ByValSize
[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/Instruction.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/ADT/VectorExtras.h"
36 #include "llvm/Support/MathExtras.h"
37 using namespace llvm;
38
39 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
40     : TargetLowering(TM), ARMPCLabelIndex(0) {
41   Subtarget = &TM.getSubtarget<ARMSubtarget>();
42
43   if (Subtarget->isTargetDarwin()) {
44     // Don't have these.
45     setLibcallName(RTLIB::UINTTOFP_I64_F32, NULL);
46     setLibcallName(RTLIB::UINTTOFP_I64_F64, NULL);
47
48     // Uses VFP for Thumb libfuncs if available.
49     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
50       // Single-precision floating-point arithmetic.
51       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
52       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
53       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
54       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
55
56       // Double-precision floating-point arithmetic.
57       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
58       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
59       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
60       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
61
62       // Single-precision comparisons.
63       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
64       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
65       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
66       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
67       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
68       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
69       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
70       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
71
72       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
73       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
74       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
75       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
76       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
77       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
78       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
79       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
80
81       // Double-precision comparisons.
82       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
83       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
84       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
85       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
86       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
87       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
88       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
89       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
90
91       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
92       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
93       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
94       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
95       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
96       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
97       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
98       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
99
100       // Floating-point to integer conversions.
101       // i64 conversions are done via library routines even when generating VFP
102       // instructions, so use the same ones.
103       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
104       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
105       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
106       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
107
108       // Conversions between floating types.
109       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
110       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
111
112       // Integer to floating-point conversions.
113       // i64 conversions are done via library routines even when generating VFP
114       // instructions, so use the same ones.
115       // FIXME: There appears to be some naming inconsistency in ARM libgcc: e.g.
116       // __floatunsidf vs. __floatunssidfvfp.
117       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
118       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
119       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
120       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
121     }
122   }
123
124   addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
125   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
126     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
127     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
128     
129     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
130   }
131   computeRegisterProperties();
132
133   // ARM does not have f32 extending load.
134   setLoadXAction(ISD::EXTLOAD, MVT::f32, Expand);
135
136   // ARM does not have i1 sign extending load.
137   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
138
139   // ARM supports all 4 flavors of integer indexed load / store.
140   for (unsigned im = (unsigned)ISD::PRE_INC;
141        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
142     setIndexedLoadAction(im,  MVT::i1,  Legal);
143     setIndexedLoadAction(im,  MVT::i8,  Legal);
144     setIndexedLoadAction(im,  MVT::i16, Legal);
145     setIndexedLoadAction(im,  MVT::i32, Legal);
146     setIndexedStoreAction(im, MVT::i1,  Legal);
147     setIndexedStoreAction(im, MVT::i8,  Legal);
148     setIndexedStoreAction(im, MVT::i16, Legal);
149     setIndexedStoreAction(im, MVT::i32, Legal);
150   }
151
152   // i64 operation support.
153   if (Subtarget->isThumb()) {
154     setOperationAction(ISD::MUL,     MVT::i64, Expand);
155     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
156     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
157     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
158     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
159   } else {
160     setOperationAction(ISD::MUL,     MVT::i64, Expand);
161     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
162     if (!Subtarget->hasV6Ops())
163       setOperationAction(ISD::MULHS, MVT::i32, Expand);
164   }
165   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
166   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
167   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
168   setOperationAction(ISD::SRL,       MVT::i64, Custom);
169   setOperationAction(ISD::SRA,       MVT::i64, Custom);
170
171   // ARM does not have ROTL.
172   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
173   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
174   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
175   if (!Subtarget->hasV5TOps() || Subtarget->isThumb())
176     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
177
178   // Only ARMv6 has BSWAP.
179   if (!Subtarget->hasV6Ops())
180     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
181
182   // These are expanded into libcalls.
183   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
184   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
185   setOperationAction(ISD::SREM,  MVT::i32, Expand);
186   setOperationAction(ISD::UREM,  MVT::i32, Expand);
187   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
188   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
189   
190   // Support label based line numbers.
191   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
192   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
193
194   setOperationAction(ISD::RET,           MVT::Other, Custom);
195   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
196   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
197   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
198   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
199
200   // Expand mem operations genericly.
201   setOperationAction(ISD::MEMSET          , MVT::Other, Expand);
202   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
203   setOperationAction(ISD::MEMMOVE         , MVT::Other, Expand);
204
205   // Use the default implementation.
206   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
207   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
208   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
209   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
210   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
211   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
212   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
213   setOperationAction(ISD::MEMBARRIER        , MVT::Other, Expand);
214   setOperationAction(ISD::PREFETCH          , MVT::Other, Expand);
215
216   if (!Subtarget->hasV6Ops()) {
217     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
218     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
219   }
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
221
222   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb())
223     // Turn f64->i64 into FMRRD iff target supports vfp2.
224     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
225
226   // We want to custom lower some of our intrinsics.
227   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
228
229   setOperationAction(ISD::SETCC    , MVT::i32, Expand);
230   setOperationAction(ISD::SETCC    , MVT::f32, Expand);
231   setOperationAction(ISD::SETCC    , MVT::f64, Expand);
232   setOperationAction(ISD::SELECT   , MVT::i32, Expand);
233   setOperationAction(ISD::SELECT   , MVT::f32, Expand);
234   setOperationAction(ISD::SELECT   , MVT::f64, Expand);
235   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
236   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
237   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
238
239   setOperationAction(ISD::BRCOND   , MVT::Other, Expand);
240   setOperationAction(ISD::BR_CC    , MVT::i32,   Custom);
241   setOperationAction(ISD::BR_CC    , MVT::f32,   Custom);
242   setOperationAction(ISD::BR_CC    , MVT::f64,   Custom);
243   setOperationAction(ISD::BR_JT    , MVT::Other, Custom);
244
245   // We don't support sin/cos/fmod/copysign/pow
246   setOperationAction(ISD::FSIN     , MVT::f64, Expand);
247   setOperationAction(ISD::FSIN     , MVT::f32, Expand);
248   setOperationAction(ISD::FCOS     , MVT::f32, Expand);
249   setOperationAction(ISD::FCOS     , MVT::f64, Expand);
250   setOperationAction(ISD::FREM     , MVT::f64, Expand);
251   setOperationAction(ISD::FREM     , MVT::f32, Expand);
252   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
253   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
254   setOperationAction(ISD::FPOW     , MVT::f64, Expand);
255   setOperationAction(ISD::FPOW     , MVT::f32, Expand);
256   
257   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
258   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
259   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
260   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
261   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
262
263   // We have target-specific dag combine patterns for the following nodes:
264   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
265   
266   setStackPointerRegisterToSaveRestore(ARM::SP);
267   setSchedulingPreference(SchedulingForRegPressure);
268   setIfCvtBlockSizeLimit(Subtarget->isThumb() ? 0 : 10);
269   setIfCvtDupBlockSizeLimit(Subtarget->isThumb() ? 0 : 2);
270
271   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
272 }
273
274
275 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
276   switch (Opcode) {
277   default: return 0;
278   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
279   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
280   case ARMISD::CALL:          return "ARMISD::CALL";
281   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
282   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
283   case ARMISD::tCALL:         return "ARMISD::tCALL";
284   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
285   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
286   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
287   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
288   case ARMISD::CMP:           return "ARMISD::CMP";
289   case ARMISD::CMPNZ:         return "ARMISD::CMPNZ";
290   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
291   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
292   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
293   case ARMISD::CMOV:          return "ARMISD::CMOV";
294   case ARMISD::CNEG:          return "ARMISD::CNEG";
295     
296   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
297   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
298   case ARMISD::SITOF:         return "ARMISD::SITOF";
299   case ARMISD::UITOF:         return "ARMISD::UITOF";
300
301   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
302   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
303   case ARMISD::RRX:           return "ARMISD::RRX";
304       
305   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
306   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
307
308   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
309   }
310 }
311
312 //===----------------------------------------------------------------------===//
313 // Lowering Code
314 //===----------------------------------------------------------------------===//
315
316
317 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
318 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
319   switch (CC) {
320   default: assert(0 && "Unknown condition code!");
321   case ISD::SETNE:  return ARMCC::NE;
322   case ISD::SETEQ:  return ARMCC::EQ;
323   case ISD::SETGT:  return ARMCC::GT;
324   case ISD::SETGE:  return ARMCC::GE;
325   case ISD::SETLT:  return ARMCC::LT;
326   case ISD::SETLE:  return ARMCC::LE;
327   case ISD::SETUGT: return ARMCC::HI;
328   case ISD::SETUGE: return ARMCC::HS;
329   case ISD::SETULT: return ARMCC::LO;
330   case ISD::SETULE: return ARMCC::LS;
331   }
332 }
333
334 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
335 /// returns true if the operands should be inverted to form the proper
336 /// comparison.
337 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
338                         ARMCC::CondCodes &CondCode2) {
339   bool Invert = false;
340   CondCode2 = ARMCC::AL;
341   switch (CC) {
342   default: assert(0 && "Unknown FP condition!");
343   case ISD::SETEQ:
344   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
345   case ISD::SETGT:
346   case ISD::SETOGT: CondCode = ARMCC::GT; break;
347   case ISD::SETGE:
348   case ISD::SETOGE: CondCode = ARMCC::GE; break;
349   case ISD::SETOLT: CondCode = ARMCC::MI; break;
350   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
351   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
352   case ISD::SETO:   CondCode = ARMCC::VC; break;
353   case ISD::SETUO:  CondCode = ARMCC::VS; break;
354   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
355   case ISD::SETUGT: CondCode = ARMCC::HI; break;
356   case ISD::SETUGE: CondCode = ARMCC::PL; break;
357   case ISD::SETLT:
358   case ISD::SETULT: CondCode = ARMCC::LT; break;
359   case ISD::SETLE:
360   case ISD::SETULE: CondCode = ARMCC::LE; break;
361   case ISD::SETNE:
362   case ISD::SETUNE: CondCode = ARMCC::NE; break;
363   }
364   return Invert;
365 }
366
367 static void
368 HowToPassArgument(MVT::ValueType ObjectVT, unsigned NumGPRs,
369                   unsigned StackOffset, unsigned &NeededGPRs,
370                   unsigned &NeededStackSize, unsigned &GPRPad,
371                   unsigned &StackPad, ISD::ParamFlags::ParamFlagsTy Flags) {
372   NeededStackSize = 0;
373   NeededGPRs = 0;
374   StackPad = 0;
375   GPRPad = 0;
376   unsigned align = ((Flags & ISD::ParamFlags::OrigAlignment) 
377                         >> ISD::ParamFlags::OrigAlignmentOffs);
378   GPRPad = NumGPRs % ((align + 3)/4);
379   StackPad = StackOffset % align;
380   unsigned firstGPR = NumGPRs + GPRPad;
381   switch (ObjectVT) {
382   default: assert(0 && "Unhandled argument type!");
383   case MVT::i32:
384   case MVT::f32:
385     if (firstGPR < 4)
386       NeededGPRs = 1;
387     else
388       NeededStackSize = 4;
389     break;
390   case MVT::i64:
391   case MVT::f64:
392     if (firstGPR < 3)
393       NeededGPRs = 2;
394     else if (firstGPR == 3) {
395       NeededGPRs = 1;
396       NeededStackSize = 4;
397     } else
398       NeededStackSize = 8;
399   }
400 }
401
402 /// LowerCALL - Lowering a ISD::CALL node into a callseq_start <-
403 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
404 /// nodes.
405 SDOperand ARMTargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
406   MVT::ValueType RetVT= Op.Val->getValueType(0);
407   SDOperand Chain    = Op.getOperand(0);
408   unsigned CallConv  = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
409   assert((CallConv == CallingConv::C ||
410           CallConv == CallingConv::Fast) && "unknown calling convention");
411   SDOperand Callee   = Op.getOperand(4);
412   unsigned NumOps    = (Op.getNumOperands() - 5) / 2;
413   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
414   unsigned NumGPRs = 0;     // GPRs used for parameter passing.
415
416   // Count how many bytes are to be pushed on the stack.
417   unsigned NumBytes = 0;
418
419   // Add up all the space actually used.
420   for (unsigned i = 0; i < NumOps; ++i) {
421     unsigned ObjSize;
422     unsigned ObjGPRs;
423     unsigned StackPad;
424     unsigned GPRPad;
425     MVT::ValueType ObjectVT = Op.getOperand(5+2*i).getValueType();
426     ISD::ParamFlags::ParamFlagsTy Flags = Op.getConstantOperandVal(5+2*i+1);
427     HowToPassArgument(ObjectVT, NumGPRs, NumBytes, ObjGPRs, ObjSize,
428                       GPRPad, StackPad, Flags);
429     NumBytes += ObjSize + StackPad;
430     NumGPRs += ObjGPRs + GPRPad;
431   }
432
433   // Adjust the stack pointer for the new arguments...
434   // These operations are automatically eliminated by the prolog/epilog pass
435   Chain = DAG.getCALLSEQ_START(Chain,
436                                DAG.getConstant(NumBytes, MVT::i32));
437
438   SDOperand StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
439
440   static const unsigned GPRArgRegs[] = {
441     ARM::R0, ARM::R1, ARM::R2, ARM::R3
442   };
443
444   NumGPRs = 0;
445   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
446   std::vector<SDOperand> MemOpChains;
447   for (unsigned i = 0; i != NumOps; ++i) {
448     SDOperand Arg = Op.getOperand(5+2*i);
449     ISD::ParamFlags::ParamFlagsTy Flags = Op.getConstantOperandVal(5+2*i+1);
450     MVT::ValueType ArgVT = Arg.getValueType();
451
452     unsigned ObjSize;
453     unsigned ObjGPRs;
454     unsigned GPRPad;
455     unsigned StackPad;
456     HowToPassArgument(ArgVT, NumGPRs, ArgOffset, ObjGPRs,
457                       ObjSize, GPRPad, StackPad, Flags);
458     NumGPRs += GPRPad;
459     ArgOffset += StackPad;
460     if (ObjGPRs > 0) {
461       switch (ArgVT) {
462       default: assert(0 && "Unexpected ValueType for argument!");
463       case MVT::i32:
464         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Arg));
465         break;
466       case MVT::f32:
467         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs],
468                                  DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Arg)));
469         break;
470       case MVT::i64: {
471         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Arg,
472                                    DAG.getConstant(0, getPointerTy()));
473         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Arg,
474                                    DAG.getConstant(1, getPointerTy()));
475         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Lo));
476         if (ObjGPRs == 2)
477           RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs+1], Hi));
478         else {
479           SDOperand PtrOff= DAG.getConstant(ArgOffset, StackPtr.getValueType());
480           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
481           MemOpChains.push_back(DAG.getStore(Chain, Hi, PtrOff, NULL, 0));
482         }
483         break;
484       }
485       case MVT::f64: {
486         SDOperand Cvt = DAG.getNode(ARMISD::FMRRD,
487                                     DAG.getVTList(MVT::i32, MVT::i32),
488                                     &Arg, 1);
489         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Cvt));
490         if (ObjGPRs == 2)
491           RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs+1],
492                                               Cvt.getValue(1)));
493         else {
494           SDOperand PtrOff= DAG.getConstant(ArgOffset, StackPtr.getValueType());
495           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
496           MemOpChains.push_back(DAG.getStore(Chain, Cvt.getValue(1), PtrOff,
497                                              NULL, 0));
498         }
499         break;
500       }
501       }
502     } else {
503       assert(ObjSize != 0);
504       SDOperand PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
505       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
506       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
507     }
508
509     NumGPRs += ObjGPRs;
510     ArgOffset += ObjSize;
511   }
512
513   if (!MemOpChains.empty())
514     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
515                         &MemOpChains[0], MemOpChains.size());
516
517   // Build a sequence of copy-to-reg nodes chained together with token chain
518   // and flag operands which copy the outgoing args into the appropriate regs.
519   SDOperand InFlag;
520   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
521     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
522                              InFlag);
523     InFlag = Chain.getValue(1);
524   }
525
526   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
527   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
528   // node so that legalize doesn't hack it.
529   bool isDirect = false;
530   bool isARMFunc = false;
531   bool isLocalARMFunc = false;
532   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
533     GlobalValue *GV = G->getGlobal();
534     isDirect = true;
535     bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
536                   GV->hasLinkOnceLinkage());
537     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
538                    getTargetMachine().getRelocationModel() != Reloc::Static;
539     isARMFunc = !Subtarget->isThumb() || isStub;
540     // ARM call to a local ARM function is predicable.
541     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
542     // tBX takes a register source operand.
543     if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
544       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
545                                                            ARMCP::CPStub, 4);
546       SDOperand CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 2);
547       CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
548       Callee = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), CPAddr, NULL, 0); 
549       SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
550       Callee = DAG.getNode(ARMISD::PIC_ADD, getPointerTy(), Callee, PICLabel);
551    } else
552       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
553   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
554     isDirect = true;
555     bool isStub = Subtarget->isTargetDarwin() &&
556                   getTargetMachine().getRelocationModel() != Reloc::Static;
557     isARMFunc = !Subtarget->isThumb() || isStub;
558     // tBX takes a register source operand.
559     const char *Sym = S->getSymbol();
560     if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
561       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(Sym, ARMPCLabelIndex,
562                                                            ARMCP::CPStub, 4);
563       SDOperand CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 2);
564       CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
565       Callee = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), CPAddr, NULL, 0); 
566       SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
567       Callee = DAG.getNode(ARMISD::PIC_ADD, getPointerTy(), Callee, PICLabel);
568     } else
569       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
570   }
571
572   // FIXME: handle tail calls differently.
573   unsigned CallOpc;
574   if (Subtarget->isThumb()) {
575     if (!Subtarget->hasV5TOps() && (!isDirect || isARMFunc))
576       CallOpc = ARMISD::CALL_NOLINK;
577     else
578       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
579   } else {
580     CallOpc = (isDirect || Subtarget->hasV5TOps())
581       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
582       : ARMISD::CALL_NOLINK;
583   }
584   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb()) {
585     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
586     Chain = DAG.getCopyToReg(Chain, ARM::LR,
587                              DAG.getNode(ISD::UNDEF, MVT::i32), InFlag);
588     InFlag = Chain.getValue(1);
589   }
590
591   std::vector<MVT::ValueType> NodeTys;
592   NodeTys.push_back(MVT::Other);   // Returns a chain
593   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
594
595   std::vector<SDOperand> Ops;
596   Ops.push_back(Chain);
597   Ops.push_back(Callee);
598
599   // Add argument registers to the end of the list so that they are known live
600   // into the call.
601   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
602     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
603                                   RegsToPass[i].second.getValueType()));
604
605   if (InFlag.Val)
606     Ops.push_back(InFlag);
607   Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
608   InFlag = Chain.getValue(1);
609
610   Chain = DAG.getCALLSEQ_END(Chain,
611                              DAG.getConstant(NumBytes, MVT::i32),
612                              DAG.getConstant(0, MVT::i32),
613                              InFlag);
614   if (RetVT != MVT::Other)
615     InFlag = Chain.getValue(1);
616
617   std::vector<SDOperand> ResultVals;
618   NodeTys.clear();
619
620   // If the call has results, copy the values out of the ret val registers.
621   switch (RetVT) {
622   default: assert(0 && "Unexpected ret value!");
623   case MVT::Other:
624     break;
625   case MVT::i32:
626     Chain = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag).getValue(1);
627     ResultVals.push_back(Chain.getValue(0));
628     if (Op.Val->getValueType(1) == MVT::i32) {
629       // Returns a i64 value.
630       Chain = DAG.getCopyFromReg(Chain, ARM::R1, MVT::i32,
631                                  Chain.getValue(2)).getValue(1);
632       ResultVals.push_back(Chain.getValue(0));
633       NodeTys.push_back(MVT::i32);
634     }
635     NodeTys.push_back(MVT::i32);
636     break;
637   case MVT::f32:
638     Chain = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag).getValue(1);
639     ResultVals.push_back(DAG.getNode(ISD::BIT_CONVERT, MVT::f32,
640                                      Chain.getValue(0)));
641     NodeTys.push_back(MVT::f32);
642     break;
643   case MVT::f64: {
644     SDOperand Lo = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag);
645     SDOperand Hi = DAG.getCopyFromReg(Lo, ARM::R1, MVT::i32, Lo.getValue(2));
646     ResultVals.push_back(DAG.getNode(ARMISD::FMDRR, MVT::f64, Lo, Hi));
647     NodeTys.push_back(MVT::f64);
648     break;
649   }
650   }
651
652   NodeTys.push_back(MVT::Other);
653
654   if (ResultVals.empty())
655     return Chain;
656
657   ResultVals.push_back(Chain);
658   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, &ResultVals[0],
659                               ResultVals.size());
660   return Res.getValue(Op.ResNo);
661 }
662
663 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
664   SDOperand Copy;
665   SDOperand Chain = Op.getOperand(0);
666   switch(Op.getNumOperands()) {
667   default:
668     assert(0 && "Do not know how to return this many arguments!");
669     abort();
670   case 1: {
671     SDOperand LR = DAG.getRegister(ARM::LR, MVT::i32);
672     return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Chain);
673   }
674   case 3:
675     Op = Op.getOperand(1);
676     if (Op.getValueType() == MVT::f32) {
677       Op = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
678     } else if (Op.getValueType() == MVT::f64) {
679       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
680       // available.
681       Op = DAG.getNode(ARMISD::FMRRD, DAG.getVTList(MVT::i32, MVT::i32), &Op,1);
682       SDOperand Sign = DAG.getConstant(0, MVT::i32);
683       return DAG.getNode(ISD::RET, MVT::Other, Chain, Op, Sign, 
684                          Op.getValue(1), Sign);
685     }
686     Copy = DAG.getCopyToReg(Chain, ARM::R0, Op, SDOperand());
687     if (DAG.getMachineFunction().getRegInfo().liveout_empty())
688       DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
689     break;
690   case 5:
691     Copy = DAG.getCopyToReg(Chain, ARM::R1, Op.getOperand(3), SDOperand());
692     Copy = DAG.getCopyToReg(Copy, ARM::R0, Op.getOperand(1), Copy.getValue(1));
693     // If we haven't noted the R0+R1 are live out, do so now.
694     if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
695       DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
696       DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R1);
697     }
698     break;
699   }
700
701   //We must use RET_FLAG instead of BRIND because BRIND doesn't have a flag
702   return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
703 }
704
705 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 
706 // their target countpart wrapped in the ARMISD::Wrapper node. Suppose N is
707 // one of the above mentioned nodes. It has to be wrapped because otherwise
708 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
709 // be used to form addressing mode. These wrapped nodes will be selected
710 // into MOVi.
711 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
712   MVT::ValueType PtrVT = Op.getValueType();
713   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
714   SDOperand Res;
715   if (CP->isMachineConstantPoolEntry())
716     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
717                                     CP->getAlignment());
718   else
719     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
720                                     CP->getAlignment());
721   return DAG.getNode(ARMISD::Wrapper, MVT::i32, Res);
722 }
723
724 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
725 SDOperand
726 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
727                                                  SelectionDAG &DAG) {
728   MVT::ValueType PtrVT = getPointerTy();
729   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
730   ARMConstantPoolValue *CPV =
731     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
732                              PCAdj, "tlsgd", true);
733   SDOperand Argument = DAG.getTargetConstantPool(CPV, PtrVT, 2);
734   Argument = DAG.getNode(ARMISD::Wrapper, MVT::i32, Argument);
735   Argument = DAG.getLoad(PtrVT, DAG.getEntryNode(), Argument, NULL, 0);
736   SDOperand Chain = Argument.getValue(1);
737
738   SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
739   Argument = DAG.getNode(ARMISD::PIC_ADD, PtrVT, Argument, PICLabel);
740
741   // call __tls_get_addr.
742   ArgListTy Args;
743   ArgListEntry Entry;
744   Entry.Node = Argument;
745   Entry.Ty = (const Type *) Type::Int32Ty;
746   Args.push_back(Entry);
747   std::pair<SDOperand, SDOperand> CallResult =
748     LowerCallTo(Chain, (const Type *) Type::Int32Ty, false, false, false,
749                 CallingConv::C, false,
750                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG);
751   return CallResult.first;
752 }
753
754 // Lower ISD::GlobalTLSAddress using the "initial exec" or
755 // "local exec" model.
756 SDOperand
757 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
758                                             SelectionDAG &DAG) {
759   GlobalValue *GV = GA->getGlobal();
760   SDOperand Offset;
761   SDOperand Chain = DAG.getEntryNode();
762   MVT::ValueType PtrVT = getPointerTy();
763   // Get the Thread Pointer
764   SDOperand ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, PtrVT);
765
766   if (GV->isDeclaration()){
767     // initial exec model
768     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
769     ARMConstantPoolValue *CPV =
770       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
771                                PCAdj, "gottpoff", true);
772     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 2);
773     Offset = DAG.getNode(ARMISD::Wrapper, MVT::i32, Offset);
774     Offset = DAG.getLoad(PtrVT, Chain, Offset, NULL, 0);
775     Chain = Offset.getValue(1);
776
777     SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
778     Offset = DAG.getNode(ARMISD::PIC_ADD, PtrVT, Offset, PICLabel);
779
780     Offset = DAG.getLoad(PtrVT, Chain, Offset, NULL, 0);
781   } else {
782     // local exec model
783     ARMConstantPoolValue *CPV =
784       new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
785     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 2);
786     Offset = DAG.getNode(ARMISD::Wrapper, MVT::i32, Offset);
787     Offset = DAG.getLoad(PtrVT, Chain, Offset, NULL, 0);
788   }
789
790   // The address of the thread local variable is the add of the thread
791   // pointer with the offset of the variable.
792   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
793 }
794
795 SDOperand
796 ARMTargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
797   // TODO: implement the "local dynamic" model
798   assert(Subtarget->isTargetELF() &&
799          "TLS not implemented for non-ELF targets");
800   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
801   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
802   // otherwise use the "Local Exec" TLS Model
803   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
804     return LowerToTLSGeneralDynamicModel(GA, DAG);
805   else
806     return LowerToTLSExecModels(GA, DAG);
807 }
808
809 SDOperand ARMTargetLowering::LowerGlobalAddressELF(SDOperand Op,
810                                                    SelectionDAG &DAG) {
811   MVT::ValueType PtrVT = getPointerTy();
812   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
813   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
814   if (RelocM == Reloc::PIC_) {
815     bool UseGOTOFF = GV->hasInternalLinkage() || GV->hasHiddenVisibility();
816     ARMConstantPoolValue *CPV =
817       new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
818     SDOperand CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 2);
819     CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
820     SDOperand Result = DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
821     SDOperand Chain = Result.getValue(1);
822     SDOperand GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PtrVT);
823     Result = DAG.getNode(ISD::ADD, PtrVT, Result, GOT);
824     if (!UseGOTOFF)
825       Result = DAG.getLoad(PtrVT, Chain, Result, NULL, 0);
826     return Result;
827   } else {
828     SDOperand CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 2);
829     CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
830     return DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
831   }
832 }
833
834 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
835 /// even in non-static mode.
836 static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
837   return RelocM != Reloc::Static &&
838     (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
839      (GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode()));
840 }
841
842 SDOperand ARMTargetLowering::LowerGlobalAddressDarwin(SDOperand Op,
843                                                       SelectionDAG &DAG) {
844   MVT::ValueType PtrVT = getPointerTy();
845   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
846   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
847   bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
848   SDOperand CPAddr;
849   if (RelocM == Reloc::Static)
850     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 2);
851   else {
852     unsigned PCAdj = (RelocM != Reloc::PIC_)
853       ? 0 : (Subtarget->isThumb() ? 4 : 8);
854     ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
855       : ARMCP::CPValue;
856     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
857                                                          Kind, PCAdj);
858     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 2);
859   }
860   CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
861
862   SDOperand Result = DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
863   SDOperand Chain = Result.getValue(1);
864
865   if (RelocM == Reloc::PIC_) {
866     SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
867     Result = DAG.getNode(ARMISD::PIC_ADD, PtrVT, Result, PICLabel);
868   }
869   if (IsIndirect)
870     Result = DAG.getLoad(PtrVT, Chain, Result, NULL, 0);
871
872   return Result;
873 }
874
875 SDOperand ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDOperand Op,
876                                                       SelectionDAG &DAG){
877   assert(Subtarget->isTargetELF() &&
878          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
879   MVT::ValueType PtrVT = getPointerTy();
880   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
881   ARMConstantPoolValue *CPV = new ARMConstantPoolValue("_GLOBAL_OFFSET_TABLE_",
882                                                        ARMPCLabelIndex,
883                                                        ARMCP::CPValue, PCAdj);
884   SDOperand CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 2);
885   CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
886   SDOperand Result = DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
887   SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
888   return DAG.getNode(ARMISD::PIC_ADD, PtrVT, Result, PICLabel);
889 }
890
891 static SDOperand LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
892   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
893   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
894   switch (IntNo) {
895   default: return SDOperand();    // Don't custom lower most intrinsics.
896   case Intrinsic::arm_thread_pointer:
897       return DAG.getNode(ARMISD::THREAD_POINTER, PtrVT);
898   }
899 }
900
901 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
902                               unsigned VarArgsFrameIndex) {
903   // vastart just stores the address of the VarArgsFrameIndex slot into the
904   // memory location argument.
905   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
906   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
907   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
908   return DAG.getStore(Op.getOperand(0), FR, Op.getOperand(1), SV, 0);
909 }
910
911 static SDOperand LowerFORMAL_ARGUMENT(SDOperand Op, SelectionDAG &DAG,
912                                       unsigned ArgNo, unsigned &NumGPRs,
913                                       unsigned &ArgOffset) {
914   MachineFunction &MF = DAG.getMachineFunction();
915   MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
916   SDOperand Root = Op.getOperand(0);
917   std::vector<SDOperand> ArgValues;
918   MachineRegisterInfo &RegInfo = MF.getRegInfo();
919
920   static const unsigned GPRArgRegs[] = {
921     ARM::R0, ARM::R1, ARM::R2, ARM::R3
922   };
923
924   unsigned ObjSize;
925   unsigned ObjGPRs;
926   unsigned GPRPad;
927   unsigned StackPad;
928   ISD::ParamFlags::ParamFlagsTy Flags = Op.getConstantOperandVal(ArgNo + 3);
929   HowToPassArgument(ObjectVT, NumGPRs, ArgOffset, ObjGPRs,
930                     ObjSize, GPRPad, StackPad, Flags);
931   NumGPRs += GPRPad;
932   ArgOffset += StackPad;
933
934   SDOperand ArgValue;
935   if (ObjGPRs == 1) {
936     unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
937     RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
938     ArgValue = DAG.getCopyFromReg(Root, VReg, MVT::i32);
939     if (ObjectVT == MVT::f32)
940       ArgValue = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, ArgValue);
941   } else if (ObjGPRs == 2) {
942     unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
943     RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
944     ArgValue = DAG.getCopyFromReg(Root, VReg, MVT::i32);
945
946     VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
947     RegInfo.addLiveIn(GPRArgRegs[NumGPRs+1], VReg);
948     SDOperand ArgValue2 = DAG.getCopyFromReg(Root, VReg, MVT::i32);
949
950     assert(ObjectVT != MVT::i64 && "i64 should already be lowered");
951     ArgValue = DAG.getNode(ARMISD::FMDRR, MVT::f64, ArgValue, ArgValue2);
952   }
953   NumGPRs += ObjGPRs;
954
955   if (ObjSize) {
956     MachineFrameInfo *MFI = MF.getFrameInfo();
957     int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
958     SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
959     if (ObjGPRs == 0)
960       ArgValue = DAG.getLoad(ObjectVT, Root, FIN, NULL, 0);
961     else {
962       SDOperand ArgValue2 = DAG.getLoad(MVT::i32, Root, FIN, NULL, 0);
963       assert(ObjectVT != MVT::i64 && "i64 should already be lowered");
964       ArgValue = DAG.getNode(ARMISD::FMDRR, MVT::f64, ArgValue, ArgValue2);
965     }
966
967     ArgOffset += ObjSize;   // Move on to the next argument.
968   }
969
970   return ArgValue;
971 }
972
973 SDOperand
974 ARMTargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
975   std::vector<SDOperand> ArgValues;
976   SDOperand Root = Op.getOperand(0);
977   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
978   unsigned NumGPRs = 0;     // GPRs used for parameter passing.
979
980   unsigned NumArgs = Op.Val->getNumValues()-1;
981   for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
982     ArgValues.push_back(LowerFORMAL_ARGUMENT(Op, DAG, ArgNo,
983                                              NumGPRs, ArgOffset));
984
985   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
986   if (isVarArg) {
987     static const unsigned GPRArgRegs[] = {
988       ARM::R0, ARM::R1, ARM::R2, ARM::R3
989     };
990
991     MachineFunction &MF = DAG.getMachineFunction();
992     MachineRegisterInfo &RegInfo = MF.getRegInfo();
993     MachineFrameInfo *MFI = MF.getFrameInfo();
994     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
995     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
996     unsigned VARegSize = (4 - NumGPRs) * 4;
997     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
998     if (VARegSaveSize) {
999       // If this function is vararg, store any remaining integer argument regs
1000       // to their spots on the stack so that they may be loaded by deferencing
1001       // the result of va_next.
1002       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1003       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1004                                                  VARegSaveSize - VARegSize);
1005       SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1006
1007       SmallVector<SDOperand, 4> MemOps;
1008       for (; NumGPRs < 4; ++NumGPRs) {
1009         unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
1010         RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
1011         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
1012         SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1013         MemOps.push_back(Store);
1014         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1015                           DAG.getConstant(4, getPointerTy()));
1016       }
1017       if (!MemOps.empty())
1018         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1019                            &MemOps[0], MemOps.size());
1020     } else
1021       // This will point to the next argument passed via stack.
1022       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1023   }
1024
1025   ArgValues.push_back(Root);
1026
1027   // Return the new list of results.
1028   std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
1029                                     Op.Val->value_end());
1030   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
1031 }
1032
1033 /// isFloatingPointZero - Return true if this is +0.0.
1034 static bool isFloatingPointZero(SDOperand Op) {
1035   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1036     return CFP->getValueAPF().isPosZero();
1037   else if (ISD::isEXTLoad(Op.Val) || ISD::isNON_EXTLoad(Op.Val)) {
1038     // Maybe this has already been legalized into the constant pool?
1039     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1040       SDOperand WrapperOp = Op.getOperand(1).getOperand(0);
1041       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1042         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1043           return CFP->getValueAPF().isPosZero();
1044     }
1045   }
1046   return false;
1047 }
1048
1049 static bool isLegalCmpImmediate(unsigned C, bool isThumb) {
1050   return ( isThumb && (C & ~255U) == 0) ||
1051          (!isThumb && ARM_AM::getSOImmVal(C) != -1);
1052 }
1053
1054 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1055 /// the given operands.
1056 static SDOperand getARMCmp(SDOperand LHS, SDOperand RHS, ISD::CondCode CC,
1057                            SDOperand &ARMCC, SelectionDAG &DAG, bool isThumb) {
1058   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.Val)) {
1059     unsigned C = RHSC->getValue();
1060     if (!isLegalCmpImmediate(C, isThumb)) {
1061       // Constant does not fit, try adjusting it by one?
1062       switch (CC) {
1063       default: break;
1064       case ISD::SETLT:
1065       case ISD::SETGE:
1066         if (isLegalCmpImmediate(C-1, isThumb)) {
1067           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1068           RHS = DAG.getConstant(C-1, MVT::i32);
1069         }
1070         break;
1071       case ISD::SETULT:
1072       case ISD::SETUGE:
1073         if (C > 0 && isLegalCmpImmediate(C-1, isThumb)) {
1074           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1075           RHS = DAG.getConstant(C-1, MVT::i32);
1076         }
1077         break;
1078       case ISD::SETLE:
1079       case ISD::SETGT:
1080         if (isLegalCmpImmediate(C+1, isThumb)) {
1081           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1082           RHS = DAG.getConstant(C+1, MVT::i32);
1083         }
1084         break;
1085       case ISD::SETULE:
1086       case ISD::SETUGT:
1087         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb)) {
1088           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1089           RHS = DAG.getConstant(C+1, MVT::i32);
1090         }
1091         break;
1092       }
1093     }
1094   }
1095
1096   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1097   ARMISD::NodeType CompareType;
1098   switch (CondCode) {
1099   default:
1100     CompareType = ARMISD::CMP;
1101     break;
1102   case ARMCC::EQ:
1103   case ARMCC::NE:
1104   case ARMCC::MI:
1105   case ARMCC::PL:
1106     // Uses only N and Z Flags
1107     CompareType = ARMISD::CMPNZ;
1108     break;
1109   }
1110   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1111   return DAG.getNode(CompareType, MVT::Flag, LHS, RHS);
1112 }
1113
1114 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1115 static SDOperand getVFPCmp(SDOperand LHS, SDOperand RHS, SelectionDAG &DAG) {
1116   SDOperand Cmp;
1117   if (!isFloatingPointZero(RHS))
1118     Cmp = DAG.getNode(ARMISD::CMPFP, MVT::Flag, LHS, RHS);
1119   else
1120     Cmp = DAG.getNode(ARMISD::CMPFPw0, MVT::Flag, LHS);
1121   return DAG.getNode(ARMISD::FMSTAT, MVT::Flag, Cmp);
1122 }
1123
1124 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG,
1125                                 const ARMSubtarget *ST) {
1126   MVT::ValueType VT = Op.getValueType();
1127   SDOperand LHS = Op.getOperand(0);
1128   SDOperand RHS = Op.getOperand(1);
1129   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1130   SDOperand TrueVal = Op.getOperand(2);
1131   SDOperand FalseVal = Op.getOperand(3);
1132
1133   if (LHS.getValueType() == MVT::i32) {
1134     SDOperand ARMCC;
1135     SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1136     SDOperand Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb());
1137     return DAG.getNode(ARMISD::CMOV, VT, FalseVal, TrueVal, ARMCC, CCR, Cmp);
1138   }
1139
1140   ARMCC::CondCodes CondCode, CondCode2;
1141   if (FPCCToARMCC(CC, CondCode, CondCode2))
1142     std::swap(TrueVal, FalseVal);
1143
1144   SDOperand ARMCC = DAG.getConstant(CondCode, MVT::i32);
1145   SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1146   SDOperand Cmp = getVFPCmp(LHS, RHS, DAG);
1147   SDOperand Result = DAG.getNode(ARMISD::CMOV, VT, FalseVal, TrueVal,
1148                                  ARMCC, CCR, Cmp);
1149   if (CondCode2 != ARMCC::AL) {
1150     SDOperand ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1151     // FIXME: Needs another CMP because flag can have but one use.
1152     SDOperand Cmp2 = getVFPCmp(LHS, RHS, DAG);
1153     Result = DAG.getNode(ARMISD::CMOV, VT, Result, TrueVal, ARMCC2, CCR, Cmp2);
1154   }
1155   return Result;
1156 }
1157
1158 static SDOperand LowerBR_CC(SDOperand Op, SelectionDAG &DAG,
1159                             const ARMSubtarget *ST) {
1160   SDOperand  Chain = Op.getOperand(0);
1161   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1162   SDOperand    LHS = Op.getOperand(2);
1163   SDOperand    RHS = Op.getOperand(3);
1164   SDOperand   Dest = Op.getOperand(4);
1165
1166   if (LHS.getValueType() == MVT::i32) {
1167     SDOperand ARMCC;
1168     SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1169     SDOperand Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb());
1170     return DAG.getNode(ARMISD::BRCOND, MVT::Other, Chain, Dest, ARMCC, CCR,Cmp);
1171   }
1172
1173   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1174   ARMCC::CondCodes CondCode, CondCode2;
1175   if (FPCCToARMCC(CC, CondCode, CondCode2))
1176     // Swap the LHS/RHS of the comparison if needed.
1177     std::swap(LHS, RHS);
1178   
1179   SDOperand Cmp = getVFPCmp(LHS, RHS, DAG);
1180   SDOperand ARMCC = DAG.getConstant(CondCode, MVT::i32);
1181   SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1182   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1183   SDOperand Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1184   SDOperand Res = DAG.getNode(ARMISD::BRCOND, VTList, Ops, 5);
1185   if (CondCode2 != ARMCC::AL) {
1186     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1187     SDOperand Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1188     Res = DAG.getNode(ARMISD::BRCOND, VTList, Ops, 5);
1189   }
1190   return Res;
1191 }
1192
1193 SDOperand ARMTargetLowering::LowerBR_JT(SDOperand Op, SelectionDAG &DAG) {
1194   SDOperand Chain = Op.getOperand(0);
1195   SDOperand Table = Op.getOperand(1);
1196   SDOperand Index = Op.getOperand(2);
1197
1198   MVT::ValueType PTy = getPointerTy();
1199   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1200   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1201   SDOperand UId =  DAG.getConstant(AFI->createJumpTableUId(), PTy);
1202   SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1203   Table = DAG.getNode(ARMISD::WrapperJT, MVT::i32, JTI, UId);
1204   Index = DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(4, PTy));
1205   SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
1206   bool isPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1207   Addr = DAG.getLoad(isPIC ? (MVT::ValueType)MVT::i32 : PTy,
1208                      Chain, Addr, NULL, 0);
1209   Chain = Addr.getValue(1);
1210   if (isPIC)
1211     Addr = DAG.getNode(ISD::ADD, PTy, Addr, Table);
1212   return DAG.getNode(ARMISD::BR_JT, MVT::Other, Chain, Addr, JTI, UId);
1213 }
1214
1215 static SDOperand LowerFP_TO_INT(SDOperand Op, SelectionDAG &DAG) {
1216   unsigned Opc =
1217     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1218   Op = DAG.getNode(Opc, MVT::f32, Op.getOperand(0));
1219   return DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
1220 }
1221
1222 static SDOperand LowerINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
1223   MVT::ValueType VT = Op.getValueType();
1224   unsigned Opc =
1225     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1226
1227   Op = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Op.getOperand(0));
1228   return DAG.getNode(Opc, VT, Op);
1229 }
1230
1231 static SDOperand LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
1232   // Implement fcopysign with a fabs and a conditional fneg.
1233   SDOperand Tmp0 = Op.getOperand(0);
1234   SDOperand Tmp1 = Op.getOperand(1);
1235   MVT::ValueType VT = Op.getValueType();
1236   MVT::ValueType SrcVT = Tmp1.getValueType();
1237   SDOperand AbsVal = DAG.getNode(ISD::FABS, VT, Tmp0);
1238   SDOperand Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG);
1239   SDOperand ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1240   SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1241   return DAG.getNode(ARMISD::CNEG, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1242 }
1243
1244 SDOperand ARMTargetLowering::LowerMEMCPYInline(SDOperand Chain,
1245                                                SDOperand Dest,
1246                                                SDOperand Source,
1247                                                unsigned Size,
1248                                                unsigned Align,
1249                                                SelectionDAG &DAG) {
1250   // Do repeated 4-byte loads and stores. To be improved.
1251   assert((Align & 3) == 0 && "Expected 4-byte aligned addresses!");
1252   unsigned BytesLeft = Size & 3;
1253   unsigned NumMemOps = Size >> 2;
1254   unsigned EmittedNumMemOps = 0;
1255   unsigned SrcOff = 0, DstOff = 0;
1256   MVT::ValueType VT = MVT::i32;
1257   unsigned VTSize = 4;
1258   unsigned i = 0;
1259   const unsigned MAX_LOADS_IN_LDM = 6;
1260   SDOperand TFOps[MAX_LOADS_IN_LDM];
1261   SDOperand Loads[MAX_LOADS_IN_LDM];
1262
1263   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1264   // same number of stores.  The loads and stores will get combined into
1265   // ldm/stm later on.
1266   while (EmittedNumMemOps < NumMemOps) {
1267     for (i = 0;
1268          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1269       Loads[i] = DAG.getLoad(VT, Chain,
1270                              DAG.getNode(ISD::ADD, MVT::i32, Source,
1271                                          DAG.getConstant(SrcOff, MVT::i32)),
1272                              NULL, 0);
1273       TFOps[i] = Loads[i].getValue(1);
1274       SrcOff += VTSize;
1275     }
1276     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1277
1278     for (i = 0;
1279          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1280       TFOps[i] = DAG.getStore(Chain, Loads[i],
1281                            DAG.getNode(ISD::ADD, MVT::i32, Dest, 
1282                                        DAG.getConstant(DstOff, MVT::i32)),
1283                            NULL, 0);
1284       DstOff += VTSize;
1285     }
1286     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1287
1288     EmittedNumMemOps += i;
1289   }
1290
1291   if (BytesLeft == 0) 
1292     return Chain;
1293
1294   // Issue loads / stores for the trailing (1 - 3) bytes.
1295   unsigned BytesLeftSave = BytesLeft;
1296   i = 0;
1297   while (BytesLeft) {
1298     if (BytesLeft >= 2) {
1299       VT = MVT::i16;
1300       VTSize = 2;
1301     } else {
1302       VT = MVT::i8;
1303       VTSize = 1;
1304     }
1305
1306     Loads[i] = DAG.getLoad(VT, Chain,
1307                            DAG.getNode(ISD::ADD, MVT::i32, Source,
1308                                        DAG.getConstant(SrcOff, MVT::i32)),
1309                            NULL, 0);
1310     TFOps[i] = Loads[i].getValue(1);
1311     ++i;
1312     SrcOff += VTSize;
1313     BytesLeft -= VTSize;
1314   }
1315   Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1316
1317   i = 0;
1318   BytesLeft = BytesLeftSave;
1319   while (BytesLeft) {
1320     if (BytesLeft >= 2) {
1321       VT = MVT::i16;
1322       VTSize = 2;
1323     } else {
1324       VT = MVT::i8;
1325       VTSize = 1;
1326     }
1327
1328     TFOps[i] = DAG.getStore(Chain, Loads[i],
1329                             DAG.getNode(ISD::ADD, MVT::i32, Dest, 
1330                                         DAG.getConstant(DstOff, MVT::i32)),
1331                             NULL, 0);
1332     ++i;
1333     DstOff += VTSize;
1334     BytesLeft -= VTSize;
1335   }
1336   return DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1337 }
1338
1339 static SDNode *ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1340   // Turn f64->i64 into FMRRD.
1341   assert(N->getValueType(0) == MVT::i64 &&
1342          N->getOperand(0).getValueType() == MVT::f64);
1343   
1344   SDOperand Op = N->getOperand(0);
1345   SDOperand Cvt = DAG.getNode(ARMISD::FMRRD, DAG.getVTList(MVT::i32, MVT::i32),
1346                               &Op, 1);
1347   
1348   // Merge the pieces into a single i64 value.
1349   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Cvt, Cvt.getValue(1)).Val;
1350 }
1351
1352 static SDNode *ExpandSRx(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST) {
1353   assert(N->getValueType(0) == MVT::i64 &&
1354          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
1355          "Unknown shift to lower!");
1356   
1357   // We only lower SRA, SRL of 1 here, all others use generic lowering.
1358   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
1359       cast<ConstantSDNode>(N->getOperand(1))->getValue() != 1)
1360     return 0;
1361   
1362   // If we are in thumb mode, we don't have RRX.
1363   if (ST->isThumb()) return 0;
1364   
1365   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
1366   SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
1367                              DAG.getConstant(0, MVT::i32));
1368   SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
1369                              DAG.getConstant(1, MVT::i32));
1370   
1371   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
1372   // captures the result into a carry flag.
1373   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
1374   Hi = DAG.getNode(Opc, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
1375   
1376   // The low part is an ARMISD::RRX operand, which shifts the carry in.
1377   Lo = DAG.getNode(ARMISD::RRX, MVT::i32, Lo, Hi.getValue(1));
1378   
1379   // Merge the pieces into a single i64 value.
1380  return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi).Val;
1381 }
1382
1383
1384 SDOperand ARMTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1385   switch (Op.getOpcode()) {
1386   default: assert(0 && "Don't know how to custom lower this!"); abort();
1387   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
1388   case ISD::GlobalAddress:
1389     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
1390       LowerGlobalAddressELF(Op, DAG);
1391   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
1392   case ISD::CALL:          return LowerCALL(Op, DAG);
1393   case ISD::RET:           return LowerRET(Op, DAG);
1394   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
1395   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
1396   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
1397   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
1398   case ISD::SINT_TO_FP:
1399   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
1400   case ISD::FP_TO_SINT:
1401   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
1402   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
1403   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
1404   case ISD::RETURNADDR:    break;
1405   case ISD::FRAMEADDR:     break;
1406   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
1407   case ISD::MEMCPY:        return LowerMEMCPY(Op, DAG);
1408   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1409       
1410       
1411   // FIXME: Remove these when LegalizeDAGTypes lands.
1412   case ISD::BIT_CONVERT:   return SDOperand(ExpandBIT_CONVERT(Op.Val, DAG), 0);
1413   case ISD::SRL:
1414   case ISD::SRA:           return SDOperand(ExpandSRx(Op.Val, DAG,Subtarget),0);
1415   }
1416   return SDOperand();
1417 }
1418
1419
1420 /// ExpandOperationResult - Provide custom lowering hooks for expanding
1421 /// operations.
1422 SDNode *ARMTargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
1423   switch (N->getOpcode()) {
1424   default: assert(0 && "Don't know how to custom expand this!"); abort();
1425   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(N, DAG);
1426   case ISD::SRL:
1427   case ISD::SRA:           return ExpandSRx(N, DAG, Subtarget);
1428   }
1429 }
1430   
1431
1432 //===----------------------------------------------------------------------===//
1433 //                           ARM Scheduler Hooks
1434 //===----------------------------------------------------------------------===//
1435
1436 MachineBasicBlock *
1437 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1438                                            MachineBasicBlock *BB) {
1439   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1440   switch (MI->getOpcode()) {
1441   default: assert(false && "Unexpected instr type to insert");
1442   case ARM::tMOVCCr: {
1443     // To "insert" a SELECT_CC instruction, we actually have to insert the
1444     // diamond control-flow pattern.  The incoming instruction knows the
1445     // destination vreg to set, the condition code register to branch on, the
1446     // true/false values to select between, and a branch opcode to use.
1447     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1448     ilist<MachineBasicBlock>::iterator It = BB;
1449     ++It;
1450
1451     //  thisMBB:
1452     //  ...
1453     //   TrueVal = ...
1454     //   cmpTY ccX, r1, r2
1455     //   bCC copy1MBB
1456     //   fallthrough --> copy0MBB
1457     MachineBasicBlock *thisMBB  = BB;
1458     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1459     MachineBasicBlock *sinkMBB  = new MachineBasicBlock(LLVM_BB);
1460     BuildMI(BB, TII->get(ARM::tBcc)).addMBB(sinkMBB)
1461       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
1462     MachineFunction *F = BB->getParent();
1463     F->getBasicBlockList().insert(It, copy0MBB);
1464     F->getBasicBlockList().insert(It, sinkMBB);
1465     // Update machine-CFG edges by first adding all successors of the current
1466     // block to the new block which will contain the Phi node for the select.
1467     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
1468         e = BB->succ_end(); i != e; ++i)
1469       sinkMBB->addSuccessor(*i);
1470     // Next, remove all successors of the current block, and add the true
1471     // and fallthrough blocks as its successors.
1472     while(!BB->succ_empty())
1473       BB->removeSuccessor(BB->succ_begin());
1474     BB->addSuccessor(copy0MBB);
1475     BB->addSuccessor(sinkMBB);
1476
1477     //  copy0MBB:
1478     //   %FalseValue = ...
1479     //   # fallthrough to sinkMBB
1480     BB = copy0MBB;
1481
1482     // Update machine-CFG edges
1483     BB->addSuccessor(sinkMBB);
1484
1485     //  sinkMBB:
1486     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1487     //  ...
1488     BB = sinkMBB;
1489     BuildMI(BB, TII->get(ARM::PHI), MI->getOperand(0).getReg())
1490       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1491       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1492
1493     delete MI;   // The pseudo instruction is gone now.
1494     return BB;
1495   }
1496   }
1497 }
1498
1499 //===----------------------------------------------------------------------===//
1500 //                           ARM Optimization Hooks
1501 //===----------------------------------------------------------------------===//
1502
1503 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
1504 static SDOperand PerformFMRRDCombine(SDNode *N, 
1505                                      TargetLowering::DAGCombinerInfo &DCI) {
1506   // fmrrd(fmdrr x, y) -> x,y
1507   SDOperand InDouble = N->getOperand(0);
1508   if (InDouble.getOpcode() == ARMISD::FMDRR)
1509     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
1510   return SDOperand();
1511 }
1512
1513 SDOperand ARMTargetLowering::PerformDAGCombine(SDNode *N,
1514                                                DAGCombinerInfo &DCI) const {
1515   switch (N->getOpcode()) {
1516   default: break;
1517   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
1518   }
1519   
1520   return SDOperand();
1521 }
1522
1523
1524 /// isLegalAddressImmediate - Return true if the integer value can be used
1525 /// as the offset of the target addressing mode for load / store of the
1526 /// given type.
1527 static bool isLegalAddressImmediate(int64_t V, MVT::ValueType VT,
1528                                     const ARMSubtarget *Subtarget) {
1529   if (V == 0)
1530     return true;
1531
1532   if (Subtarget->isThumb()) {
1533     if (V < 0)
1534       return false;
1535
1536     unsigned Scale = 1;
1537     switch (VT) {
1538     default: return false;
1539     case MVT::i1:
1540     case MVT::i8:
1541       // Scale == 1;
1542       break;
1543     case MVT::i16:
1544       // Scale == 2;
1545       Scale = 2;
1546       break;
1547     case MVT::i32:
1548       // Scale == 4;
1549       Scale = 4;
1550       break;
1551     }
1552
1553     if ((V & (Scale - 1)) != 0)
1554       return false;
1555     V /= Scale;
1556     return V == (V & ((1LL << 5) - 1));
1557   }
1558
1559   if (V < 0)
1560     V = - V;
1561   switch (VT) {
1562   default: return false;
1563   case MVT::i1:
1564   case MVT::i8:
1565   case MVT::i32:
1566     // +- imm12
1567     return V == (V & ((1LL << 12) - 1));
1568   case MVT::i16:
1569     // +- imm8
1570     return V == (V & ((1LL << 8) - 1));
1571   case MVT::f32:
1572   case MVT::f64:
1573     if (!Subtarget->hasVFP2())
1574       return false;
1575     if ((V & 3) != 0)
1576       return false;
1577     V >>= 2;
1578     return V == (V & ((1LL << 8) - 1));
1579   }
1580 }
1581
1582 /// isLegalAddressingMode - Return true if the addressing mode represented
1583 /// by AM is legal for this target, for a load/store of the specified type.
1584 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
1585                                               const Type *Ty) const {
1586   if (!isLegalAddressImmediate(AM.BaseOffs, getValueType(Ty), Subtarget))
1587     return false;
1588   
1589   // Can never fold addr of global into load/store.
1590   if (AM.BaseGV) 
1591     return false;
1592   
1593   switch (AM.Scale) {
1594   case 0:  // no scale reg, must be "r+i" or "r", or "i".
1595     break;
1596   case 1:
1597     if (Subtarget->isThumb())
1598       return false;
1599     // FALL THROUGH.
1600   default:
1601     // ARM doesn't support any R+R*scale+imm addr modes.
1602     if (AM.BaseOffs)
1603       return false;
1604     
1605     int Scale = AM.Scale;
1606     switch (getValueType(Ty)) {
1607     default: return false;
1608     case MVT::i1:
1609     case MVT::i8:
1610     case MVT::i32:
1611     case MVT::i64:
1612       // This assumes i64 is legalized to a pair of i32. If not (i.e.
1613       // ldrd / strd are used, then its address mode is same as i16.
1614       // r + r
1615       if (Scale < 0) Scale = -Scale;
1616       if (Scale == 1)
1617         return true;
1618       // r + r << imm
1619       return isPowerOf2_32(Scale & ~1);
1620     case MVT::i16:
1621       // r + r
1622       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
1623         return true;
1624       return false;
1625       
1626     case MVT::isVoid:
1627       // Note, we allow "void" uses (basically, uses that aren't loads or
1628       // stores), because arm allows folding a scale into many arithmetic
1629       // operations.  This should be made more precise and revisited later.
1630       
1631       // Allow r << imm, but the imm has to be a multiple of two.
1632       if (AM.Scale & 1) return false;
1633       return isPowerOf2_32(AM.Scale);
1634     }
1635     break;
1636   }
1637   return true;
1638 }
1639
1640
1641 static bool getIndexedAddressParts(SDNode *Ptr, MVT::ValueType VT,
1642                                    bool isSEXTLoad, SDOperand &Base,
1643                                    SDOperand &Offset, bool &isInc,
1644                                    SelectionDAG &DAG) {
1645   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
1646     return false;
1647
1648   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
1649     // AddressingMode 3
1650     Base = Ptr->getOperand(0);
1651     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1652       int RHSC = (int)RHS->getValue();
1653       if (RHSC < 0 && RHSC > -256) {
1654         isInc = false;
1655         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1656         return true;
1657       }
1658     }
1659     isInc = (Ptr->getOpcode() == ISD::ADD);
1660     Offset = Ptr->getOperand(1);
1661     return true;
1662   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
1663     // AddressingMode 2
1664     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1665       int RHSC = (int)RHS->getValue();
1666       if (RHSC < 0 && RHSC > -0x1000) {
1667         isInc = false;
1668         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1669         Base = Ptr->getOperand(0);
1670         return true;
1671       }
1672     }
1673
1674     if (Ptr->getOpcode() == ISD::ADD) {
1675       isInc = true;
1676       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
1677       if (ShOpcVal != ARM_AM::no_shift) {
1678         Base = Ptr->getOperand(1);
1679         Offset = Ptr->getOperand(0);
1680       } else {
1681         Base = Ptr->getOperand(0);
1682         Offset = Ptr->getOperand(1);
1683       }
1684       return true;
1685     }
1686
1687     isInc = (Ptr->getOpcode() == ISD::ADD);
1688     Base = Ptr->getOperand(0);
1689     Offset = Ptr->getOperand(1);
1690     return true;
1691   }
1692
1693   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
1694   return false;
1695 }
1696
1697 /// getPreIndexedAddressParts - returns true by value, base pointer and
1698 /// offset pointer and addressing mode by reference if the node's address
1699 /// can be legally represented as pre-indexed load / store address.
1700 bool
1701 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
1702                                              SDOperand &Offset,
1703                                              ISD::MemIndexedMode &AM,
1704                                              SelectionDAG &DAG) {
1705   if (Subtarget->isThumb())
1706     return false;
1707
1708   MVT::ValueType VT;
1709   SDOperand Ptr;
1710   bool isSEXTLoad = false;
1711   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1712     Ptr = LD->getBasePtr();
1713     VT  = LD->getMemoryVT();
1714     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
1715   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1716     Ptr = ST->getBasePtr();
1717     VT  = ST->getMemoryVT();
1718   } else
1719     return false;
1720
1721   bool isInc;
1722   bool isLegal = getIndexedAddressParts(Ptr.Val, VT, isSEXTLoad, Base, Offset,
1723                                         isInc, DAG);
1724   if (isLegal) {
1725     AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
1726     return true;
1727   }
1728   return false;
1729 }
1730
1731 /// getPostIndexedAddressParts - returns true by value, base pointer and
1732 /// offset pointer and addressing mode by reference if this node can be
1733 /// combined with a load / store to form a post-indexed load / store.
1734 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1735                                                    SDOperand &Base,
1736                                                    SDOperand &Offset,
1737                                                    ISD::MemIndexedMode &AM,
1738                                                    SelectionDAG &DAG) {
1739   if (Subtarget->isThumb())
1740     return false;
1741
1742   MVT::ValueType VT;
1743   SDOperand Ptr;
1744   bool isSEXTLoad = false;
1745   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1746     VT  = LD->getMemoryVT();
1747     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
1748   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1749     VT  = ST->getMemoryVT();
1750   } else
1751     return false;
1752
1753   bool isInc;
1754   bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
1755                                         isInc, DAG);
1756   if (isLegal) {
1757     AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
1758     return true;
1759   }
1760   return false;
1761 }
1762
1763 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
1764                                                        const APInt &Mask,
1765                                                        APInt &KnownZero, 
1766                                                        APInt &KnownOne,
1767                                                        const SelectionDAG &DAG,
1768                                                        unsigned Depth) const {
1769   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1770   switch (Op.getOpcode()) {
1771   default: break;
1772   case ARMISD::CMOV: {
1773     // Bits are known zero/one if known on the LHS and RHS.
1774     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1775     if (KnownZero == 0 && KnownOne == 0) return;
1776
1777     APInt KnownZeroRHS, KnownOneRHS;
1778     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
1779                           KnownZeroRHS, KnownOneRHS, Depth+1);
1780     KnownZero &= KnownZeroRHS;
1781     KnownOne  &= KnownOneRHS;
1782     return;
1783   }
1784   }
1785 }
1786
1787 //===----------------------------------------------------------------------===//
1788 //                           ARM Inline Assembly Support
1789 //===----------------------------------------------------------------------===//
1790
1791 /// getConstraintType - Given a constraint letter, return the type of
1792 /// constraint it is for this target.
1793 ARMTargetLowering::ConstraintType
1794 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
1795   if (Constraint.size() == 1) {
1796     switch (Constraint[0]) {
1797     default:  break;
1798     case 'l': return C_RegisterClass;
1799     case 'w': return C_RegisterClass;
1800     }
1801   }
1802   return TargetLowering::getConstraintType(Constraint);
1803 }
1804
1805 std::pair<unsigned, const TargetRegisterClass*> 
1806 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1807                                                 MVT::ValueType VT) const {
1808   if (Constraint.size() == 1) {
1809     // GCC RS6000 Constraint Letters
1810     switch (Constraint[0]) {
1811     case 'l':
1812     // FIXME: in thumb mode, 'l' is only low-regs.
1813     // FALL THROUGH.
1814     case 'r':
1815       return std::make_pair(0U, ARM::GPRRegisterClass);
1816     case 'w':
1817       if (VT == MVT::f32)
1818         return std::make_pair(0U, ARM::SPRRegisterClass);
1819       if (VT == MVT::f64)
1820         return std::make_pair(0U, ARM::DPRRegisterClass);
1821       break;
1822     }
1823   }
1824   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1825 }
1826
1827 std::vector<unsigned> ARMTargetLowering::
1828 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1829                                   MVT::ValueType VT) const {
1830   if (Constraint.size() != 1)
1831     return std::vector<unsigned>();
1832
1833   switch (Constraint[0]) {      // GCC ARM Constraint Letters
1834   default: break;
1835   case 'l':
1836   case 'r':
1837     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
1838                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
1839                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
1840                                  ARM::R12, ARM::LR, 0);
1841   case 'w':
1842     if (VT == MVT::f32)
1843       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
1844                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
1845                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
1846                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
1847                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
1848                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
1849                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
1850                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
1851     if (VT == MVT::f64)
1852       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
1853                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
1854                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
1855                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
1856       break;
1857   }
1858
1859   return std::vector<unsigned>();
1860 }