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