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