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