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