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